Skip to content

Instantly share code, notes, and snippets.

@Bigfoot71
Created November 20, 2023 00:24
Show Gist options
  • Select an option

  • Save Bigfoot71/2022fdb944e80bade05dc4c008cb4ea7 to your computer and use it in GitHub Desktop.

Select an option

Save Bigfoot71/2022fdb944e80bade05dc4c008cb4ea7 to your computer and use it in GitHub Desktop.
// This code is distributed under the Unlicense license.
// For more details, please visit https://unlicense.org/
template <class T>
class CircularBuffer
{
private:
std::unique_ptr<T[]> buffer;
size_t frontIndex;
size_t backIndex;
size_t maxSize;
size_t count;
public:
CircularBuffer(size_t maxSize)
: buffer(std::make_unique<T[]>(maxSize))
, frontIndex(0), backIndex(0)
, maxSize(maxSize), count(0) { }
template <typename... Args>
void emplace(Args&&... args)
{
if (full()) throw std::overflow_error("Queue is full.");
buffer[backIndex] = T(std::forward<Args>(args)...);
backIndex = (backIndex + 1) % maxSize;
count++;
}
void push(T&& item)
{
if (full()) throw std::overflow_error("Queue is full.");
buffer[backIndex] = std::move(item);
backIndex = (backIndex + 1) % maxSize;
count++;
}
void pop()
{
if (empty()) throw std::underflow_error("Queue is empty.");
frontIndex = (frontIndex + 1) % maxSize;
count--;
}
T& front() const
{
if (empty()) throw std::underflow_error("Queue is empty.");
return buffer[frontIndex];
}
T& back() const
{
if (empty()) throw std::underflow_error("Queue is empty.");
return buffer[(backIndex - 1 + maxSize) % maxSize];
}
bool empty() const noexcept { return count == 0; }
bool full() const noexcept { return count == maxSize; }
size_t size() const noexcept { return count; }
size_t capacity() const noexcept { return maxSize; }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment