Search code examples
c++circular-buffer

Simplified algorithm for calculating remaining space in a circular buffer?


I was wonder if there is a simpler (single) way to calculate the remaining space in a circular buffer than this?

int remaining = (end > start)
                ? end-start
                : bufferSize - start + end;

Solution

  • If you're worried about poorly-predicted conditionals slowing down your CPU's pipeline, you could use this:

    int remaining = (end - start) + (-((int) (end <= start)) & bufferSize);
    

    But that's likely to be premature optimisation (unless you have really identified this as a hotspot). Stick with your current technique, which is much more readable.