Small RingQueue for embedded program (e.g. Arduino, AVR, mbed etc.
#ifndef __RINGQUEUE_H__
#define __RINGQUEUE_H__
#define DEFAULT_MAX_SIZE 16
template<typename T>
class RingQueue
{
public:
RingQueue(unsigned int size = DEFAULT_MAX_SIZE)
: mMaxSize(size)
{
mHead = mTail = 0;
mQueue = new T[mMaxSize];
};
~RingQueue() { delete[] mQueue; };
int size() { return (mTail-mHead); };
bool empty() { return !(mTail-mHead); };
void clear() { mHead = 0; mTail = 0; };
void pop() { mHead++; };
void push(T data)
{
mQueue[(mTail++)%mMaxSize] = data;
if (size() >= mMaxSize) mHead++;
else if (size() < 0) clear();
};
T& front()
{
return *(empty() ? NULL : mQueue+mHead%mMaxSize);
};
T& back()
{
return *(empty() ? NULL : mQueue+(mTail-1)%mMaxSize);
}
private:
volatile unsigned int mHead;
volatile unsigned int mTail;
const unsigned int mMaxSize;
T* mQueue;
};
#endif // __RINGQUEUE_H__