A ring buffer (circular queue) joins head and tail: read/write cursors advance around a fixed slice instead of shifting elements on every dequeue.
The payoff: after a dequeue you do not slide the rest of the queue forward; the next enqueue overwrites the freed slot.
Below is a common pattern—separate read/write counters—with a diagram-friendly walkthrough. Code is adapted from chanx ringbuffer.
Counter-based implementation
Skim the code first; a picture afterward makes the flow obvious.
Data layout:
1 | type T interface{} |
Reads:
1 | // Empty when read and write cursors meet |
Writes:
1 | func (r *RingBuffer) Write(v T) { |
Growth:
1 | func (r *RingBuffer) grow() { |
The figure below walks through a concrete example:

Another classic approach uses mirror index bits instead of growing.
Mirror index implementation
If the buffer length is n, logical indices are 0…n−1; indices n…2n−1 mirror that space. Read and write pointers live in 0…2n−1: the low half is the real buffer, the high half is the mirror. When a pointer reaches ≥2n, wrap with
ptr − 2n. One bit records whether the pointer is in the mirror region.
From Wikipedia — circular buffer (mirror solution)
Counters may lap the buffer twice (up to 2n−1). “Full” used to mean r == w after wrap-to-zero; with mirroring, full is w == r + n before resetting.
Illustration:

When capacity is a power of two, a bitwise test checks whether the gap is exactly n:
1 | func (r *RingBuffer) IsFull() bool { |
Index and advance can use masks instead of %:
1 | // Index |
Full code: ringbuffer-mirror.
Questions? Leave a comment below or email: newbvirgil@gmail.com![]()
