Programming Search⌘K

Conceptcore

Ring buffer

Also called ring buffer, circular buffer, circular queue, cyclic buffer, bounded buffer, deque maxlen.

A ring buffer is a fixed-size array used as a queue. The read and write positions wrap around to the start, so no item moves, and a full buffer refuses new items or overwrites the oldest.

Applies to
core-languages

Idea

A ring buffer is a fixed array that acts as if its last slot were joined to its first. Wikipedia: "a circular buffer, circular queue, cyclic buffer or ring buffer is a data structure that uses a single, fixed-size buffer as if it were connected end-to-end."1 A program writes at one position and reads at another. When a position passes the last slot, it goes back to slot 0.

This class keeps the newest three readings. When the buffer is full, a new reading overwrites the oldest one.

class RingBuffer:
    def __init__(self, capacity):
        self.items = [None] * capacity
        self.start = 0
        self.count = 0

    def push(self, item):
        end = (self.start + self.count) % len(self.items)
        self.items[end] = item
        if self.count < len(self.items):
            self.count += 1
        else:
            self.start = (self.start + 1) % len(self.items)

    def __iter__(self):
        for i in range(self.count):
            yield self.items[(self.start + i) % len(self.items)]


ring = RingBuffer(3)
for reading in [10, 20, 30, 40, 50]:
    ring.push(reading)
    print("push", reading, "->", list(ring), "slots", ring.items, "start", ring.start)
Output
push 10 -> [10] slots [10, None, None] start 0
push 20 -> [10, 20] slots [10, 20, None] start 0
push 30 -> [10, 20, 30] slots [10, 20, 30] start 0
push 40 -> [20, 30, 40] slots [40, 20, 30] start 1
push 50 -> [30, 40, 50] slots [40, 50, 30] start 2

The slots show that no item moves. Only the start index changes.

How it works

The parts. A ring buffer has an array of fixed capacity, a read index (the start) and either a write index (the end) or a count.1

  • A write puts the item at the end index and moves the end index to the next slot.
  • A read takes the item at the start index and moves the start index to the next slot.
  • "The next slot" is (index + 1) % capacity, so the index goes from the last slot back to slot 0.

Wikipedia: "When elements get removed, only the read-pointer moves to the next element. Removed elements are still in the buffer, waiting to get overwritten by new elements."1

Full and empty. If the buffer keeps only the two indexes, a full buffer and an empty buffer both have start equal to end. Wikipedia: "The start and end indexes alone are not enough to distinguish between buffer full or empty state while also utilizing all buffer slots".1 There are two common fixes:

  • Keep one slot always empty. The buffer is then full when it holds capacity minus one items.1
  • Keep a count. "Then checking for emptiness means testing count equals 0 and checking for fullness means testing count equals Length."1

When the buffer is full. A write to a full buffer must do one of two things. It can overwrite the oldest item: "when it is full and a subsequent write is performed, then it starts overwriting the oldest data."1 Or it can refuse: "the routines that manage the buffer could prevent overwriting the data and return an error or raise an exception."1 A log of recent events usually overwrites. A queue of orders must refuse, or it loses orders.

Why it is used. "The useful property of a circular buffer is that it does not need to have its elements shuffled around when one is consumed."1 For a queue with a maximum size, "all queue operations are constant time".1 The memory is allocated once, so a ring buffer suits streams of data, audio, keyboard input and other places that cannot allocate memory at each item.

In languages

LanguageVerdictNote
PythonStandard library
C++Idiom
JavaIdiom
CIdiom
C#Idiom
JavaScriptIdiom
TypeScriptIdiomTypeScript has no ring buffer type. A class keeps an array, a start index and a count, as in the JavaScript example. No example file exists.
GoIdiom
RustStandard library
KotlinIdiomKotlin has no fixed ring buffer type. A class over an array, or ArrayDeque with a size check, does the work. No example file exists because kotlinc is not installed.
SQLIdiomA table can keep only its newest rows if the program deletes the oldest rows after each insert. SQL has no ring buffer type.
BashIdiomAn indexed array with an index that wraps with the % operator works as a ring buffer. No example file exists.
PowerShellIdiomA .NET array with a start index and a count works as a ring buffer. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is markup. It has no data structures for a program.
CSSDoes not applyCSS style rules have no data structures.
Regular expressionsDoes not applyA regular expression matches text. It has no data structures.
Language Verdict Form
Python stdlib collections.deque(maxlen=n) overwrites the oldest item2
JavaScript idiom an array, a start index and a count
TypeScript idiom as JavaScript
Java idiom an array and two indexes; ArrayDeque is a ring that grows3
C idiom an array, a start index and a count
C++ idiom a std::array and two indexes
C# idiom an array and two indexes; Queue<T> is a circular array that grows4
Go idiom a slice and two indexes; container/ring is a circular list5
Rust stdlib VecDeque, a growable ring buffer, with a length check6
Kotlin idiom an array and two indexes, or ArrayDeque with a size check
PowerShell idiom a .NET array and two indexes
Bash idiom an indexed array and an index with %
SQL idiom a table that deletes its oldest rows after each insert
Regex n/a a pattern has no data structures
HTML/CSS n/a markup and style rules have no data structures

Python. A deque with maxlen is a ring buffer that overwrites. "Once a bounded length deque is full, when new items are added, a corresponding number of items are discarded from the opposite end."2 The documentation adds: "Bounded length deques provide functionality similar to the tail filter in Unix."2

Rust. VecDeque is "A double-ended queue implemented with a growable ring buffer."6 It grows when it is full. For a fixed size, the program calls pop_front before push_back when the length reaches the limit.

C#. The Queue<T> class "implements a generic queue as a circular array."4 It also grows when it is full.

Java. ArrayDeque is a "Resizable-array implementation of the Deque interface." "Array deques have no capacity restrictions; they grow as necessary to support usage."3 A fixed ring with overwrite is a small class over an array.

C, C++, Go and JavaScript. These programs write the ring by hand. The example files show the same buffer of capacity 3 in each language.

PythonGitHub
from collections import deque

ring = deque(maxlen=3)
for reading in [10, 20, 30, 40, 50]:
    ring.append(reading)
    print(f"after {reading}:", *ring)

oldest = ring.popleft()
print(f"read {oldest}, left:", *ring)
Output
after 10: 10
after 20: 10 20
after 30: 10 20 30
after 40: 20 30 40
after 50: 30 40 50
read 30, left: 40 50
  • Verdict: stdlib. deque(maxlen=3) is a ring buffer that overwrites. When it is full, append drops the item at the left end.
  • popleft reads the oldest item.
#include <array>
#include <cstddef>
#include <initializer_list>
#include <iostream>
#include <optional>

template <typename T, std::size_t N>
class RingBuffer {
public:
    void push(const T& item) {
        items_[(start_ + count_) % N] = item;
        if (count_ < N) {
            ++count_;
        } else {
            start_ = (start_ + 1) % N;
        }
    }

    std::optional<T> pop() {
        if (count_ == 0) {
            return std::nullopt;
        }
        T item = items_[start_];
        start_ = (start_ + 1) % N;
        --count_;
        return item;
    }

    void print() const {
        for (std::size_t i = 0; i < count_; ++i) {
            std::cout << ' ' << items_[(start_ + i) % N];
        }
        std::cout << '\n';
    }

private:
    std::array<T, N> items_{};
    std::size_t start_ = 0;
    std::size_t count_ = 0;
};

int main() {
    RingBuffer<int, 3> ring;
    for (int reading : {10, 20, 30, 40, 50}) {
        ring.push(reading);
        std::cout << "after " << reading << ':';
        ring.print();
    }

    if (auto oldest = ring.pop()) {
        std::cout << "read " << *oldest << ", left:";
        ring.print();
    }
}
Output
after 10: 10
after 20: 10 20
after 30: 10 20 30
after 40: 20 30 40
after 50: 30 40 50
read 30, left: 40 50
  • Verdict: idiom. The standard library has no ring buffer. This class template keeps a std::array of fixed size N.
  • pop returns an empty std::optional when the buffer is empty.
JavaGitHub
public class Main {
    static final class RingBuffer {
        private final int[] items;
        private int start = 0;
        private int count = 0;

        RingBuffer(int capacity) {
            items = new int[capacity];
        }

        void push(int item) {
            items[(start + count) % items.length] = item;
            if (count < items.length) {
                count++;
            } else {
                start = (start + 1) % items.length;
            }
        }

        int pop() {
            if (count == 0) {
                throw new IllegalStateException("empty");
            }
            int item = items[start];
            start = (start + 1) % items.length;
            count--;
            return item;
        }

        String contents() {
            StringBuilder out = new StringBuilder();
            for (int i = 0; i < count; i++) {
                out.append(" ").append(items[(start + i) % items.length]);
            }
            return out.toString();
        }
    }

    public static void main(String[] args) {
        RingBuffer ring = new RingBuffer(3);
        for (int reading : new int[] {10, 20, 30, 40, 50}) {
            ring.push(reading);
            System.out.println("after " + reading + ":" + ring.contents());
        }

        int oldest = ring.pop();
        System.out.println("read " + oldest + ", left:" + ring.contents());
    }
}
Output
after 10: 10
after 20: 10 20
after 30: 10 20 30
after 40: 20 30 40
after 50: 30 40 50
read 30, left: 40 50
  • Verdict: idiom. The standard ArrayDeque grows, so a fixed ring that overwrites is a small class over an int array.
  • pop throws IllegalStateException when the buffer is empty.
#include <stdbool.h>
#include <stdio.h>

#define CAPACITY 3

struct ring {
    int items[CAPACITY];
    int start;
    int count;
};

static void push(struct ring *r, int item) {
    r->items[(r->start + r->count) % CAPACITY] = item;
    if (r->count < CAPACITY) {
        r->count++;
    } else {
        r->start = (r->start + 1) % CAPACITY;
    }
}

static bool pop(struct ring *r, int *out) {
    if (r->count == 0) {
        return false;
    }
    *out = r->items[r->start];
    r->start = (r->start + 1) % CAPACITY;
    r->count--;
    return true;
}

static void print_items(const struct ring *r) {
    for (int i = 0; i < r->count; i++) {
        printf(" %d", r->items[(r->start + i) % CAPACITY]);
    }
    printf("\n");
}

int main(void) {
    struct ring r = {.start = 0, .count = 0};
    int readings[] = {10, 20, 30, 40, 50};
    for (int i = 0; i < 5; i++) {
        push(&r, readings[i]);
        printf("after %d:", readings[i]);
        print_items(&r);
    }

    int oldest = 0;
    if (pop(&r, &oldest)) {
        printf("read %d, left:", oldest);
        print_items(&r);
    }
    return 0;
}
Output
after 10: 10
after 20: 10 20
after 30: 10 20 30
after 40: 20 30 40
after 50: 30 40 50
read 30, left: 40 50
  • Verdict: idiom. A fixed array, a start index and a count make a ring buffer. It allocates no memory.
  • pop returns false when the buffer is empty.
var ring = new RingBuffer<int>(3);
foreach (int reading in new[] { 10, 20, 30, 40, 50 })
{
    ring.Push(reading);
    Console.WriteLine("after " + reading + ": " + string.Join(" ", ring.Items()));
}

int oldest = ring.Pop();
Console.WriteLine("read " + oldest + ", left: " + string.Join(" ", ring.Items()));

class RingBuffer<T>
{
    private readonly T[] items;
    private int start;
    private int count;

    public RingBuffer(int capacity) => items = new T[capacity];

    public void Push(T item)
    {
        items[(start + count) % items.Length] = item;
        if (count < items.Length)
        {
            count++;
        }
        else
        {
            start = (start + 1) % items.Length;
        }
    }

    public T Pop()
    {
        if (count == 0)
        {
            throw new InvalidOperationException("empty");
        }
        T item = items[start];
        start = (start + 1) % items.Length;
        count--;
        return item;
    }

    public IEnumerable<T> Items()
    {
        for (int i = 0; i < count; i++)
        {
            yield return items[(start + i) % items.Length];
        }
    }
}
Output
after 10: 10
after 20: 10 20
after 30: 10 20 30
after 40: 20 30 40
after 50: 30 40 50
read 30, left: 40 50
  • Verdict: idiom. .NET Queue<T> is a circular array that grows, so a fixed ring that overwrites is a small class.
  • Items yields the items from the oldest to the newest.
JavaScriptGitHub
class RingBuffer {
  #items;
  #start = 0;
  #count = 0;

  constructor(capacity) {
    this.#items = new Array(capacity);
  }

  push(item) {
    const capacity = this.#items.length;
    this.#items[(this.#start + this.#count) % capacity] = item;
    if (this.#count < capacity) {
      this.#count++;
    } else {
      this.#start = (this.#start + 1) % capacity;
    }
  }

  shift() {
    if (this.#count === 0) return undefined;
    const item = this.#items[this.#start];
    this.#start = (this.#start + 1) % this.#items.length;
    this.#count--;
    return item;
  }

  toArray() {
    const out = [];
    for (let i = 0; i < this.#count; i++) {
      out.push(this.#items[(this.#start + i) % this.#items.length]);
    }
    return out;
  }
}

const ring = new RingBuffer(3);
for (const reading of [10, 20, 30, 40, 50]) {
  ring.push(reading);
  console.log(`after ${reading}:`, ring.toArray().join(" "));
}

const oldest = ring.shift();
console.log(`read ${oldest}, left:`, ring.toArray().join(" "));
Output
after 10: 10
after 20: 10 20
after 30: 10 20 30
after 40: 20 30 40
after 50: 30 40 50
read 30, left: 40 50
  • Verdict: idiom. JavaScript has no ring buffer type. This class keeps an array, a start index and a count.
  • The write position is (start + count) % capacity. When the buffer is full, push overwrites the oldest item and moves the start.
package main

import "fmt"

type ring struct {
	items []int
	start int
	count int
}

func newRing(capacity int) *ring {
	return &ring{items: make([]int, capacity)}
}

func (r *ring) push(item int) {
	r.items[(r.start+r.count)%len(r.items)] = item
	if r.count < len(r.items) {
		r.count++
	} else {
		r.start = (r.start + 1) % len(r.items)
	}
}

func (r *ring) pop() (int, bool) {
	if r.count == 0 {
		return 0, false
	}
	item := r.items[r.start]
	r.start = (r.start + 1) % len(r.items)
	r.count--
	return item, true
}

func (r *ring) print() {
	for i := 0; i < r.count; i++ {
		fmt.Print(" ", r.items[(r.start+i)%len(r.items)])
	}
	fmt.Println()
}

func main() {
	r := newRing(3)
	for _, reading := range []int{10, 20, 30, 40, 50} {
		r.push(reading)
		fmt.Printf("after %d:", reading)
		r.print()
	}

	if oldest, ok := r.pop(); ok {
		fmt.Printf("read %d, left:", oldest)
		r.print()
	}
}
Output
after 10: 10
after 20: 10 20
after 30: 10 20 30
after 40: 20 30 40
after 50: 30 40 50
read 30, left: 40 50
  • Verdict: idiom. A slice of fixed length, a start index and a count make a ring buffer.
  • pop returns false as its second value when the buffer is empty.
RustGitHub
use std::collections::VecDeque;

struct RingBuffer<T> {
    items: VecDeque<T>,
    capacity: usize,
}

impl<T> RingBuffer<T> {
    fn new(capacity: usize) -> Self {
        RingBuffer {
            items: VecDeque::with_capacity(capacity),
            capacity,
        }
    }

    fn push(&mut self, item: T) {
        if self.items.len() == self.capacity {
            self.items.pop_front();
        }
        self.items.push_back(item);
    }

    fn pop(&mut self) -> Option<T> {
        self.items.pop_front()
    }
}

fn show(ring: &RingBuffer<i32>) -> String {
    let parts: Vec<String> = ring.items.iter().map(|n| n.to_string()).collect();
    parts.join(" ")
}

fn main() {
    let mut ring = RingBuffer::new(3);
    for reading in [10, 20, 30, 40, 50] {
        ring.push(reading);
        println!("after {reading}: {}", show(&ring));
    }

    if let Some(oldest) = ring.pop() {
        println!("read {oldest}, left: {}", show(&ring));
    }
}
Output
after 10: 10
after 20: 10 20
after 30: 10 20 30
after 40: 20 30 40
after 50: 30 40 50
read 30, left: 40 50
  • Verdict: stdlib. VecDeque is a growable ring buffer. This wrapper calls pop_front before push_back when the length reaches the capacity, so the size stays fixed.
  • pop returns None when the buffer is empty.
  • Growable ring buffer. When the buffer is full, it allocates a bigger array and copies the items in order. VecDeque and .NET Queue<T> work like this.64 Wikipedia notes that "expanding a circular buffer requires shifting memory, which is comparatively costly."1
  • Bounded buffer between threads. A producer writes and a consumer reads, with locks or atomic operations around the indexes. Wikipedia mentions the ring buffer as "the bounded buffer in the producer–consumer problem".1 See producer-consumer. Concurrent ring buffers belong to concurrency.
  • Go channels. A buffered channel is a bounded first in, first out queue between goroutines. See channels.
  • Circular linked list. Go's container/ring is a list whose last node links to the first. "Rings do not have a beginning or end; a pointer to any ring element serves as reference to the entire ring."5 It is not an array, and its Len "executes in time proportional to the number of elements."5
  • Items that wrap. The items of a ring buffer can sit in two parts of the array. Rust says that "its elements are not necessarily contiguous in memory".6 See deque for as_slices and make_contiguous.

Pitfalls

Full and empty look the same

With only a start index and an end index, a buffer that holds capacity items has start equal to end, as an empty buffer has.

This code runs but gives a wrong answer on purpose.

class Ring:
    def __init__(self, capacity):
        self.items = [None] * capacity
        self.start = 0
        self.end = 0

    def is_empty(self):
        return self.start == self.end

    def push(self, item):
        self.items[self.end] = item
        self.end = (self.end + 1) % len(self.items)


ring = Ring(3)
print("empty at start:", "yes" if ring.is_empty() else "no")
for item in "abc":
    ring.push(item)
print("empty after 3 pushes:", "yes" if ring.is_empty() else "no")
Output
empty at start: yes
empty after 3 pushes: yes

Keep a count, as in the Idea example, or treat the buffer as full when it holds capacity minus one items.1

A bounded deque drops items without an error

deque(maxlen=n).append never fails. When the deque is full, the oldest item goes away.2 That is right for a window of recent values, and wrong for work that must not be lost.

This code runs but gives a wrong answer on purpose.

from collections import deque

orders = deque(maxlen=3)
for order in ["A1", "A2", "A3", "A4", "A5"]:
    orders.append(order)
print("kept:", list(orders))
print("lost: A1 and A2, with no error")
Output
kept: ['A3', 'A4', 'A5']
lost: A1 and A2, with no error

For work that must not be lost, check the length first and refuse or wait when the buffer is full.

The remainder of a negative number

To step an index back by one, a program may write (index - 1) % capacity. In Java, when the index is 0, the result is -1, which is not a valid index. Other languages with the same % rule fail in the same way.

This code runs but gives a wrong answer on purpose.

public class Main {
    public static void main(String[] args) {
        int capacity = 4;
        int index = 0;
        System.out.println("(index - 1) % capacity = " + (index - 1) % capacity);
        System.out.println("Math.floorMod(index - 1, capacity) = " + Math.floorMod(index - 1, capacity));
        System.out.println("(index - 1 + capacity) % capacity = " + (index - 1 + capacity) % capacity);
    }
}
Output
(index - 1) % capacity = -1
Math.floorMod(index - 1, capacity) = 3
(index - 1 + capacity) % capacity = 3

Add the capacity before the remainder, or use a floor modulo function. For Python, see integer division and modulo.

A growable ring buffer is not bounded

VecDeque, ArrayDeque and .NET Queue<T> use a ring inside, but they grow without limit.643 A program that needs a fixed memory size must check the length itself.

Cost

Operation Ring buffer Array with shift at the front
write at the end constant constant (amortized)
read from the front constant linear
memory fixed at creation grows
grow linear copy linear copy

Wikipedia: for a queue with a maximum size, "all queue operations are constant time".1 Without the ring, "it would be necessary to shift all elements when one is consumed."1

History

Wikipedia states that "There were early circular buffer implementations in hardware."1 The read-only maxlen attribute of a Python deque was "Added in version 3.1."2

References

  1. Circular buffer, Wikipedia, the introduction; Overview; Uses; Circular buffer mechanics
  2. collections, Container datatypes, Python documentation, deque objects
  3. ArrayDeque (Java SE 27 and JDK 27), the class description
  4. Queue<T> Class, .NET API reference, Remarks
  5. ring package, container/ring, Go standard library, Overview; type Ring; func (*Ring) Len
  6. Struct VecDeque, The Rust Standard Library, the description

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/CRWTGM/text.yaml