Skip to content

Instantly share code, notes, and snippets.

@ar1a
Created May 25, 2016 07:40
Show Gist options
  • Save ar1a/248bce798296131f70ad5447e01f44dd to your computer and use it in GitHub Desktop.
Save ar1a/248bce798296131f70ad5447e01f44dd to your computer and use it in GitHub Desktop.
Templated Circular Buffer in C++
#ifndef __CBUFFER_HPP
#define __CBUFFER_HPP
#include <memory>
#include <stdexcept>
template <typename T>
class Circular_buffer
{
public:
/**
* @param size Wanted size of buffer
*/
Circular_buffer(size_t size) : size(size), front(0), count(0)
{
if (size == 0) throw std::invalid_argument("size cannot be 0");
data = std::unique_ptr<T>(new T[size]);
}
/**
* @return True if empty
*/
bool empty() { return count == 0; }
/**
* @return True if full
*/
bool full() { return count == size; }
/**
* @param Item wanted to add to the buffer
* @return True if successful, false if the buffer is full.
*/
bool add(const T& t)
{
if (full()) return false;
int end = (front + count++) % size;
data.get()[end] = t;
// c u cked yea nigger lol
return true;
}
/**
* @param OUT Item you removed off the stack
* @return True if successful, false if the buffer is empty.
*/
bool remove(T& t)
{
if (empty()) return false;
t = std::forward(data.get()[front]);
front = front >= size ? 0 : front + 1;
--count;
return true;
}
private:
const size_t size;
std::unique_ptr<T> data;
size_t front;
size_t count;
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment