Overview
A ring buffer (circular buffer) is a fixed-size array that wraps around from end to beginning, treating the storage as a continuous loop. It enables efficient first-in-first-out (FIFO) operations without memory allocation, making it essential for audio processing, network packets, and game mechanics like snake body segments.
Fast Facts
| Aspect | Detail |
|---|
| Also called | Circular buffer, cyclic buffer |
| Operations | O(1) read, O(1) write |
| Memory | Fixed, pre-allocated |
| Common uses | Audio, networking, input history |
How It Works
| Pointer | Purpose |
|---|
| Head (write) | Where new data goes |
| Tail (read) | Where old data comes from |
| Wrap | When pointer exceeds size, reset to 0 |
Buffer: [A][B][C][D][E][F][G][H]
^tail ^head
Write X: [X][B][C][D][E][F][G][H]
^tail ^head (wrapped)
Implementation
| Operation | Logic |
|---|
| Write | buffer[head] = value; head = (head + 1) % size |
| Read | value = buffer[tail]; tail = (tail + 1) % size |
| Full | (head + 1) % size == tail |
| Empty | head == tail |
Gaming Applications
Snake Body
| Frame | Head Position | Tail Position |
|---|
| 1 | Write new head | Read (remove) old tail |
| 2 | Write new head | Read old tail |
| Grow | Write new head | Don’t read tail |
The snake’s body is naturally a ring buffer of positions.
| Use | Benefit |
|---|
| Fighting games | Store last N inputs for combos |
| Replays | Record input history |
| Undo systems | Fixed-depth undo stack |
| Ghost racing | Store position history |
Audio
| Application | Why Ring Buffer |
|---|
| Streaming | Producer/consumer decoupling |
| Effects | Delay lines are ring buffers |
| Mixing | Lock-free audio threads |
Vintage Implementation (6502)
On limited hardware, the power-of-two trick avoids division:
| Buffer Size | Wrap Method |
|---|
| 256 bytes | Natural 8-bit overflow |
| 128 bytes | AND #$7F |
| 64 bytes | AND #$3F |
Using AND instead of modulo is much faster.
Modern Applications
| System | Usage |
|---|
| FMOD/Wwise | Audio streaming buffers |
| TCP/IP stacks | Packet receive buffers |
| GGPO (rollback) | Input history for netcode |
| Logging | Circular log files |
Lock-Free Benefits
Ring buffers enable lock-free producer/consumer patterns:
- Audio thread writes, main thread reads
- Network thread writes, game thread reads
- No mutexes needed with single producer/consumer
Trade-offs
| Advantage | Disadvantage |
|---|
| No allocation | Fixed maximum size |
| O(1) operations | Can overflow if full |
| Cache-friendly | Must handle wrap-around |
| Lock-free possible | Power-of-two size optimal |
Legacy
Ring buffers appear everywhere in systems programming. Understanding them connects game development to audio engineering, networking, and operating systems—fundamental computer science in action.
See Also