Expand description
Circular/ring buffer implementation with fixed capacity.
This module provides RingBuf, a circular buffer (also known as a ring buffer)
that operates in a First-In-First-Out (FIFO) manner. It’s particularly useful for
producer-consumer scenarios, buffering streams of data, or implementing queues
without heap allocation.
§Overview
A ring buffer is a fixed-size buffer that wraps around when it reaches the end, forming a conceptual circle. Elements are added at the head and removed from the tail, making it ideal for streaming data and FIFO queues.
§Capacity
The buffer has a compile-time fixed size SIZE, but the actual usable capacity
is SIZE - 1. This is a common implementation technique that simplifies the
empty/full detection logic.
§Use Cases
Ring buffers are excellent for:
- Buffering serial/UART data in embedded systems
- Implementing producer-consumer queues
- Audio/video frame buffers
- Network packet buffers
- Log message buffers
- Any scenario requiring a fixed-size FIFO queue
§Performance
- Push: O(1)
- Pop: O(1)
- Space efficient: uses exactly
SIZE * sizeof(T)bytes - Lock-free for single producer/single consumer scenarios
§Examples
use planck_noalloc::ringbuf::RingBuf;
// Create a ring buffer with size 8 (capacity 7)
let mut buf = RingBuf::<u8, 8>::new();
// Push some data
buf.push(1);
buf.push(2);
buf.push(3);
// Pop in FIFO order
assert_eq!(buf.pop(), Some(1));
assert_eq!(buf.pop(), Some(2));
assert_eq!(buf.len(), 1);
// Can push more after popping
buf.push(4);
buf.push(5);
assert_eq!(buf.len(), 3);§Error Handling
use planck_noalloc::ringbuf::RingBuf;
let mut buf = RingBuf::<u8, 4>::new();
// Fill to capacity (3 elements for size 4)
buf.push(1);
buf.push(2);
buf.push(3);
// Trying to push beyond capacity returns an error
assert!(buf.try_push(4).is_err());
assert!(buf.is_full());
// After popping, we can push again
buf.pop();
assert!(buf.try_push(4).is_ok());Structs§
- RingBuf
- A Circular / Ring buffer.