Skip to main content

Safe Systems Programming Series I: Zero-Cost Ring Buffers in Rust

Safe Systems Programming Series I: Zero-Cost Ring Buffers in Rust

Zero-cost Promise

Zero-cost abstractions fundamentally change how we think about building systems. Rust's zero-cost abstractions allow developers to write expressive, high-level code without compromising performance. This article will showcase zero-cost abstractions in Rust by building a ring buffer for a reliable UDP network protocol.

Ring buffers are essential in systems programming, used in areas like audio processing and network packet handling. Despite their simplicity, creating a safe and efficient implementation is challenging.

Recall the requirements for a network buffer:

  • The buffer stores network bytes in the same memory allocation
  • The buffer supports single and batch insertion and removal
  • The length of an insertion is unknown in advance
  • An insertion can fail

We start with single-element operations. Then we build a flexible method to insert data of unknown length.

The next articles in this series extend this framework to buffer unreliable UDP traffic:

Network Ring Buffers

Network buffers typically use a ring buffer. A ring buffer has a fixed size, and adds and removes elements in constant time. Constant-time operations without data copies and good data locality make ring buffers suitable for data streaming workloads.

Our buffer, Ring, stores a head pointer and a length:

pub struct Ring<'a, T> {
  head: u32,
  len: u32,
  buffer: &'a mut [T],
}

Network buffers typically use a fixed length. The diagram below shows a 10-element buffer:

An empty ring buffer of 10 elements. The start pointer and the tail pointer are at the first index, and the length is 0.

We insert packets of different lengths at the tail of the buffer:

A ring buffer with one packet at the start pointer. The tail pointer is at the next empty index, and the length is 2. A ring buffer with three packets of different lengths. The tail pointer is at the next empty index, and the length is 8.

Removing the first two packets does not move the third packet within the buffer:

The ring buffer after we remove the first two packets. The third packet stays at the same index, and the start pointer moves to it.

If we insert a packet that is longer than the free space at the buffer tail, the packet wraps to the start of the buffer. Wrapping pads the last element.

Packet 4 wraps to the start of the ring buffer. Padding fills the buffer from packet 3 to the end, and the length is 8.

Removing the third element also removes the padding:

The ring buffer after we remove packet 3 and its padding. Only packet 4 remains at the start of the buffer.

There are different ways to implement ring buffers. We use the head and length because it is simple.

I've been writing ring buffers wrong all these years

Zero-cost Abstractions

Recall that receiving a UDP packet requires a preallocated buffer with known location. The size of the packet is unknown ahead of time, and receiving the packet can fail.

let socket = std::net::UdpSocket::bind("127.0.0.1:34254")?;
// Packet will be truncated if `buf` is too small
let mut buf = [0; 10];
let (written, _) = socket.recv_from(&mut buf)?;

In this article we will implement basic single-element insertion and removal methods ending in an insertion method that can handle the unknown length case.

let mut ring: Ring<'_, u8>;
let mut socket: std::net::UdpSocket;

// Insert single element
*ring.push()?.data_mut() = 42;

// Remove single element and verify its value
assert_eq!(*ring.pop()?.data(), 42);

// Insert message fallibly
let written = ring.push_many_with(|mut v: RingManyMutView<'_, '_, u8>| {
  let (written, _) = socket.recv_from(v.data_mut())?;
  v.set_modified(written as u32);
  Ok(written)
})?;

Introducing Views

Views in our ring buffer provide a way to access and manipulate its elements safely and efficiently without copying data or taking ownership. They act as references to specific portions of the buffer.

For operations on individual elements we use two types of views:

  • RingView: Provides read-only access to an element
  • RingMutView: Provides read-write access to an element

Here is how we implement RingMutView:

pub struct RingMutView<'a, 's, T> {
  index: u32,                // Position in the buffer
  ring: &'a mut Ring<'s, T>, // Mutable reference to the ring buffer
}

impl<'a, 's, T> RingMutView<'a, 's, T> {
  pub fn index(&self) -> u32 {
    self.index
  }

  pub fn data(&self) -> &T {
    // Returns an immutable reference to the element at the index
    &self.ring.buffer[self.index as usize]
  }

  pub fn data_mut(&mut self) -> &mut T {
    // Returns a mutable reference to the element at the index
    &mut self.ring.buffer[self.index as usize]
  }
}
A ring buffer with one packet. RingMutView points to the first empty index.

Let's implement Ring::push which pushes a single element into the buffer:

impl<'a, T> Ring<'a, T> {
  /// Push a new element, returning a mutable view to write to it
  pub fn push(&mut self) -> Result<RingMutView<'_, 'a, T>, ErrorFull> {
    if self.is_full() {
      return Err(ErrorFull);
    }
    let index = self.tail();
    self.len += 1;
    Ok(RingMutView::new(index, self))
  }
}

We write data to the buffer through the RingMutView that Ring::push returns:

let mut ring: Ring<'_, u8>;
*ring.push()?.data_mut() = 42;

Now we can implement Ring::pop, which removes the value that we just pushed from the head:

impl<'a, T> Ring<'a, T> {
  /// Pop the oldest element, returning a view to read it
  pub fn pop(&mut self) -> Option<RingView<'_, 'a, T>> {
    if self.is_empty() {
      return None;
    }
    let index = self.head();
    self.head = self.get_idx(1);
    self.len -= 1;
    Some(RingView::new(index, self))
  }
}

Ring::pop gives us a RingView to read the data:

let mut ring: Ring<'_, u8>;
assert_eq!(*ring.pop()?.data(), 42);

Views let us work with the data directly.

Introducing Closures

Closures in Rust are anonymous functions that can capture their environment. Together with views, closures let us run operations on the ring buffer that can fail. This helps when we know the data size only at runtime.

The Ring::push_many_with method uses a closure and view, RingManyMutView, to handle operations where the number of elements to insert isn't known upfront.

Here's how it works for receiving a UDP packet:

let mut socket: std::net::UdpSocket;
let written = ring.push_many_with(|mut v: RingManyMutView<'_, '_, u8>| {
  let (written, _) = socket.recv_from(v.data_mut())?;
  v.set_modified(written as u32);
  Ok(written)
})?;

Ring::push_many_with takes a closure that receives a RingManyMutView which represents a mutable slice of the ring buffer. RingManyMutView::set_modified tells the ring buffer how many elements the closure modified.

pub struct RingManyMutView<'a, 's, T> {
  modified: &'a mut u32,
  view: RingManyView<'a, 's, T>,
}

impl<'a, 's, T> RingManyMutView<'a, 's, T> {
  pub fn set_modified(&mut self, modified: u32) {
    *self.modified = modified;
  }
}

Ring::push_many_with must return the largest available empty window to write to the buffer. After the closure writes the data, we must shrink RingManyMutView to the length of that data:

Ring buffer with largest empty window exposed to RingManyMutView Ring buffer with empty window partially filled by write operation through RingManyMutView Ring buffer with trimmed RingManyMutView to the length of the inserted object

Ring::push_many_with has the following implementation:

impl<'a, T> Ring<'a, T> {
  /// Push many elements into ring
  ///
  /// # Panics
  /// Panics if the write count returned by the closure was larger than the
  /// available buffer window.
  pub fn push_many_with<R, E, F>(&mut self, f: F) -> Result<R, E>
  where
    F: FnOnce(RingManyMutView<'_, 'a, T>) -> Result<R, E>,
  {
    let index = self.tail();
    let len = self.empty_tail_window();
    let view = RingManyView::new(index, len, self);
    // `modified` can be overwritten by the calling function to shorten the committed buffer
    let modified = &mut len.clone();
    let res = f(RingManyMutView::new(modified, view));
    if res.is_ok() {
      if *modified > len {
        panic!("written count was larger than available buffer window");
      }
      self.len += *modified;
    }
    res
  }
}

Ring::empty_tail_window returns the length of contiguous empty elements at the end of the buffer.

The empty tail window is typically at the end of our buffer allocation. After the ring buffer wraps, the window may be at the start of the allocation.

Empty window at the end of the buffer Empty tail window at the beginning of the buffer after buffer wrap
impl<'a, T> Ring<'a, T> {
  /// Returns the length of contiguous empty elements at the end of the buffer
  pub fn empty_tail_window(&self) -> u32 {
    core::cmp::min(self.window(), self.capacity() - self.tail())
  }
}

Our basic implementation does not guarantee enough space to fill the window. It also does not wrap the buffer automatically.

The next article in this series extends the current framework to implement an UnorderedBuffer that can buffer UDP traffic:

Safe Systems Programming Series II: Network Buffers in Rust

Rust in Action

The integration of views and closures in this ring buffer exemplifies Rust’s zero-cost abstractions:

Efficiency: Views use references (&T or &mut T) for direct access to buffer elements. The references compile to simple pointer arithmetic with no runtime overhead. The compiler usually inlines closures, so high-level logic costs no more than manual low-level code.

Safety: Rust’s borrow checker enforces proper use of views at compile time, preventing data races or invalid memory access without runtime checks.

Expressiveness: Closures let developers put custom logic (for example, receiving network data) behind a reusable interface. Views make it simpler to work with the buffer.

The result is a high-level API that performs as efficiently as a low-level implementation. This is what zero-cost abstractions promise.

Conclusion

This Rust ring buffer combines views and closures to manage dynamic data streams, such as UDP packets. Views give safe, efficient access to the elements of the buffer. Closures allow operations that can fail on data of variable size. Together, they use Rust’s zero-cost abstractions to make a design that is safe, simple, and fast.

Back to top

Next post:

Safe Systems Programming Series II: Network Buffers in Rust