Improved circular list /array (ring buffer) in C++

I

This is a new version of the ring buffer. Using function templates the FIFO ring buffer is able to handle almost any type of data.

template<typename T> struct cbuffer_t
{
   T * data; 
   T * first;
   T * next;
   int max;
};


template<typename T> extern cbuffer_t<T> * cBufferInit(int);
 
template<typename T> extern int cBufferPush(cbuffer_t<T> *, T );
 
template<typename T> extern int cBufferPop(cbuffer_t<T> *, T *);



template<typename T> cbuffer_t<T> *  cBufferInit(int max)
{
   cbuffer_t<T> * buffer = (cbuffer_t<T>*)malloc(sizeof(cbuffer_t<T>));
	 
   buffer->data = (T*)malloc(max * sizeof(T));
	 
   buffer->first = (T*)0;
	 
   buffer->next = buffer->data;
	 
   buffer->max = max;
	 
   return buffer;
}
	 

template<typename T> int cBufferPush(cbuffer_t<T> *buffer, T data)
{
   int x = (int)(buffer->next - buffer->first);
	 
   if (buffer->first == buffer->next || buffer->next - buffer->first == buffer->max)
	 
      return -1;
	 
   *buffer->next = data;
	 
   buffer->first = buffer->first == (T*)0 ? buffer->next : buffer->first;
	 
   buffer->next = buffer->next + 1 == buffer->data + buffer->max ? buffer->data : buffer->next + 1;
	 
   return 0;
}
	
 	 
template<typename T> int cBufferPop(cbuffer_t<T> *buffer, T *data)
{
   if (buffer->first == (T*)0)	 

      return -1;

   *data = *buffer->first;

   buffer->first = buffer->first + 1 == buffer->data + buffer->max ? buffer->data : buffer->first + 1;
   
   buffer->first = buffer->first == buffer->next ? (T*)0 : buffer->first;
	 
   return 0;
}

Disclaimer: The present content may not be used for training artificial intelligence or machine learning algorithms. All other uses, including search, entertainment, and commercial use, are permitted.

Categories

Tags