Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 36 ยท Projects and Practice

Project: A Generic Ring Buffer in Nim

Build a fixed-size generic ring buffer in Nim with static sizes, iterators and operator templates, and try the same circular-queue logic in runnable C.

A ring buffer (circular queue) stores the most recent N items in a fixed block of memory. When it is full, a new item overwrites the oldest one. It is used for logs, audio, network packets and "last 10 values" widgets, anywhere you need constant memory and constant-time operations.

This project combines generics, static sizes from compile-time execution, iterators and value semantics from Objects and Tuples. The Nim code is read-only on this site; the C version below runs here.

How it works

flowchart LR
  subgraph B["capacity 4"]
    S0["[0]"] --- S1["[1]"] --- S2["[2]"] --- S3["[3]"]
  end
  H["head: oldest"] -.-> S1
  T["tail: next write"] -.-> S3

Two indexes chase each other around the array; count tells full from empty.

Keep three numbers: head (index of the oldest item), count, and the capacity. The write position is (head + count) mod capacity. Pushing when full overwrites the oldest item and moves head forward.

The Nim version

NIM
type
  RingBuffer[N: static int, T] = object
    data: array[N, T]
    head, count: int

proc push[N: static int, T](r: var RingBuffer[N, T], x: T) =
  let tail = (r.head + r.count) mod N
  r.data[tail] = x
  if r.count < N:
    inc r.count
  else:
    r.head = (r.head + 1) mod N      # overwrote the oldest

proc pop[N: static int, T](r: var RingBuffer[N, T]): T =
  doAssert r.count > 0, "pop from empty buffer"
  result = r.data[r.head]
  r.head = (r.head + 1) mod N
  dec r.count

proc len[N: static int, T](r: RingBuffer[N, T]): int = r.count
proc isFull[N: static int, T](r: RingBuffer[N, T]): bool = r.count == N

iterator items[N: static int, T](r: RingBuffer[N, T]): T =
  for i in 0 ..< r.count:
    yield r.data[(r.head + i) mod N]

var log: RingBuffer[3, string]
for line in ["a", "b", "c", "d", "e"]:
  log.push line
for x in log: echo x          # c, d, e

Points to notice:

  • N: static int makes the size part of the type. RingBuffer[3, string] and RingBuffer[8, string] are different types and the array is stored inline with no heap allocation.
  • The type is generic in the element type T as well, so it works for int, string or your own objects.
  • iterator items lets for x in log work, from oldest to newest.
  • Because RingBuffer is a plain object, assigning one copies all the elements (value semantics).

The same logic in C

C C stand-in: ring buffer

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

After pushing 1 to 5 into a buffer of three, only 3, 4 and 5 remain, and pop returns the oldest, 3.

Adding statistics

A moving average over the last N samples is a typical use. Keep a running sum so each update is constant time:

C C stand-in: moving average with a running sum

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Extensions

  1. Add peek, clear and an [] operator for index access relative to the oldest item.
  2. Add a {.raises.}-free tryPop that returns Option[T].
  3. Use a power-of-two capacity and replace mod N with and (N - 1), which is faster.
  4. Make it thread safe by wrapping operations in a lock (see Threads and Channels).
  5. Test the wrap-around cases with std/unittest.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How is the next write position computed?

    The newest item sits count steps after the oldest, wrapping around.
  2. 2. What happens when pushing into a full buffer?

    head advances so the oldest value is replaced.
  3. 3. What does N: static int achieve?

    The array size is known at compile time and stored inline.
  4. 4. Why keep a running sum for a moving average?

    Subtract the dropped item and add the new one instead of re-summing.

Summary

  • A ring buffer is a fixed array with a head and a count.
  • Static sizes in the type give heap-free, copyable containers.
  • Generic element types and an items iterator make it reusable.
  • Constant memory and constant time suit logs, streams and windows.

Next: Nim Practice Problems