diff --git a/include/queue.h b/include/queue.h index f614070..904f91a 100644 --- a/include/queue.h +++ b/include/queue.h @@ -34,7 +34,7 @@ public: std::expected peek(); - std::expected unqueue(); + std::expected dequeue(); void display(); }; @@ -89,5 +89,62 @@ QueueErr Queue::enqueue(T value) { this->data[this->head] = value; this->len++; this->head = (this->head + 1) % this->cap; + return QueueErr::ok; +} + +template +requires std::formattable +std::expected Queue::dequeue() { + if (this->len == 0) { + return std::unexpected(QueueErr::empty); + } + + if (this->cap > DEFAULT_QUEUE_SIZE && this->cap / 4 > this->len) { + uint64_t new_cap = this->cap / 2; + if (new_cap < DEFAULT_QUEUE_SIZE) { + new_cap = DEFAULT_QUEUE_SIZE; + } + + T *tmp; + try { + tmp = new T[new_cap]; + } catch(const std::bad_alloc& e) { + return std::unexpected(QueueErr::bad_alloc); + } + + for (uint64_t i = 0; i < this->len; i++) { + uint64_t index = (this->tail) % this->cap; + tmp[i] = this->data[index]; + } + + delete[] this->data; + this->data = tmp; + this->cap = new_cap; + this->tail = 0; + this->head = this->len; + + } + + T out; + out = this->data[this->tail]; + this->len--; + this->tail = (this->tail + 1) % this->cap; + + return out; +} + +template +requires std::formattable +std::expected Queue::peek() { + if (this->len == 0) { + return std::unexpected(QueueErr::empty); + } + + T out; + out = this->data[this->tail]; + this->len--; + this->tail = (this->tail + 1) % this->cap; + + return out; } #endif // !QUEUE_H