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

> Build a ring buffer in Rust for a reliable UDP protocol. Views and closures give safe access and insertions that can fail, with zero-cost abstractions.

- Author: Jakub Łabor
- Published: 2025-09-04
- Source: https://suficio.com/blog/2025-09-04-ring-buffer/

## 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:
>
> - [Safe Systems Programming Series II: Network Buffers in Rust](https://suficio.com/blog/2025-09-16-unordered-buffer/)
> - [Safe Systems Programming Series III: Managing Reliable Sequenced Data in Rust](https://suficio.com/blog/2026-12-06-ordered-buffer/)

## 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:

```rust
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.](https://suficio.com/blog/2025-09-04-ring-buffer/images/introduction-ring-buffer-01.drawio.svg)

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.](https://suficio.com/blog/2025-09-04-ring-buffer/images/introduction-ring-buffer-02.drawio.svg)
![A ring buffer with three packets of different lengths. The tail pointer is at the next empty index, and the length is 8.](https://suficio.com/blog/2025-09-04-ring-buffer/images/introduction-ring-buffer-03.drawio.svg)

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.](https://suficio.com/blog/2025-09-04-ring-buffer/images/introduction-ring-buffer-04.drawio.svg)

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.](https://suficio.com/blog/2025-09-04-ring-buffer/images/introduction-ring-buffer-05.drawio.svg)

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.](https://suficio.com/blog/2025-09-04-ring-buffer/images/introduction-ring-buffer-06.drawio.svg)

> 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](https://www.snellman.net/blog/archive/2016-12-13-ring-buffers/)

## 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.

```rust
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.

```rust
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`:

```rust
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.](https://suficio.com/blog/2025-09-04-ring-buffer/images/views-01.drawio.svg)

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

```rust
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:

```rust
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:

```rust
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:

```rust
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:

```rust
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.

```rust
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](https://suficio.com/blog/2025-09-04-ring-buffer/images/closures-01.drawio.svg)
![Ring buffer with empty window partially filled by write operation through RingManyMutView](https://suficio.com/blog/2025-09-04-ring-buffer/images/closures-02.drawio.svg)
![Ring buffer with trimmed RingManyMutView to the length of the inserted object](https://suficio.com/blog/2025-09-04-ring-buffer/images/closures-03.drawio.svg)

`Ring::push_many_with` has the following implementation:

```rust
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](https://suficio.com/blog/2025-09-04-ring-buffer/images/closures-04.drawio.svg)
> ![Empty tail window at the beginning of the buffer after buffer wrap](https://suficio.com/blog/2025-09-04-ring-buffer/images/closures-05.drawio.svg)
>
> ```rust
> 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](https://suficio.com/blog/2025-09-16-unordered-buffer/)

## 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.
