pub struct SpscRing<T> { /* private fields */ }Expand description
Lock-free single-producer/single-consumer ring with fixed capacity.
The slot buffer is allocated exactly once in SpscRing::new; push,
pop, and len never allocate or panic. Indices are monotonic u64s —
the modern technique that needs no power-of-two capacity: slot =
index % capacity, empty when head == tail, full when
tail - head == capacity. u64 indices cannot wrap within the lifetime
of any process (2^64 single ops at 1 GHz is ~584 years), and
wrapping_* keeps the arithmetic panic-free regardless.
§The sanctioned unsafe exception
This is the estate’s approved use of raw slot access: a MaybeUninit
buffer behind UnsafeCell, synchronized by two atomics. The protocol
(model-checked under loom in tests/loom_spsc.rs):
- Producer owns
tail: reads itRelaxed(own index), writes the slot, then storestail + 1withRelease. - Consumer owns
head: reads itRelaxed(own index), loadstailwithAcquire— pairing with the producer’sReleasestore so the slot write is visible before the read — then storeshead + 1withRelease. - Slot reuse: before overwriting a slot the producer loads
headwithAcquire, pairing with the consumer’sReleasestore ofhead, so the consumer’s earlier reads of that slot are complete.
Each slot is written at exactly one monotonic index and read at exactly one monotonic index, so the acquire/release pairs above are the only cross-thread ordering the protocol needs.
§Single-producer / single-consumer contract
push is the producer side, pop the consumer side: at most one thread
may push and at most one thread may pop concurrently. Concurrent pushes
or concurrent pops are a contract violation, not dynamically enforced —
this is the documented cost of the sanctioned exception. Under contention
either side may transiently observe a stale peer index and report
full/empty one step late; the caller retries.
Implementations§
Source§impl<T> SpscRing<T>
impl<T> SpscRing<T>
Sourcepub fn new(capacity: usize) -> Option<Self>
pub fn new(capacity: usize) -> Option<Self>
New ring with capacity slots; None for capacity 0 (a ring with
no slots can never hand anything off, so it is refused at
construction rather than made a permanent no-op). The only
allocation in the ring’s lifetime happens here.
Sourcepub fn push(&self, value: T) -> Result<(), T>
pub fn push(&self, value: T) -> Result<(), T>
Producer side: push one value. Err(value) when the ring is full
(transiently possible under contention — retry). Never allocates,
never panics.
§Errors
Returns Err(value) unchanged when the ring is full; the value is
not stored and the caller may retry or take it back.
Sourcepub fn pop(&self) -> Option<T>
pub fn pop(&self) -> Option<T>
Consumer side: pop the oldest value, or None when empty
(transiently possible under contention — retry). Never allocates,
never panics.