91 lines
1.9 KiB
C
Raw Normal View History

2013-08-29 11:45:22 +09:00
/*
Copyright (c) 2013 yvt
2013-08-29 11:45:22 +09:00
This file is part of OpenSpades.
2013-08-29 11:45:22 +09:00
OpenSpades is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
2013-08-29 11:45:22 +09:00
OpenSpades is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
2013-08-29 11:45:22 +09:00
You should have received a copy of the GNU General Public License
along with OpenSpades. If not, see <http://www.gnu.org/licenses/>.
2013-08-29 11:45:22 +09:00
*/
2013-08-18 16:18:06 +09:00
#pragma once
#include <cstdio>
#include <cstdlib>
#include <Core/Debug.h>
2013-08-18 16:18:06 +09:00
namespace spades {
/** Deque implementation. NPOT is not fully supported. */
template <typename T> class Deque {
2013-08-18 16:18:06 +09:00
T *ptr;
size_t length;
size_t startPos;
size_t capacity;
2013-08-18 16:18:06 +09:00
public:
Deque(size_t cap) {
ptr = (T *)malloc(sizeof(T) * cap);
startPos = 0;
length = 0;
capacity = cap;
}
~Deque() { free(ptr); }
2013-08-18 16:18:06 +09:00
void Reserve(size_t newCap) {
if (newCap <= capacity)
2013-08-18 16:18:06 +09:00
return;
T *newPtr = (T *)malloc(sizeof(T) * newCap);
size_t pos = startPos;
for (size_t i = 0; i < length; i++) {
2013-08-18 16:18:06 +09:00
newPtr[i] = ptr[pos++];
if (pos == capacity)
2013-08-18 16:18:06 +09:00
pos = 0;
}
free(ptr);
ptr = newPtr;
2013-08-18 16:18:06 +09:00
startPos = 0;
capacity = newCap;
}
void Push(const T &e) {
if (length + 1 > capacity) {
2013-08-18 16:18:06 +09:00
size_t newCap = capacity;
while (newCap < length + 1)
2013-08-18 16:18:06 +09:00
newCap <<= 1;
Reserve(newCap);
}
size_t pos = startPos + length;
if (pos >= capacity)
pos -= capacity;
2013-08-18 16:18:06 +09:00
ptr[pos] = e;
length++;
}
T &Front() { return ptr[startPos]; }
2013-08-18 16:18:06 +09:00
void Shift() {
SPAssert(length > 0);
startPos++;
if (startPos == capacity)
startPos = 0;
2013-08-18 16:18:06 +09:00
length--;
}
size_t GetLength() const { return length; }
bool IsEmpty() const { return length == 0; }
2013-08-18 16:18:06 +09:00
};
}