Skip to main content

Crate spsc_ring

Crate spsc_ring 

Source
Expand description

§spsc-ring

Lock-free SPSC ring buffer.

§Design

Sequence-number protocol: each slot carries a stamp that the producer writes after storing the value, and the consumer checks before reading. Acquire/Release ordering only (no SeqCst). Cache-line padding prevents false sharing between producer and consumer cursors.

The SPSC contract is enforced at compile time: ring returns a (Producer<T>, Consumer<T>) pair. Each half is Send but not Clone.

§Example

use spsc_ring::{ring, TryRecvError, TrySendError};
use std::thread;

let (tx, rx) = ring::<u64>(64).unwrap();

thread::spawn(move || {
    for i in 0..100u64 {
        loop {
            match tx.try_push(i) {
                Ok(()) => break,
                Err(TrySendError::Full(_)) => std::hint::spin_loop(),
                Err(TrySendError::Disconnected(_)) => return,
            }
        }
    }
});

let mut received = Vec::new();
while received.len() < 100 {
    match rx.try_pop() {
        Ok(v) => received.push(v),
        Err(TryRecvError::Empty) => std::hint::spin_loop(),
        Err(TryRecvError::Disconnected) => break,
    }
}
assert_eq!(received, (0..100).collect::<Vec<_>>());

Structs§

Consumer
Read half of the SPSC ring. Not Clone — only one consumer exists.
InvalidCapacity
Error returned by ring when capacity is zero or not a power of two.
Producer
Write half of the SPSC ring. Not Clone — only one producer exists.
RecvError
Error returned by Consumer::pop when the producer has been dropped.
SendError
Error returned by Producer::push when the consumer has been dropped.

Enums§

TryRecvError
Error returned by Consumer::try_pop.
TrySendError
Error returned by Producer::try_push.
WaitStrategy
Strategy used by blocking Producer::push and Consumer::pop while waiting.

Functions§

ring
Create an SPSC ring buffer with the given capacity (must be a power of 2).