ds-ring 0.2.0

Fixed-capacity ring buffers: sample/latency ring and SPSC, loom-tested
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! Fixed-capacity ring buffers: a stack-allocated sample/latency ring and a
//! lock-free single-producer/single-consumer ring, loom-tested.
//!
//! ds-kit roadmap Part 3.2: latency/sample history and cross-thread handoff
//! both want bounded queues with zero steady-state allocation. This crate is
//! the canonical leaf (layering L0: zero estate deps — any tier may depend
//! on it; the A0 survey measured four crates duplicating ring mechanics to
//! avoid upward edges).
//!
//! Hot path contract: no panics, no syscalls, and no allocation after
//! construction — [`SampleRing`] never allocates at all, [`SpscRing`]
//! allocates its slot buffer exactly once in [`SpscRing::new`]. The naive
//! reference lives in [`oracle`] and is kept forever for differential
//! testing (ds-kit AGENTS.md).
//!
//! [`SpscRing`] is the estate's **sanctioned unsafe exception**: `UnsafeCell`
//! slots behind per-slot sequence atomics (Vyukov bounded-queue protocol),
//! with every block annotated with the acquire/release invariant it relies
//! on and the whole protocol model-checked under `loom`
//! (`tests/loom_spsc.rs`). [`SampleRing`] contains no unsafe code.

#![no_std]
extern crate alloc;

// loom replaces the core atomics with modeled ones when the workspace runs
// `RUSTFLAGS="--cfg loom" cargo test --test loom_spsc` (roadmap Part 3.2).
#[cfg(not(loom))]
use alloc::sync::Arc;
#[cfg(not(loom))]
use core::sync::atomic::{AtomicUsize, Ordering};
#[cfg(loom)]
use loom::sync::atomic::{AtomicUsize, Ordering};
#[cfg(loom)]
use loom::sync::Arc;

use alloc::boxed::Box;
use alloc::vec::Vec;
use core::cell::UnsafeCell;
use core::fmt;

/// The forever-oracle for differential testing: naive `Vec` + shift-on-pop
/// spec forms, not optimized. Never deleted, never optimized.
pub mod oracle;

/// Fixed-capacity sample/latency ring, stack-allocated, oldest-first.
///
/// Capacity `N` is a const generic: the whole ring lives inline in the
/// owner (`[Option<T>; N]` plus two indices), so construction allocates
/// nothing and `push` allocates nothing — eviction returns the oldest
/// value by move. FIFO order is preserved: `iter` walks oldest-first and
/// `push` returns the evicted oldest when full.
///
/// With `N == 0` nothing can be stored; [`SampleRing::push`] hands the
/// value straight back (`Some(value)`), i.e. the value is "evicted" the
/// moment it arrives. There is deliberately no indexing API.
///
/// ```
/// use ds_ring::SampleRing;
///
/// let mut ring = SampleRing::<u64, 2>::new();
/// assert_eq!(ring.push(1), None);
/// assert_eq!(ring.push(2), None);
/// assert_eq!(ring.push(3), Some(1)); // 1 is the evicted oldest
/// assert_eq!(ring.iter().copied().collect::<Vec<_>>(), vec![2, 3]);
/// assert_eq!(ring.last(), Some(&3));
/// ```
#[derive(Clone)]
pub struct SampleRing<T, const N: usize> {
    /// Index of the oldest live value (`0..N` once any value was stored;
    /// never advanced when empty, so `slots.get` below never sees `% 0`).
    head: usize,
    /// Number of live values (`0..=N`).
    len: usize,
    /// Ring slots; occupied iff within the logical window.
    slots: [Option<T>; N],
}

impl<T, const N: usize> SampleRing<T, N> {
    /// New empty ring; nothing is allocated (the slots are inline).
    #[must_use]
    pub fn new() -> Self {
        Self {
            head: 0,
            len: 0,
            slots: core::array::from_fn(|_| None),
        }
    }

    /// Push one value. Returns `None` when the value was accepted without
    /// eviction, `Some(old)` when the ring was full and `old` (the oldest
    /// value) was evicted to make room. With `N == 0` the pushed value is
    /// returned immediately (nothing can be stored). Never allocates,
    /// never panics.
    pub fn push(&mut self, value: T) -> Option<T> {
        if N == 0 {
            return Some(value);
        }
        if self.len == N {
            // Full: the write slot coincides with `head`, the oldest live
            // value, so eviction and insertion are one `replace`. `head < N`
            // is an invariant, so the slot always exists; were it empty
            // (impossible while `len == N`), the value is still stored and
            // `None` honestly reports "no eviction".
            let evicted = match self.slots.get_mut(self.head) {
                Some(slot) => slot.replace(value),
                // Unreachable (`head < N` is an invariant): nothing was
                // stored, so bounce the value back instead of panicking
                // or leaking it.
                None => return Some(value),
            };
            self.head = (self.head + 1) % N;
            return evicted;
        }
        let slot = (self.head + self.len) % N;
        match self.slots.get_mut(slot) {
            Some(cell) => {
                *cell = Some(value);
                self.len += 1;
                None
            }
            // Unreachable (`slot < N` by construction): bounce the value
            // back rather than panic or leak it.
            None => Some(value),
        }
    }

    /// Oldest-first iterator over the live values.
    #[must_use]
    pub fn iter(&self) -> Iter<'_, T, N> {
        Iter { ring: self, pos: 0 }
    }

    /// Number of live values (`0..=N`).
    #[must_use]
    pub const fn len(&self) -> usize {
        self.len
    }

    /// True when the ring holds no values.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Newest value, or `None` when empty.
    #[must_use]
    pub fn last(&self) -> Option<&T> {
        if self.len == 0 {
            return None;
        }
        let slot = (self.head + self.len - 1) % N;
        self.slots.get(slot).and_then(Option::as_ref)
    }
}

impl<T, const N: usize> Default for SampleRing<T, N> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: fmt::Debug, const N: usize> fmt::Debug for SampleRing<T, N> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_list().entries(self.iter()).finish()
    }
}

impl<'a, T, const N: usize> IntoIterator for &'a SampleRing<T, N> {
    type Item = &'a T;
    type IntoIter = Iter<'a, T, N>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// Oldest-first iterator over a [`SampleRing`]; exact-size.
#[derive(Clone)]
pub struct Iter<'a, T, const N: usize> {
    /// Borrowed ring.
    ring: &'a SampleRing<T, N>,
    /// Steps taken from the oldest live value.
    pos: usize,
}

impl<'a, T, const N: usize> Iterator for Iter<'a, T, N> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.pos >= self.ring.len {
            // Also covers N == 0 (len == 0), so the `% N` below never sees 0.
            return None;
        }
        let slot = (self.ring.head + self.pos) % N;
        self.pos += 1;
        // `slot < N` by construction; a live slot always holds `Some`.
        self.ring.slots.get(slot).and_then(Option::as_ref)
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.ring.len - self.pos;
        (remaining, Some(remaining))
    }
}

impl<T, const N: usize> ExactSizeIterator for Iter<'_, T, N> {}

/// 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
///   with `Acquire` (empty slot confirmed), writes the payload, stores
///   `pos + 1` with `Release` (publish), then advances its own cursor
///   `Relaxed`.
/// - **Consumer**: mirror image — `Acquire` load of the sequence
///   confirms a published value, takes the payload, stores
///   `pos + CAP` with `Release` (slot reusable one lap later), advances
///   its cursor `Relaxed`.
///
/// # 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_push`es or `try_pop`s 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.
pub struct SpscRing<T, const CAP: usize> {
    /// Fixed slot count minus one (`CAP` is a power of two, checked at
    /// compile time), so `pos & mask` replaces a modulo.
    mask: usize,
    /// Producer cursor (slots written), padded to its own cache line.
    head: PaddedCursor,
    /// Consumer cursor (slots read), padded to its own cache line.
    tail: PaddedCursor,
    /// One sequence-guarded slot per ring position; allocated once.
    slots: Box<[Slot<T>]>,
}

/// Pads a cursor to a full cache line so the producer and consumer
/// cursors never share a line (false sharing would serialize the two
/// threads on the hardware coherence protocol).
#[repr(align(64))]
#[derive(Default)]
struct PaddedCursor(AtomicUsize);

/// One ring slot: a sequence number guarding an `Option` payload.
struct Slot<T> {
    /// Lap counter: `pos` when empty and claimable, `pos + 1` when full,
    /// `pos + CAP` after the consumer took the value (next lap).
    sequence: AtomicUsize,
    /// Payload; `None` exactly while the slot is logically empty.
    value: UnsafeCell<Option<T>>,
}

// SAFETY: `try_push` runs on the producer only, `try_pop` on the consumer
// only (struct doc). `T: Send` makes values safe to hand off between those
// two threads; slot access is mediated by the acquire/release protocol
// documented on [`SpscRing`] and model-checked under loom.
#[allow(unsafe_code)] // sanctioned unsafe exception (crate docs, ds-kit AGENTS.md)
unsafe impl<T: Send, const CAP: usize> Send for SpscRing<T, CAP> {}

// SAFETY: shared access is split by role — the producer writes only its
// cursor and empty slots, the consumer reads only its cursor and full
// slots, and the acquire/release pairs on the slot sequences order every
// payload access.
#[allow(unsafe_code)] // sanctioned unsafe exception (crate docs, ds-kit AGENTS.md)
unsafe impl<T: Send, const CAP: usize> Sync for SpscRing<T, CAP> {}

// Raw slot access lives inside this impl: `unsafe_code` is the
// estate-sanctioned exception (crate docs, ds-kit AGENTS.md) — every unsafe
// block below carries its own SAFETY comment citing the sequence protocol
// documented on [`SpscRing`], model-checked under loom.
#[allow(unsafe_code)]
impl<T, const CAP: usize> SpscRing<T, CAP> {
    /// 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.
    #[must_use]
    pub fn new() -> Self {
        const {
            assert!(
                CAP.is_power_of_two() && CAP >= 2,
                "SpscRing capacity must be a power of two >= 2 (CAP == 1 makes \
                 the sequence protocol's write and consume transitions collide, \
                 losing unconsumed values)"
            );
        }
        let slots = (0..CAP)
            .map(|i| Slot {
                sequence: AtomicUsize::new(i),
                value: UnsafeCell::new(None),
            })
            .collect::<Vec<_>>();
        Self {
            mask: CAP - 1,
            head: PaddedCursor::default(),
            tail: PaddedCursor::default(),
            slots: slots.into_boxed_slice(),
        }
    }

    /// 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.
    #[must_use = "a full ring hands the value back: dropping it loses data"]
    pub fn try_push(&self, value: T) -> Option<T> {
        let pos = self.head.0.load(Ordering::Relaxed);
        #[allow(clippy::indexing_slicing)] // pos & mask < CAP by construction
        let slot = &self.slots[pos & self.mask];
        // Acquire pairs with the consumer's Release store of `pos + CAP`:
        // the previous occupant of this slot was fully read before reuse.
        if slot.sequence.load(Ordering::Acquire) != pos {
            return Some(value); // full
        }
        // SAFETY: sequence == pos means the slot is empty and exclusively
        // claimable by the (single) producer.
        unsafe {
            *slot.value.get() = Some(value);
        }
        // Release publishes the payload write to the consumer's Acquire
        // load of the sequence.
        slot.sequence.store(pos.wrapping_add(1), Ordering::Release);
        self.head.0.store(pos.wrapping_add(1), Ordering::Relaxed);
        None
    }

    /// Consumer side: pop the oldest value, or [`None`] when empty.
    /// Lock-free, never blocks, never allocates, never panics.
    #[must_use]
    pub fn try_pop(&self) -> Option<T> {
        let pos = self.tail.0.load(Ordering::Relaxed);
        #[allow(clippy::indexing_slicing)] // pos & mask < CAP by construction
        let slot = &self.slots[pos & self.mask];
        // Acquire pairs with the producer's Release store of `pos + 1`:
        // the payload write is visible before this read.
        if slot.sequence.load(Ordering::Acquire) != pos + 1 {
            return None; // empty
        }
        // SAFETY: sequence == pos + 1 means a value was published (release)
        // and this (single) consumer owns the take.
        let value = unsafe { (*slot.value.get()).take() };
        // Release marks the slot reusable one lap later (pos + CAP).
        slot.sequence
            .store(pos.wrapping_add(CAP), Ordering::Release);
        self.tail.0.store(pos.wrapping_add(1), Ordering::Relaxed);
        value
    }

    /// Approximate occupancy. `Relaxed` loads, so the pair may lag
    /// concurrent progress; a hint, never a correctness input.
    #[must_use]
    pub fn len(&self) -> usize {
        self.head
            .0
            .load(Ordering::Relaxed)
            .wrapping_sub(self.tail.0.load(Ordering::Relaxed))
    }

    /// True when the ring appears empty (see [`len`](Self::len)).
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl<T, const CAP: usize> Default for SpscRing<T, CAP> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T, const CAP: usize> fmt::Debug for SpscRing<T, CAP> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Contents are never printed: reading slots here would race the
        // producer/consumer roles and need unsafe.
        f.debug_struct("SpscRing")
            .field("cap", &CAP)
            .field("len", &self.len())
            .finish()
    }
}

/// Pair a ring with its two ends for handing to separate threads. The
/// ring itself lives in an `Arc`; the handles are the only way the two
/// threads reach it, which documents the SPSC contract at the type level.
#[must_use]
pub fn channel<T, const CAP: usize>() -> (SpscSender<T, CAP>, SpscReceiver<T, CAP>) {
    let ring = Arc::new(SpscRing::new());
    (
        SpscSender {
            ring: Arc::clone(&ring),
        },
        SpscReceiver { ring },
    )
}

/// Producer handle: the only way to `try_push` into a [`channel`] ring.
pub struct SpscSender<T, const CAP: usize> {
    ring: Arc<SpscRing<T, CAP>>,
}

impl<T, const CAP: usize> SpscSender<T, CAP> {
    /// Enqueues without blocking; `Err(value)` when full.
    ///
    /// # Errors
    /// Returns the value back when the ring is full (lock-free bound).
    #[inline]
    pub fn send(&self, value: T) -> Result<(), T> {
        match self.ring.try_push(value) {
            None => Ok(()),
            Some(back) => Err(back),
        }
    }
}

/// Consumer handle: the only way to `try_pop` from a [`channel`] ring.
pub struct SpscReceiver<T, const CAP: usize> {
    ring: Arc<SpscRing<T, CAP>>,
}

impl<T, const CAP: usize> SpscReceiver<T, CAP> {
    /// Dequeues without blocking; [`None`] when empty.
    #[inline]
    #[must_use]
    pub fn recv(&self) -> Option<T> {
        self.ring.try_pop()
    }
}