Implement a circular list /array (ring buffer) in C

I

A very simple implementation, expressed in C. Implements a simple circular buffer in C as a FIFO queue. Note that this allows queues of any size.

#ifndef CIRCULARBUFFER_H_
#define CIRCULARBUFFER_H_

	typedef struct
	{
		int * data;

		int * first;

		int * next;

		int max;
	}
	cbuffer_t;

	cbuffer_t * cBufferInit(int max);

	int cBufferPush(cbuffer_t *c, int data);

	int cBufferPop(cbuffer_t *c, int *data);

#endif /* CIRCULARBUFFER_H_ */
#include "CircularBuffer.h"

cbuffer_t * cBufferInit(int max)
{
	cbuffer_t * buffer = (cbuffer_t*)malloc(sizeof(cbuffer_t));

	buffer->data = (int*)malloc(max * sizeof(int));

	buffer->first = (int*)0;

	buffer->next = buffer->data;

	buffer->max = max;

	return buffer;
}

int cBufferPush(cbuffer_t *buffer, int 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 == (int*)0 ? buffer->next : buffer->first;

	buffer->next = buffer->next + 1 == buffer->data + buffer->max ? buffer->data : buffer->next + 1;

	return 0;
}

int cBufferPop(cbuffer_t *buffer, int *data)
{
	if (buffer->first == (int*)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 ? (int*)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