s LearnSqueak.com

DATA STRUCTURES · BOUNDED HISTORY

Ring buffers: keep recent values without shifting an array

Build a fixed-capacity circular buffer in Squeak Smalltalk, make overwrite-oldest explicit, trace wraparound, and test FIFO order, empty removal and nil values.

8 native checkpoints12 SUnit testsExplicit overflow policy

Before you start

A normal growable queue can retain every item. This bounded recent-history buffer intentionally cannot. Unlike the stack and queue lesson, the focus is physical wraparound, bounded storage and a declared overflow policy, not just FIFO behavior.

  1. Use a private copy of native Squeak 6.1. This class is not preinstalled in the browser playground.
  2. Download ring-buffer.st. Open it in Squeak’s File List and choose fileIn. The chunk-format class file belongs in File List, not a Workspace paste.
  3. Open a Workspace. Each numbered expression is independent: select the whole block and choose Print it. Read class methods in the Browser.

Prerequisites: classes and objects, Arrays and collections, and SUnit. Download the complete source kit for the model, tests, visual trace and reproducible checkpoints.

01 · Separate storage from occupancy

A ring buffer is useful when a stream should retain only its most recent values: the last three sensor readings, for example. The storage is one Array that never grows. The model stores head, the index of the oldest occupied slot, and count, the number of occupied slots. Initially head is 1 and count is 0. All three Array entries are nil, but none is data yet. A head index is still maintained when empty so the next insertion has a well-defined place to go.

LSRingBuffer method · read in the Browser
initializeCapacity: anInteger
 (anInteger isInteger and: [anInteger > 0])
  ifFalse: [self error: 'Capacity must be a positive integer'].
 slots := Array new: anInteger.
 head := 1.
 count := 0.
 ^ self
Independent Workspace expression · select all, then Print it
| b |
b := LSRingBuffer capacity: 3.
{b capacity. b size. b headIndex. b asArray}

Expected: #(3 0 1 #())

Open LSRingBuffer in the System Browser and inspect initializeCapacity:. Its positive-integer check rules out an empty storage array before any remainder operation happens. The invariant is 1 ≤ head ≤ capacity and 0 ≤ count ≤ capacity. This workshop deliberately uses a count instead of a separate tail pointer: two equal pointers alone would not tell you whether a ring was empty or full.

NATIVE SQUEAK CAPTURE
Native Squeak ring buffer checkpoint 1: Separate storage from occupancy
Actual Squeak SystemWindow after this checkpoint’s operations. Green marks occupied storage; the lower row is the FIFO snapshot.

02 · Append using a wrapped index

When the buffer is not full, its next unused position is head plus count, wrapped back into the Array. Smalltalk Arrays start at 1, so the formula first shifts into a zero-based range, applies the remainder message, and then adds 1. The parentheses are essential: this is an index calculation, not a change to Smalltalk’s indexing rules. After storing an item, count increases; head stays put because the oldest item has not changed.

LSRingBuffer method · read in the Browser
add: anObject
 | index |
 self isFull
  ifTrue: [
   slots at: head put: anObject.
   head := self nextIndex: head]
  ifFalse: [
   index := ((head + count - 1) \\ self capacity) + 1.
   slots at: index put: anObject.
   count := count + 1].
 ^ anObject
Independent Workspace expression · select all, then Print it
| b |
b := LSRingBuffer capacity: 3.
b add: 10.
b asArray

Expected: #(10)

Read the not-full branch of add:. For head = 1 and count = 0, the index is 1. With count = 1 it becomes 2. There is no removeFirst or copying of the remaining values. The return value of add: is the inserted object, not the whole buffer; the example explicitly asks b for its snapshot afterward. The screenshot’s green slot denotes occupancy, not a non-nil test.

NATIVE SQUEAK CAPTURE
Native Squeak ring buffer checkpoint 2: Append using a wrapped index
Actual Squeak SystemWindow after this checkpoint’s operations. Green marks occupied storage; the lower row is the FIFO snapshot.

03 · Recognize full without sacrificing a slot

After three insertions all three slots are usable. Some ring representations leave one slot unused to distinguish full from empty; this one does not, because count already contains that information. Full means count equals the fixed capacity. The head still points at 10. The next append must follow an explicit overflow policy rather than silently extending the Array.

LSRingBuffer method · read in the Browser
isFull
 ^ count = self capacity
Independent Workspace expression · select all, then Print it
| b |
b := LSRingBuffer capacity: 3.
#(10 20 30) do: [:value | b add: value].
{b isFull. b size. b asArray}

Expected: #(true 3 #(10 20 30))

Our policy is keep the newest values and discard the oldest when necessary. That is appropriate for a recent-history display, but not automatically appropriate for invoices, commands or a lossless audio pipeline. A rejecting buffer could signal an overflow Error instead. A blocking queue would require a producer/consumer coordination design; neither behavior is implemented here. State the policy in the API rather than asking callers to infer it from the word queue.

NATIVE SQUEAK CAPTURE
Native Squeak ring buffer checkpoint 3: Recognize full without sacrificing a slot
Actual Squeak SystemWindow after this checkpoint’s operations. Green marks occupied storage; the lower row is the FIFO snapshot.

04 · Overwrite the oldest value, then move head

The fourth insertion replaces the entry at head with 40. It then advances head from 1 to 2. Count stays at 3: one old value left and one new value arrived. The physical Array now reads 40, 20, 30, but the logical oldest-to-newest sequence is 20, 30, 40. This distinction is the central idea of the ring, not an incidental display trick.

LSRingBuffer method · read in the Browser
nextIndex: index
 ^ (index \\ self capacity) + 1
Independent Workspace expression · select all, then Print it
| b |
b := LSRingBuffer capacity: 3.
#(10 20 30 40) do: [:value | b add: value].
{b physicalSlots. b headIndex. b asArray}

Expected: #(#(40 20 30) 2 #(20 30 40))

nextIndex: uses remainder so advancing from capacity returns 1. For capacity 3, the sequence is 1 → 2 → 3 → 1. Do not advance head before writing in the full branch: that would overwrite the second-oldest entry and keep the value that was meant to leave. Compare both arrays in the result; a plain slots copy would be a structurally independent but incorrectly ordered FIFO snapshot.

NATIVE SQUEAK CAPTURE
Native Squeak ring buffer checkpoint 4: Overwrite the oldest value, then move head
Actual Squeak SystemWindow after this checkpoint’s operations. Green marks occupied storage; the lower row is the FIFO snapshot.

05 · Remove oldest and clear its reference

Removal returns the oldest value, clears that storage slot, advances head and decreases count. Clearing the reference matters even though count would already exclude the slot from the logical queue: an unused slot should not unnecessarily keep its former object reachable. Nothing shifts. The gray slot is now available for a future append.

LSRingBuffer method · read in the Browser
removeOldest
 | value |
 self isEmpty ifTrue: [self error: 'Buffer is empty'].
 value := slots at: head.
 slots at: head put: nil.
 head := self nextIndex: head.
 count := count - 1.
 ^ value
Independent Workspace expression · select all, then Print it
| b removed |
b := LSRingBuffer capacity: 3.
#(10 20 30 40) do: [:value | b add: value].
removed := b removeOldest.
{removed. b physicalSlots. b headIndex. b asArray}

Expected: #(20 #(40 nil 30) 3 #(30 40))

The empty check runs before reading a slot. Removing from an empty buffer signals Error; returning nil would be ambiguous because nil is allowed as real data. The model is not thread-safe: testing isEmpty and removing are separate operations unless performed together inside the method. A second process must not interleave updates without a separate synchronization strategy. There is no promise of lock-free behavior in this teaching model.

NATIVE SQUEAK CAPTURE
Native Squeak ring buffer checkpoint 5: Remove oldest and clear its reference
Actual Squeak SystemWindow after this checkpoint’s operations. Green marks occupied storage; the lower row is the FIFO snapshot.

06 · Reuse space across the physical boundary

With head at 3 and count at 2, the next free slot wraps to physical position 2. Appending 50 fills that slot without moving 30 or 40. The result is full again. checkInvariant is a compact diagnostic of index bounds and occupancy bounds; it does not compare the contents against a separate reference queue or prove the whole algorithm correct.

LSRingBuffer method · read in the Browser
checkInvariant
 ^ (head between: 1 and: self capacity)
  and: [count between: 0 and: self capacity]
Independent Workspace expression · select all, then Print it
| b |
b := LSRingBuffer capacity: 3.
#(10 20 30 40) do: [:value | b add: value].
b removeOldest.
b add: 50.
{b physicalSlots. b asArray. b checkInvariant}

Expected: #(#(40 50 30) #(30 40 50) true)

Try capacity 1 as a boundary case. An append to a full one-slot buffer replaces its only value; head remains 1. A remove then leaves count 0. Tests include that case because it quickly exposes an off-by-one error that may appear harmless at capacity 3. The test suite also repeats one hundred inserts, checking bounds after every operation.

NATIVE SQUEAK CAPTURE
Native Squeak ring buffer checkpoint 6: Reuse space across the physical boundary
Actual Squeak SystemWindow after this checkpoint’s operations. Green marks occupied storage; the lower row is the FIFO snapshot.

07 · Return FIFO order without exposing storage

asArray visits exactly count slots, beginning at head and wrapping when needed. It writes them into a new Array in FIFO order. Here the oldest value is 50 in physical slot 2, followed by 60 in slot 3 and 70 in slot 1. The returned Array is a snapshot of the ordering at that moment; a later append does not update it.

LSRingBuffer method · read in the Browser
asArray
 | answer index |
 answer := Array new: count.
 1 to: count do: [:offset |
  index := ((head + offset - 2) \\ self capacity) + 1.
  answer at: offset put: (slots at: index)].
 ^ answer
Independent Workspace expression · select all, then Print it
| b snapshot |
b := LSRingBuffer capacity: 3.
#(10 20 30 40) do: [:value | b add: value].
b removeOldest.
b add: 50.
b removeOldest.
b add: 60; add: 70.
snapshot := b asArray.
{b physicalSlots. snapshot}

Expected: #(#(70 50 60) #(50 60 70))

The container copy is shallow. Changing a snapshot entry with at:put: does not change the buffer’s entry, but a mutable object stored inside both containers is still the same object. The numeric examples avoid that aliasing complication. physicalSlots also returns a copy for inspection, not the private Array itself. Append and removal take constant indexing work; creating a snapshot allocates an Array and visits every stored item, so it is linear in count.

NATIVE SQUEAK CAPTURE
Native Squeak ring buffer checkpoint 7: Return FIFO order without exposing storage
Actual Squeak SystemWindow after this checkpoint’s operations. Green marks occupied storage; the lower row is the FIFO snapshot.

08 · Allow nil without confusing it with empty

After draining the buffer, append nil. It is now one stored value, even though every physical Array entry prints nil. The occupancy metadata is what makes the distinction. In the screenshot only slot 2 is green, because that is the one occupied slot. A search for the first nil would give the wrong answer and would prevent callers from storing a legitimate nil value.

LSRingBuffer method · read in the Browser
isEmpty
 ^ count = 0
Independent Workspace expression · select all, then Print it
| b |
b := LSRingBuffer capacity: 3.
#(10 20 30 40) do: [:value | b add: value].
b removeOldest.
b add: 50.
b removeOldest.
b add: 60; add: 70.
3 timesRepeat: [b removeOldest].
b add: nil.
{b size. b isEmpty. b asArray}

Expected: #(1 false #(nil))

Now removeOldest returns nil and the buffer becomes empty. Repeating that removal would signal Error. This separation between stored data and bookkeeping is useful far beyond ring buffers: sentinel values can be convenient, but they restrict which data can be represented. Here count carries that information explicitly and uses all capacity slots.

NATIVE SQUEAK CAPTURE
Native Squeak ring buffer checkpoint 8: Allow nil without confusing it with empty
Actual Squeak SystemWindow after this checkpoint’s operations. Green marks occupied storage; the lower row is the FIFO snapshot.

Replay and reproduce the native trace

NATIVE SQUEAK CAPTURE
Empty native Squeak circular buffer before the captured-state replay
Eight genuine native Squeak window captures after scripted operations. This GIF is a captured-state replay, not mouse footage.

Download the visual trace expression, open it as text and evaluate the entire expression with Do it after installing the model. Change stage := 0. to an integer from 0 through 7 to reproduce a later checkpoint. It opens a fixed 1000 × 520 native window. Close each old window before opening another; no timer, network or persistent saving is involved.

Run tests before extending the model

File in the SUnit tests, then select and Print it:

Workspace · Print it
LSRingBufferTest suite run

Verified in Squeak 6.1 build 23976: 12 tests, 12 passes, 0 failures and 0 errors. They cover empty/fill/overwrite/removal behavior, invalid capacities, capacity one, repeated wraps, nil data and independence of returned container copies. All eight displayed checkpoint expressions were also evaluated and compared with their stated results.

Extend the exercise by implementing a rejecting overflow policy in a separate class, then change the tests to require an Error rather than data loss. Add a read-only oldest accessor without changing count. Finally, compare a thousand random operations against an OrderedCollection reference implementation trimmed to capacity. Do not call this buffer concurrent or lossless merely because the examples pass: those are additional contracts and require different tests.

Sources and next steps

The policy distinction is supported by Boost’s official circular-buffer implementation notes: overwriting the oldest entry is one intentional choice for a full buffer, rather than a guarantee shared by every bounded queue. This Smalltalk class, tests, explanations and native visual trace are original and are not a translation of Boost source.

For Squeak tools, see official Squeak documentation. Continue with linked lists to compare storage strategies, or measure first to examine real workload costs. The object payloads themselves can occupy arbitrary memory: a fixed number of slots is not a hard byte-size memory limit.