Ring buffer size must be power of 2

cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Ring buffer size must be power of 2

1,764 Views
lpcware
NXP Employee
NXP Employee
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.



Labels (1)
0 Kudos
3 Replies

1,187 Views
lpcware
NXP Employee
NXP Employee
Content originally posted in LPCWare by starblue on Sat Aug 08 03:15:01 MST 2015
If the modulus is a constant power of two and the operands are unsigned then the compiler should use AND.  (For signed operands a small correction is needed for negative numbers.)
0 Kudos

1,187 Views
lpcware
NXP Employee
NXP Employee
Content originally posted in LPCWare by wmues on Fri Aug 07 02:22:30 MST 2015
Sorry, this is no AND.
It's a MODULO operation. This is the remainder of a division.
And a division is a slow operation.
0 Kudos

1,187 Views
lpcware
NXP Employee
NXP Employee
Content originally posted in LPCWare by kmdewaal on Fri Aug 07 01:04:55 MST 2015
Correction: it is of course a bitwise AND, not a logical AND.
0 Kudos