Skip to content

Instantly share code, notes, and snippets.

@harshkn
Created April 8, 2011 09:26
Show Gist options
  • Save harshkn/909546 to your computer and use it in GitHub Desktop.
Save harshkn/909546 to your computer and use it in GitHub Desktop.
C Implementation of simple circular buffer, Functionality provided are add to queue, read latest
typedef struct circular_buffer
{
void *buffer; // data buffer
void *buffer_end; // end of data buffer
size_t capacity; // maximum number of items in the buffer
size_t count; // number of items in the buffer
size_t sz; // size of each item in the buffer
void *head; // pointer to head
void *tail; // pointer to tail
} circular_buffer;
void cb_init(circular_buffer *cb, size_t capacity, size_t sz)
{
cb->buffer = malloc(capacity * sz);
if(cb->buffer == NULL)
// handle error
cb->buffer_end = (char *)cb->buffer + capacity * sz;
cb->capacity = capacity;
cb->count = 0;
cb->sz = sz;
cb->head = cb->buffer;
cb->tail = cb->buffer;
}
void cb_free(circular_buffer *cb)
{
free(cb->buffer);
// clear out other fields too, just to be safe
}
void cb_push_back(circular_buffer *cb, const void *item)
{
if(cb->count == cb->capacity)
// handle error
memcpy(cb->head, item, cb->sz);
cb->head = (char*)cb->head + cb->sz;
if(cb->head == cb->buffer_end)
cb->head = cb->buffer;
cb->count++;
}
void cb_pop_front(circular_buffer *cb, void *item)
{
if(cb->count == 0)
// handle error
memcpy(item, cb->tail, cb->sz);
cb->tail = (char*)cb->tail + cb->sz;
if(cb->tail == cb->buffer_end)
cb->tail = cb->buffer;
cb->count--;
}
@mofosyne
Copy link

Thanks for the paste. It helped me to understand circular buffer better.
I've rewritten your approach as a simplified circular buffer byte buffer without malloc (intended for embedded purpose), using both pointer and array index approaches. Also used static inline declaration to be used in a header for ease of inclusion (Don't want the function call overhead anyway):

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment