Skip to main content

ds_ring/
lib.rs

1//! Fixed-capacity ring buffers: a stack-allocated sample/latency ring and a
2//! lock-free single-producer/single-consumer ring, loom-tested.
3//!
4//! ds-kit roadmap Part 3.2: latency/sample history and cross-thread handoff
5//! both want bounded queues with zero steady-state allocation. This crate is
6//! the canonical leaf (layering L0: zero estate deps — any tier may depend
7//! on it; the A0 survey measured four crates duplicating ring mechanics to
8//! avoid upward edges).
9//!
10//! Hot path contract: no panics, no syscalls, and no allocation after
11//! construction — [`SampleRing`] never allocates at all, [`SpscRing`]
12//! allocates its slot buffer exactly once in [`SpscRing::new`]. The naive
13//! reference lives in [`oracle`] and is kept forever for differential
14//! testing (ds-kit AGENTS.md).
15//!
16//! [`SpscRing`] is the estate's **sanctioned unsafe exception**: `UnsafeCell`
17//! slots behind per-slot sequence atomics (Vyukov bounded-queue protocol),
18//! with every block annotated with the acquire/release invariant it relies
19//! on and the whole protocol model-checked under `loom`
20//! (`tests/loom_spsc.rs`). [`SampleRing`] contains no unsafe code.
21
22#![no_std]
23extern crate alloc;
24
25// loom replaces the core atomics with modeled ones when the workspace runs
26// `RUSTFLAGS="--cfg loom" cargo test --test loom_spsc` (roadmap Part 3.2).
27#[cfg(not(loom))]
28use alloc::sync::Arc;
29#[cfg(not(loom))]
30use core::sync::atomic::{AtomicUsize, Ordering};
31#[cfg(loom)]
32use loom::sync::atomic::{AtomicUsize, Ordering};
33#[cfg(loom)]
34use loom::sync::Arc;
35
36use alloc::boxed::Box;
37use alloc::vec::Vec;
38use core::cell::UnsafeCell;
39use core::fmt;
40
41/// The forever-oracle for differential testing: naive `Vec` + shift-on-pop
42/// spec forms, not optimized. Never deleted, never optimized.
43pub mod oracle;
44
45/// Fixed-capacity sample/latency ring, stack-allocated, oldest-first.
46///
47/// Capacity `N` is a const generic: the whole ring lives inline in the
48/// owner (`[Option<T>; N]` plus two indices), so construction allocates
49/// nothing and `push` allocates nothing — eviction returns the oldest
50/// value by move. FIFO order is preserved: `iter` walks oldest-first and
51/// `push` returns the evicted oldest when full.
52///
53/// With `N == 0` nothing can be stored; [`SampleRing::push`] hands the
54/// value straight back (`Some(value)`), i.e. the value is "evicted" the
55/// moment it arrives. There is deliberately no indexing API.
56///
57/// ```
58/// use ds_ring::SampleRing;
59///
60/// let mut ring = SampleRing::<u64, 2>::new();
61/// assert_eq!(ring.push(1), None);
62/// assert_eq!(ring.push(2), None);
63/// assert_eq!(ring.push(3), Some(1)); // 1 is the evicted oldest
64/// assert_eq!(ring.iter().copied().collect::<Vec<_>>(), vec![2, 3]);
65/// assert_eq!(ring.last(), Some(&3));
66/// ```
67#[derive(Clone)]
68pub struct SampleRing<T, const N: usize> {
69    /// Index of the oldest live value (`0..N` once any value was stored;
70    /// never advanced when empty, so `slots.get` below never sees `% 0`).
71    head: usize,
72    /// Number of live values (`0..=N`).
73    len: usize,
74    /// Ring slots; occupied iff within the logical window.
75    slots: [Option<T>; N],
76}
77
78impl<T, const N: usize> SampleRing<T, N> {
79    /// New empty ring; nothing is allocated (the slots are inline).
80    #[must_use]
81    pub fn new() -> Self {
82        Self {
83            head: 0,
84            len: 0,
85            slots: core::array::from_fn(|_| None),
86        }
87    }
88
89    /// Push one value. Returns `None` when the value was accepted without
90    /// eviction, `Some(old)` when the ring was full and `old` (the oldest
91    /// value) was evicted to make room. With `N == 0` the pushed value is
92    /// returned immediately (nothing can be stored). Never allocates,
93    /// never panics.
94    pub fn push(&mut self, value: T) -> Option<T> {
95        if N == 0 {
96            return Some(value);
97        }
98        if self.len == N {
99            // Full: the write slot coincides with `head`, the oldest live
100            // value, so eviction and insertion are one `replace`. `head < N`
101            // is an invariant, so the slot always exists; were it empty
102            // (impossible while `len == N`), the value is still stored and
103            // `None` honestly reports "no eviction".
104            let evicted = match self.slots.get_mut(self.head) {
105                Some(slot) => slot.replace(value),
106                // Unreachable (`head < N` is an invariant): nothing was
107                // stored, so bounce the value back instead of panicking
108                // or leaking it.
109                None => return Some(value),
110            };
111            self.head = (self.head + 1) % N;
112            return evicted;
113        }
114        let slot = (self.head + self.len) % N;
115        match self.slots.get_mut(slot) {
116            Some(cell) => {
117                *cell = Some(value);
118                self.len += 1;
119                None
120            }
121            // Unreachable (`slot < N` by construction): bounce the value
122            // back rather than panic or leak it.
123            None => Some(value),
124        }
125    }
126
127    /// Oldest-first iterator over the live values.
128    #[must_use]
129    pub fn iter(&self) -> Iter<'_, T, N> {
130        Iter { ring: self, pos: 0 }
131    }
132
133    /// Number of live values (`0..=N`).
134    #[must_use]
135    pub const fn len(&self) -> usize {
136        self.len
137    }
138
139    /// True when the ring holds no values.
140    #[must_use]
141    pub const fn is_empty(&self) -> bool {
142        self.len == 0
143    }
144
145    /// Newest value, or `None` when empty.
146    #[must_use]
147    pub fn last(&self) -> Option<&T> {
148        if self.len == 0 {
149            return None;
150        }
151        let slot = (self.head + self.len - 1) % N;
152        self.slots.get(slot).and_then(Option::as_ref)
153    }
154}
155
156impl<T, const N: usize> Default for SampleRing<T, N> {
157    fn default() -> Self {
158        Self::new()
159    }
160}
161
162impl<T: fmt::Debug, const N: usize> fmt::Debug for SampleRing<T, N> {
163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164        f.debug_list().entries(self.iter()).finish()
165    }
166}
167
168impl<'a, T, const N: usize> IntoIterator for &'a SampleRing<T, N> {
169    type Item = &'a T;
170    type IntoIter = Iter<'a, T, N>;
171
172    fn into_iter(self) -> Self::IntoIter {
173        self.iter()
174    }
175}
176
177/// Oldest-first iterator over a [`SampleRing`]; exact-size.
178#[derive(Clone)]
179pub struct Iter<'a, T, const N: usize> {
180    /// Borrowed ring.
181    ring: &'a SampleRing<T, N>,
182    /// Steps taken from the oldest live value.
183    pos: usize,
184}
185
186impl<'a, T, const N: usize> Iterator for Iter<'a, T, N> {
187    type Item = &'a T;
188
189    fn next(&mut self) -> Option<Self::Item> {
190        if self.pos >= self.ring.len {
191            // Also covers N == 0 (len == 0), so the `% N` below never sees 0.
192            return None;
193        }
194        let slot = (self.ring.head + self.pos) % N;
195        self.pos += 1;
196        // `slot < N` by construction; a live slot always holds `Some`.
197        self.ring.slots.get(slot).and_then(Option::as_ref)
198    }
199
200    fn size_hint(&self) -> (usize, Option<usize>) {
201        let remaining = self.ring.len - self.pos;
202        (remaining, Some(remaining))
203    }
204}
205
206impl<T, const N: usize> ExactSizeIterator for Iter<'_, T, N> {}
207
208/// Lock-free single-producer/single-consumer ring, fixed const capacity.
209///
210/// The design is the Vyukov bounded queue: every slot carries a sequence
211/// number, the cursors advance monotonically and index slots by mask
212/// (`CAP` must be a power of two, checked at compile time), and the two
213/// cursors sit on their own cache lines (`repr(align(64))`) so producer
214/// and consumer never false-share. The slot buffer is allocated exactly
215/// once in [`SpscRing::new`]; `try_push`, `try_pop`, and `len` never
216/// allocate or panic.
217///
218/// # The sanctioned unsafe exception
219///
220/// This is the estate's approved use of raw slot access: `UnsafeCell`
221/// slots behind per-slot sequence atomics. The handoff edge is the
222/// standard acquire/release message-passing pair, zero `SeqCst`
223/// (model-checked under `loom` in `tests/loom_spsc.rs`):
224///
225/// - **Producer**: reads its cursor `Relaxed`, loads the slot sequence
226///   with `Acquire` (empty slot confirmed), writes the payload, stores
227///   `pos + 1` with `Release` (publish), then advances its own cursor
228///   `Relaxed`.
229/// - **Consumer**: mirror image — `Acquire` load of the sequence
230///   confirms a published value, takes the payload, stores
231///   `pos + CAP` with `Release` (slot reusable one lap later), advances
232///   its cursor `Relaxed`.
233///
234/// # Single-producer / single-consumer contract
235///
236/// `try_push` is the producer side, `try_pop` the consumer side: at most
237/// one thread may push and at most one may pop concurrently. Concurrent
238/// `try_push`es or `try_pop`s are a contract violation, not dynamically
239/// enforced — the documented cost of the sanctioned exception. Both
240/// operations are lock-free: neither side ever blocks; a full ring
241/// hands the value back, an empty ring hands back [`None`], and the
242/// caller retries.
243pub struct SpscRing<T, const CAP: usize> {
244    /// Fixed slot count minus one (`CAP` is a power of two, checked at
245    /// compile time), so `pos & mask` replaces a modulo.
246    mask: usize,
247    /// Producer cursor (slots written), padded to its own cache line.
248    head: PaddedCursor,
249    /// Consumer cursor (slots read), padded to its own cache line.
250    tail: PaddedCursor,
251    /// One sequence-guarded slot per ring position; allocated once.
252    slots: Box<[Slot<T>]>,
253}
254
255/// Pads a cursor to a full cache line so the producer and consumer
256/// cursors never share a line (false sharing would serialize the two
257/// threads on the hardware coherence protocol).
258#[repr(align(64))]
259#[derive(Default)]
260struct PaddedCursor(AtomicUsize);
261
262/// One ring slot: a sequence number guarding an `Option` payload.
263struct Slot<T> {
264    /// Lap counter: `pos` when empty and claimable, `pos + 1` when full,
265    /// `pos + CAP` after the consumer took the value (next lap).
266    sequence: AtomicUsize,
267    /// Payload; `None` exactly while the slot is logically empty.
268    value: UnsafeCell<Option<T>>,
269}
270
271// SAFETY: `try_push` runs on the producer only, `try_pop` on the consumer
272// only (struct doc). `T: Send` makes values safe to hand off between those
273// two threads; slot access is mediated by the acquire/release protocol
274// documented on [`SpscRing`] and model-checked under loom.
275#[allow(unsafe_code)] // sanctioned unsafe exception (crate docs, ds-kit AGENTS.md)
276unsafe impl<T: Send, const CAP: usize> Send for SpscRing<T, CAP> {}
277
278// SAFETY: shared access is split by role — the producer writes only its
279// cursor and empty slots, the consumer reads only its cursor and full
280// slots, and the acquire/release pairs on the slot sequences order every
281// payload access.
282#[allow(unsafe_code)] // sanctioned unsafe exception (crate docs, ds-kit AGENTS.md)
283unsafe impl<T: Send, const CAP: usize> Sync for SpscRing<T, CAP> {}
284
285// Raw slot access lives inside this impl: `unsafe_code` is the
286// estate-sanctioned exception (crate docs, ds-kit AGENTS.md) — every unsafe
287// block below carries its own SAFETY comment citing the sequence protocol
288// documented on [`SpscRing`], model-checked under loom.
289#[allow(unsafe_code)]
290impl<T, const CAP: usize> SpscRing<T, CAP> {
291    /// New ring with `CAP` slots. Compile-time refusal of non-power-of-two
292    /// capacities (the mask indexing requires one) and of `CAP < 2`: with a
293    /// single slot the sequence protocol's two transitions (`pos + 1` on
294    /// write, `pos + CAP` on consume) collide on the same number, and the
295    /// producer would overwrite an unconsumed value (a lost update that a
296    /// lenient loom assertion cannot catch — the model found it). The only
297    /// allocation in the ring's lifetime happens here.
298    #[must_use]
299    pub fn new() -> Self {
300        const {
301            assert!(
302                CAP.is_power_of_two() && CAP >= 2,
303                "SpscRing capacity must be a power of two >= 2 (CAP == 1 makes \
304                 the sequence protocol's write and consume transitions collide, \
305                 losing unconsumed values)"
306            );
307        }
308        let slots = (0..CAP)
309            .map(|i| Slot {
310                sequence: AtomicUsize::new(i),
311                value: UnsafeCell::new(None),
312            })
313            .collect::<Vec<_>>();
314        Self {
315            mask: CAP - 1,
316            head: PaddedCursor::default(),
317            tail: PaddedCursor::default(),
318            slots: slots.into_boxed_slice(),
319        }
320    }
321
322    /// Producer side: push one value, or hand it straight back when the
323    /// ring is full. Lock-free, never blocks, never allocates, never
324    /// panics. The returned `Some(value)` is unchanged and not stored.
325    #[must_use = "a full ring hands the value back: dropping it loses data"]
326    pub fn try_push(&self, value: T) -> Option<T> {
327        let pos = self.head.0.load(Ordering::Relaxed);
328        #[allow(clippy::indexing_slicing)] // pos & mask < CAP by construction
329        let slot = &self.slots[pos & self.mask];
330        // Acquire pairs with the consumer's Release store of `pos + CAP`:
331        // the previous occupant of this slot was fully read before reuse.
332        if slot.sequence.load(Ordering::Acquire) != pos {
333            return Some(value); // full
334        }
335        // SAFETY: sequence == pos means the slot is empty and exclusively
336        // claimable by the (single) producer.
337        unsafe {
338            *slot.value.get() = Some(value);
339        }
340        // Release publishes the payload write to the consumer's Acquire
341        // load of the sequence.
342        slot.sequence.store(pos.wrapping_add(1), Ordering::Release);
343        self.head.0.store(pos.wrapping_add(1), Ordering::Relaxed);
344        None
345    }
346
347    /// Consumer side: pop the oldest value, or [`None`] when empty.
348    /// Lock-free, never blocks, never allocates, never panics.
349    #[must_use]
350    pub fn try_pop(&self) -> Option<T> {
351        let pos = self.tail.0.load(Ordering::Relaxed);
352        #[allow(clippy::indexing_slicing)] // pos & mask < CAP by construction
353        let slot = &self.slots[pos & self.mask];
354        // Acquire pairs with the producer's Release store of `pos + 1`:
355        // the payload write is visible before this read.
356        if slot.sequence.load(Ordering::Acquire) != pos + 1 {
357            return None; // empty
358        }
359        // SAFETY: sequence == pos + 1 means a value was published (release)
360        // and this (single) consumer owns the take.
361        let value = unsafe { (*slot.value.get()).take() };
362        // Release marks the slot reusable one lap later (pos + CAP).
363        slot.sequence
364            .store(pos.wrapping_add(CAP), Ordering::Release);
365        self.tail.0.store(pos.wrapping_add(1), Ordering::Relaxed);
366        value
367    }
368
369    /// Approximate occupancy. `Relaxed` loads, so the pair may lag
370    /// concurrent progress; a hint, never a correctness input.
371    #[must_use]
372    pub fn len(&self) -> usize {
373        self.head
374            .0
375            .load(Ordering::Relaxed)
376            .wrapping_sub(self.tail.0.load(Ordering::Relaxed))
377    }
378
379    /// True when the ring appears empty (see [`len`](Self::len)).
380    #[must_use]
381    pub fn is_empty(&self) -> bool {
382        self.len() == 0
383    }
384}
385
386impl<T, const CAP: usize> Default for SpscRing<T, CAP> {
387    fn default() -> Self {
388        Self::new()
389    }
390}
391
392impl<T, const CAP: usize> fmt::Debug for SpscRing<T, CAP> {
393    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394        // Contents are never printed: reading slots here would race the
395        // producer/consumer roles and need unsafe.
396        f.debug_struct("SpscRing")
397            .field("cap", &CAP)
398            .field("len", &self.len())
399            .finish()
400    }
401}
402
403/// Pair a ring with its two ends for handing to separate threads. The
404/// ring itself lives in an `Arc`; the handles are the only way the two
405/// threads reach it, which documents the SPSC contract at the type level.
406#[must_use]
407pub fn channel<T, const CAP: usize>() -> (SpscSender<T, CAP>, SpscReceiver<T, CAP>) {
408    let ring = Arc::new(SpscRing::new());
409    (
410        SpscSender {
411            ring: Arc::clone(&ring),
412        },
413        SpscReceiver { ring },
414    )
415}
416
417/// Producer handle: the only way to `try_push` into a [`channel`] ring.
418pub struct SpscSender<T, const CAP: usize> {
419    ring: Arc<SpscRing<T, CAP>>,
420}
421
422impl<T, const CAP: usize> SpscSender<T, CAP> {
423    /// Enqueues without blocking; `Err(value)` when full.
424    ///
425    /// # Errors
426    /// Returns the value back when the ring is full (lock-free bound).
427    #[inline]
428    pub fn send(&self, value: T) -> Result<(), T> {
429        match self.ring.try_push(value) {
430            None => Ok(()),
431            Some(back) => Err(back),
432        }
433    }
434}
435
436/// Consumer handle: the only way to `try_pop` from a [`channel`] ring.
437pub struct SpscReceiver<T, const CAP: usize> {
438    ring: Arc<SpscRing<T, CAP>>,
439}
440
441impl<T, const CAP: usize> SpscReceiver<T, CAP> {
442    /// Dequeues without blocking; [`None`] when empty.
443    #[inline]
444    #[must_use]
445    pub fn recv(&self) -> Option<T> {
446        self.ring.try_pop()
447    }
448}