![]() |
ring
1.1
A Flexible Ring Buffer in C.
|
This ring buffer can contain elements of any size. Multiple ring buffers can be used in the same project. This ring buffer uses a struct with information about the ring buffer. The compleet ring buffer is descripted in this header file. There is no accompanying c file. All functions are static inline functions.
For ring buffers containing char's some extra functionality is added. E.g. a function ringGetLine() to read a line (text ending with a \n) from the ring buffer.
A small example how to use this ringbuffer in an application is:
#include <stdio.h> #include "ring.h" #define BUFFERSIZE 100 int main(void) { int square, data, count; // Create the ring buffer with BUFFERSIZE elements of integers ring_t *pRing = ringCreate(sizeof(int), BUFFERSIZE); // Fill the ring buffer with 16 elements for (int i=0; i<16; i++) { square = i * i; ringWrite(pRing, (uint8_t *) (&square)); } count = ringGetCount(pRing); printf("The buffer is filled with %d elements\n", count); // Read 10 elements from the ring buffer for(int i=0; i<10; i++) { ringRead(pRing, (uint8_t *) (&data)); printf("read from buffer: %d\n", data); } count = ringGetCount(pRing); printf("The buffer is now filled with %d elements\n", count); // Read all elements from the ring buffer until it is empty while( ! ringIsEmpty(pRing) ) { ringRead(pRing, (uint8_t *) (&data)); printf("read from buffer: %d\n", data); } count = ringGetCount(pRing); printf("The buffer is now filled with %d elements\n", count); return 0; }
An incomplete example with two ring buffers:
#define COMMBUFFERSIZE 4096 #define RXBUFFERSIZE 4096 #define PXLBUFFERSIZE 4096 #define LINEBUFFERSIZE 256 typedef struct pixel_struct { uint8_t r; uint8_t g; uint8_t b; } pxl_t; char lineBuffer[LINEBUFFERSIZE]; // buffer for a complete packet char commBuffer[COMMBUFFERSIZE]; // buffer for serial communication int main(void) { unsigned int r, g, b; pxl_t wpixel; pxl_t rpixel; ring_t *pRingRx = ringCreate(sizeof(char), RXBUFFERSIZE); ring_t *pRingPxl = ringCreate(sizeof(pxl_t), PXLBUFFERSIZE); // initialize serial communication while(1) { // some code receive serial communication // copy received chars to Rx ring buffer for(int i=0; i<len; i++) { // len is number of receivedd characters ringWrite(pRingRx, &commBuffer[i]); } // copy pixel packets from Rx ring buffer to Pxl ring buffer while (ringGetLine(pRingRx, (uint8_t *) lineBuffer) ) { sscanf(lineBuffer, "%u;%u;%u", &r, &g, &b); wpixel.r = r/8; wpixel.g = g/8; wpixel.b = b/8; ringWrite(pRingPxl, (uint8_t *) (&wpixel)); } // read and print pixel packets from Pxl ring buffer if (! ringIsEmpty(pRingPxl) ) { ringRead(pRingPxl, (uint8_t *) (&rpixel)); printf("(%u %u %u)\n", rpixel.r, rpixel.g, rpixel.b); } } return 0; }
This library is free software. You can redistribute it and/or modify it. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.