← All Exercises
Generic Fixed-Size Ring Buffer
intermediatego
Background
Ring buffers provide bounded memory for streaming data and recent-history views; modular indexing avoids shifting elements on every push.
Problem
Implement RingBuffer[T] with NewRingBuffer(capacity), Push, Len, and Snapshot. Push overwrites the oldest value once full, Len reports stored items, and Snapshot returns a copy from oldest to newest. Reject capacities below one.
Input
A positive capacity and a sequence of values pushed into the buffer.
Output
The current length and a snapshot slice in oldest-to-newest order.
Sample tests
Sample 1
Input: capacity = 3, push 1, 2, 3, 4, 5
Expected: len=3, snapshot=[3 4 5]
Sample 2
Input: capacity = 2, push 7
Expected: len=1, snapshot=[7]
Your solution
Learning objective
Implement a generic bounded buffer with modular indexing and overwrite-on-full semantics.