A Ring Buffer by Indices

A ring buffer uses fixed storage and wraps logical positions back to the beginning of its physical array.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Trace a three-slot example
  2. Disambiguate full and empty
  3. Use a count to distinguish identical boundary indices
  4. Choose one full-state representation

Trace a three-slot example

With head at two and two stored elements, their physical positions are two and zero. The next free position is one. Taking the remainder of an advancing offset by positive capacity implements the wrap. See quotient and remainder.

Disambiguate full and empty

If head and tail may have equal indices for both states, track size, use a dedicated flag, or reserve one slot under the contract. A FIFO queue defines the expected logical removal order even when physical indices wrap.[1]

Use a count to distinguish identical boundary indices

In a capacity-four buffer with head at three and count two, occupied entries lie at positions three and zero. The next write occurs at position one because \((3+2)\bmod4=1\). A numeric order of occupied indices would display them in the wrong queue order. See rotating a sequence.

Head=3, count=2, capacity=4
Logical order: indices 3, 0
Write at 1: count becomes 3
Remove at 3: head becomes 0, count becomes 2
Logical order now: indices 0, 1

Choose one full-state representation

With head and next-write indices alone, their equality can indicate both empty and full. Store a count, add a flag, or deliberately reserve one slot. Test the wraparound at capacity and again after draining every item.

References

  1. Jeff Erickson, Algorithms ↩