lpcware

Ring buffer size must be power of 2

Discussion created by lpcware Employee on Jun 15, 2016
Latest reply on Jun 15, 2016 by lpcware
Content originally posted in LPCWare by kmdewaal on Thu Aug 06 08:19:24 MST 2015
The ring buffer code in lpc_chip_43xx/src/ring_buffer.c only works correct if the buffer size is a power of 2.

The reason for this is the way the position of the head and the tail of the ring buffer are computed.
This is done with a logical AND computation in the following macro's:
#define RB_INDH(rb)                ((rb)->head & ((rb)->count - 1))
#define RB_INDT(rb)                ((rb)->tail & ((rb)->count - 1))

When the ring buffer size is a power of 2 this is fast way of computing the modulus.
However, this does NOT work when the buffer size is NOT a power of 2.

Instead of a logcal AND it is better to do a modulo computation that works with all buffer sizes:
#define RB_INDH(rb)                ((rb)->head % (rb)->count)
#define RB_INDT(rb)                ((rb)->tail % (rb)->count)


Note that the logical AND computation can be faster, depending on the processor.



Outcomes