Expand description
A fast, small single-producer single-consumer (SPSC) ringbuffer designed
for low-latency and high-throughput exchange between a single writer and
a single reader. This crate is #![no_std] and uses alloc internally; it provides a
minimal, ergonomic API that works well from no_std contexts that supply
an allocator as well as from normal std programs and examples.
Important design points:
- The ringbuffer capacity is specified at runtime via the
ringbufferconstructor and must be a power of two. The implementation uses a bitmask to wrap indices which is much faster than a modulo operation and reduces runtime overhead in hot paths. - The API is non-blocking:
RingBufferWriter::pushreturnsSome(T)immediately when the buffer is full (giving back ownership of the value), andRingBufferReader::pullreturnsNoneimmediately when the buffer is empty. Typical usage is to yield or retry in those cases.
NOTE: elements remaining in the buffer are dropped when the internal storage is deallocated.
This happens when both RingBufferReader and RingBufferWriter are dropped.
§Example
use ringbuffer_spsc::ringbuffer;
const N: usize = 8;
// Create a ringbuffer with capacity 16 (must be power of two)
let (mut writer, mut reader) = ringbuffer::<usize>(16);
// Producer
std::thread::spawn(move || for i in 0..N {
if writer.push(i).is_some() {
std::thread::yield_now();
}
});
// Consumer
let mut i = 0;
while i < N {
match reader.pull() {
Some(_) => i += 1,
None => std::thread::yield_now(),
}
}Structs§
- Ring
Buffer Reader - Reader handle of the ringbuffer.
- Ring
Buffer Writer - Writer handle of the ringbuffer.
Functions§
- ringbuffer
- Create a new ringbuffer with a fixed capacity.