|
|
|
|
|
by properparity
1493 days ago
|
|
Not necessarily divisible, but requires power of 2 bufsize with this code (but you probably want that anyway to avoid division). With non-power-2 bufsize you need some extra logic for write/readix++, but the rest of the code can stay the same. |
|
If bufsize is a power of 2, doing the modulo would be exactly the same as just using a smaller integer type (like 8 bits on a microcontroller). What we want is the integer wraparound to never coincide with the buffer position wrapping. For that we would need a size that has some other factor than 2, and thus a "real" modulo operation in the indexing (which is slow).
Or is there an error in my thinking?
edit: Duh, I understand now. If the counter has at least twice the range as the buffer size, the subtraction will always give the correct number of elements used. Power of 2 or not doesn't matter.
Not having to do the subtraction could still give a performance benefit, and if the buffer elements aren't very large, one wasted slot is worth the tradeoff.