SimpleLib

Ring Buffer Class

CRingBuffer implements a circular buffer of elements, implemented as an allocated block of memory for the element data with a read and write position. It also maintains a count of the number of elements and supports SimpleLib's semantics classes.

CRingBuffer is safe for use as single reader/single writer lock free queue in multi-threaded situations.

template <class T, class TSem=SValue>
class CRingBuffer;

When constructing a ring buffer you must specify the buffer capacity as a parameter:

// A circular buffer of 100 integers
CRingBuffer<int> buf(100);

To add items to the buffer, use the Enqueue method:

buf.Enqueue(100);
buf.Enqueue(200);

To read from the buffer use the Dequeue method:

int iVal;
while (buf.Dequeue(iBuffer))
{
	// process iVal
}

Dequeue comes in two flavours - the above version which returns a boolean if something is available and the following version which returns the value but asserts if the buffer is empty:

while (!buf.IsEmpty())
{
	printf("%i\n", buf.Dequeue());
}

Although uncommon, it's possible to iterate over the buffer's contents (note: buf[0] returns the first enqueued item)

for (int i=0; i<buf.GetSize(); i++)
{
	printf("%i\n", buf[i]);
}

You can check the state of the buffer with IsEmpty, IsFull and IsOverflow. IsOverflow is set if an attempt has been made to enqueue more items than are available in the queue. The RemoveAll empties the queue and clears the overflow flag.

Other occasionally useful methods include:

  • Peek - Returns the next item to be dequeued without removing it.
  • PeekLast - Returns the most recently enqueued item.
  • Unenqueue - Removes the most recently enqueued item.
  • Reset - Empties the buffer and optionally resizes the capacity of the buffer.
  • GetCapacity - Returns the capacity of the buffer.