#buffer #circular #circular-buffer #zero #allocation


A zero-allocation, fast, circular buffer implementation in Rust

3 releases

0.1.2 Jul 25, 2020
0.1.1 Jul 25, 2020
0.1.0 Jul 25, 2020

#887 in Algorithms

Download history 23/week @ 2023-02-08 46/week @ 2023-02-15 23/week @ 2023-02-22 14/week @ 2023-03-01 15/week @ 2023-03-08 11/week @ 2023-03-15 6/week @ 2023-03-22 9/week @ 2023-03-29 12/week @ 2023-04-05 14/week @ 2023-04-12 5/week @ 2023-04-19 19/week @ 2023-04-26 14/week @ 2023-05-03 20/week @ 2023-05-10 18/week @ 2023-05-17 8/week @ 2023-05-24

64 downloads per month
Used in 2 crates

MIT license

551 lines


A zero dependencies, zero run-time allocation, circular buffer.

This crates provide a simple circular buffer that does not do any allocation at run time. The main focus of this crate is correctess and performances.

The circular buffer never wait, if the buffer is full, it overwrite the first element.

The API is extremelly simple, you create the buffer specify how many elements the buffer can hold. Then you can start pushing elements into it.

use rbl_circular_buffer::*;

let mut buffer = CircularBuffer::new(3);
assert_eq!(0, buffer.len());

assert_eq!(1, buffer.len());

assert_eq!(2, buffer.len());

assert_eq!(3, buffer.len());

// now the buffer is full, we can insert the next element, but it will overwrite the first one
assert_eq!(3, buffer.len());

let v: Vec<u32> = buffer.collect();
assert_eq!(vec![2,3,4], v);

There are two ways to read the elements from the buffer.

  1. CircularBuffer implement the Iterator trait, you can loop over it.
  2. CircularBuffer provided the .fill() method.

Using the iterator

The iterator will consume the elements in the buffer.

use rbl_circular_buffer::*;

let mut buffer = CircularBuffer::new(3);

let mut sum = 0;
for element in &mut buffer {
    sum += element;
assert_eq!(1 + 2 + 3, sum);
assert_eq!(0, buffer.len());

Filling a vector

In demanding application, the iterator can be a bad choice.

Think about communication between threads, each thread can have a reference to the CircularBuffer and take a lock while reading from it. If the reading operation are not fast enough, or simply if there are too many elements, the lock will be hold for a long period of time. The alternative is to fill a vector.

use rbl_circular_buffer::*;

// let's make a bigger vector
let mut buffer = CircularBuffer::new(5);
for i in 1..=5 {

// with this vector we will remove the first 3 elements
let mut v = Vec::with_capacity(3);

buffer.fill(&mut v);
assert_eq!(vec![1, 2, 3], v);

// in the vector there are still 4 and 5
assert_eq!(2, buffer.len());


// the fill avoid any allocation even in the vector to fill.
// if we remove one element, and refill, we will push only one element.
// this because `.fill()` does not allocate any memory.


buffer.fill(&mut v);

assert_eq!(vec![2, 3, 4], v);
assert_eq!(4, buffer.len())

No runtime deps