B
Ben Collingsworth
Anyone have some efficient source code for implementing a ring buffer?
Ben said:Anyone have some efficient source code for implementing a ring buffer?
Anyone have some efficient source code for implementing a ring buffer?
Ben said:Anyone have some efficient source code for implementing a ring buffer?
Anyone have some efficient source code for implementing a ring buffer?
Nick Austin said:Anyone have some efficient source code for implementing a ring buffer?
There are several ways to implement a ring-buffer, depending on
how easy you want to make the tests for buffer empty/full. The
usual way I do it (without optimisations) is:
static unsigned char ringbuffer[ 256 ];
static unsigned short getindex = 0;
static unsigned short putindex = 0;
static unsigned short buffersize = 0;
int putring( char c )
{
if ( buffersize >= sizeof ringbuffer )
return -1;
ringbuffer[ putindex ] = c;
putindex++;
if ( putindex >= sizeof ringbuffer )
putindex = 0;
Now, to make it faster.
If the size of the ring buffer is always a power-of-two you can
use masking to make the index variables wrap-around. For example
the increment and test for wrap-around becomes:
putindex = ( putindex++ ) & 0xFF;
If you have suitable compiler-extensions then force the start
address of the ring buffer to an alignment that is the same
as its size. That is for a 256-byte buffer it should be
aligned on a 256-byte boundary.
The indexing can then be replaced by pointers:
static char *putpointer = ringbuffer;
*putpointer = c;
putpointer = ( putpointer++ ) & ~0xFF;
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.