pub struct SpscRing<T, const CAP: usize> { /* private fields */ }Expand description
Lock-free single-producer/single-consumer ring, fixed const capacity.
The design is the Vyukov bounded queue: every slot carries a sequence
number, the cursors advance monotonically and index slots by mask
(CAP must be a power of two, checked at compile time), and the two
cursors sit on their own cache lines (repr(align(64))) so producer
and consumer never false-share. The slot buffer is allocated exactly
once in SpscRing::new; try_push, try_pop, and len never
allocate or panic.
§The sanctioned unsafe exception
This is the estate’s approved use of raw slot access: UnsafeCell
slots behind per-slot sequence atomics. The handoff edge is the
standard acquire/release message-passing pair, zero SeqCst
(model-checked under loom in tests/loom_spsc.rs):
- Producer: reads its cursor
Relaxed, loads the slot sequence withAcquire(empty slot confirmed), writes the payload, storespos + 1withRelease(publish), then advances its own cursorRelaxed. - Consumer: mirror image —
Acquireload of the sequence confirms a published value, takes the payload, storespos + CAPwithRelease(slot reusable one lap later), advances its cursorRelaxed.
§Single-producer / single-consumer contract
try_push is the producer side, try_pop the consumer side: at most
one thread may push and at most one may pop concurrently. Concurrent
try_pushes or try_pops are a contract violation, not dynamically
enforced — the documented cost of the sanctioned exception. Both
operations are lock-free: neither side ever blocks; a full ring
hands the value back, an empty ring hands back None, and the
caller retries.
Implementations§
Source§impl<T, const CAP: usize> SpscRing<T, CAP>
impl<T, const CAP: usize> SpscRing<T, CAP>
Sourcepub fn new() -> Self
pub fn new() -> Self
New ring with CAP slots. Compile-time refusal of non-power-of-two
capacities (the mask indexing requires one) and of CAP < 2: with a
single slot the sequence protocol’s two transitions (pos + 1 on
write, pos + CAP on consume) collide on the same number, and the
producer would overwrite an unconsumed value (a lost update that a
lenient loom assertion cannot catch — the model found it). The only
allocation in the ring’s lifetime happens here.
Sourcepub fn try_push(&self, value: T) -> Option<T>
pub fn try_push(&self, value: T) -> Option<T>
Producer side: push one value, or hand it straight back when the
ring is full. Lock-free, never blocks, never allocates, never
panics. The returned Some(value) is unchanged and not stored.
Sourcepub fn try_pop(&self) -> Option<T>
pub fn try_pop(&self) -> Option<T>
Consumer side: pop the oldest value, or None when empty.
Lock-free, never blocks, never allocates, never panics.