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: every domain crate may depend on it (layering L1, no
7//! upward edges).
8//!
9//! Hot path contract: no panics, no syscalls, and no allocation after
10//! construction — [`SampleRing`] never allocates at all, [`SpscRing`]
11//! allocates its slot buffer exactly once in [`SpscRing::new`]. The naive
12//! reference lives in [`oracle`] and is kept forever for differential
13//! testing (ds-kit AGENTS.md).
14//!
15//! [`SpscRing`] is the estate's **sanctioned unsafe exception**: raw slot
16//! access into a `MaybeUninit` buffer behind `UnsafeCell`, with every block
17//! annotated with the acquire/release invariant it relies on and the whole
18//! protocol model-checked under `loom` (`tests/loom_spsc.rs`). [`SampleRing`]
19//! contains no unsafe code.
20
21#![no_std]
22extern crate alloc;
23
24// loom replaces the core atomics with modeled ones when the workspace runs
25// `RUSTFLAGS="--cfg loom" cargo test --test loom_spsc` (roadmap Part 3.2).
26#[cfg(not(loom))]
27use core::sync::atomic::{AtomicU64, Ordering};
28#[cfg(loom)]
29use loom::sync::atomic::{AtomicU64, Ordering};
30
31use alloc::vec::Vec;
32use core::cell::UnsafeCell;
33use core::fmt;
34use core::mem::MaybeUninit;
35
36/// The forever-oracle for differential testing: naive `Vec` + shift-on-pop
37/// spec forms, not optimized. Never deleted, never optimized.
38pub mod oracle;
39
40/// Fixed-capacity sample/latency ring, stack-allocated, oldest-first.
41///
42/// Capacity `N` is a const generic: the whole ring lives inline in the
43/// owner (`[Option<T>; N]` plus two indices), so construction allocates
44/// nothing and `push` allocates nothing — eviction returns the oldest
45/// value by move. FIFO order is preserved: `iter` walks oldest-first and
46/// `push` returns the evicted oldest when full.
47///
48/// With `N == 0` nothing can be stored; [`SampleRing::push`] hands the
49/// value straight back (`Some(value)`), i.e. the value is "evicted" the
50/// moment it arrives. There is deliberately no indexing API.
51///
52/// ```
53/// use ds_ring::SampleRing;
54///
55/// let mut ring = SampleRing::<u64, 2>::new();
56/// assert_eq!(ring.push(1), None);
57/// assert_eq!(ring.push(2), None);
58/// assert_eq!(ring.push(3), Some(1)); // 1 is the evicted oldest
59/// assert_eq!(ring.iter().copied().collect::<Vec<_>>(), vec![2, 3]);
60/// assert_eq!(ring.last(), Some(&3));
61/// ```
62#[derive(Clone)]
63pub struct SampleRing<T, const N: usize> {
64 /// Index of the oldest live value (`0..N` once any value was stored;
65 /// never advanced when empty, so `slots.get` below never sees `% 0`).
66 head: usize,
67 /// Number of live values (`0..=N`).
68 len: usize,
69 /// Ring slots; occupied iff within the logical window.
70 slots: [Option<T>; N],
71}
72
73impl<T, const N: usize> SampleRing<T, N> {
74 /// New empty ring; nothing is allocated (the slots are inline).
75 #[must_use]
76 pub fn new() -> Self {
77 Self {
78 head: 0,
79 len: 0,
80 slots: core::array::from_fn(|_| None),
81 }
82 }
83
84 /// Push one value. Returns `None` when the value was accepted without
85 /// eviction, `Some(old)` when the ring was full and `old` (the oldest
86 /// value) was evicted to make room. With `N == 0` the pushed value is
87 /// returned immediately (nothing can be stored). Never allocates,
88 /// never panics.
89 pub fn push(&mut self, value: T) -> Option<T> {
90 if N == 0 {
91 return Some(value);
92 }
93 if self.len == N {
94 // Full: the write slot coincides with `head`, the oldest live
95 // value, so eviction and insertion are one `replace`. `head < N`
96 // is an invariant, so the slot always exists; were it empty
97 // (impossible while `len == N`), the value is still stored and
98 // `None` honestly reports "no eviction".
99 let evicted = match self.slots.get_mut(self.head) {
100 Some(slot) => slot.replace(value),
101 // Unreachable (`head < N` is an invariant): nothing was
102 // stored, so bounce the value back instead of panicking
103 // or leaking it.
104 None => return Some(value),
105 };
106 self.head = (self.head + 1) % N;
107 return evicted;
108 }
109 let slot = (self.head + self.len) % N;
110 match self.slots.get_mut(slot) {
111 Some(cell) => {
112 *cell = Some(value);
113 self.len += 1;
114 None
115 }
116 // Unreachable (`slot < N` by construction): bounce the value
117 // back rather than panic or leak it.
118 None => Some(value),
119 }
120 }
121
122 /// Oldest-first iterator over the live values.
123 #[must_use]
124 pub fn iter(&self) -> Iter<'_, T, N> {
125 Iter { ring: self, pos: 0 }
126 }
127
128 /// Number of live values (`0..=N`).
129 #[must_use]
130 pub const fn len(&self) -> usize {
131 self.len
132 }
133
134 /// True when the ring holds no values.
135 #[must_use]
136 pub const fn is_empty(&self) -> bool {
137 self.len == 0
138 }
139
140 /// Newest value, or `None` when empty.
141 #[must_use]
142 pub fn last(&self) -> Option<&T> {
143 if self.len == 0 {
144 return None;
145 }
146 let slot = (self.head + self.len - 1) % N;
147 self.slots.get(slot).and_then(Option::as_ref)
148 }
149}
150
151impl<T, const N: usize> Default for SampleRing<T, N> {
152 fn default() -> Self {
153 Self::new()
154 }
155}
156
157impl<T: fmt::Debug, const N: usize> fmt::Debug for SampleRing<T, N> {
158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159 f.debug_list().entries(self.iter()).finish()
160 }
161}
162
163impl<'a, T, const N: usize> IntoIterator for &'a SampleRing<T, N> {
164 type Item = &'a T;
165 type IntoIter = Iter<'a, T, N>;
166
167 fn into_iter(self) -> Self::IntoIter {
168 self.iter()
169 }
170}
171
172/// Oldest-first iterator over a [`SampleRing`]; exact-size.
173#[derive(Clone)]
174pub struct Iter<'a, T, const N: usize> {
175 /// Borrowed ring.
176 ring: &'a SampleRing<T, N>,
177 /// Steps taken from the oldest live value.
178 pos: usize,
179}
180
181impl<'a, T, const N: usize> Iterator for Iter<'a, T, N> {
182 type Item = &'a T;
183
184 fn next(&mut self) -> Option<Self::Item> {
185 if self.pos >= self.ring.len {
186 // Also covers N == 0 (len == 0), so the `% N` below never sees 0.
187 return None;
188 }
189 let slot = (self.ring.head + self.pos) % N;
190 self.pos += 1;
191 // `slot < N` by construction; a live slot always holds `Some`.
192 self.ring.slots.get(slot).and_then(Option::as_ref)
193 }
194
195 fn size_hint(&self) -> (usize, Option<usize>) {
196 let remaining = self.ring.len - self.pos;
197 (remaining, Some(remaining))
198 }
199}
200
201impl<T, const N: usize> ExactSizeIterator for Iter<'_, T, N> {}
202
203/// Lock-free single-producer/single-consumer ring with fixed capacity.
204///
205/// The slot buffer is allocated exactly once in [`SpscRing::new`]; `push`,
206/// `pop`, and `len` never allocate or panic. Indices are monotonic `u64`s —
207/// the modern technique that needs no power-of-two capacity: slot =
208/// `index % capacity`, empty when `head == tail`, full when
209/// `tail - head == capacity`. `u64` indices cannot wrap within the lifetime
210/// of any process (2^64 single ops at 1 GHz is ~584 years), and
211/// `wrapping_*` keeps the arithmetic panic-free regardless.
212///
213/// # The sanctioned unsafe exception
214///
215/// This is the estate's approved use of raw slot access: a `MaybeUninit`
216/// buffer behind `UnsafeCell`, synchronized by two atomics. The protocol
217/// (model-checked under `loom` in `tests/loom_spsc.rs`):
218///
219/// - **Producer** owns `tail`: reads it `Relaxed` (own index), writes the
220/// slot, then stores `tail + 1` with `Release`.
221/// - **Consumer** owns `head`: reads it `Relaxed` (own index), loads `tail`
222/// with `Acquire` — pairing with the producer's `Release` store so the
223/// slot write is visible before the read — then stores `head + 1` with
224/// `Release`.
225/// - **Slot reuse**: before overwriting a slot the producer loads `head`
226/// with `Acquire`, pairing with the consumer's `Release` store of `head`,
227/// so the consumer's earlier reads of that slot are complete.
228///
229/// Each slot is written at exactly one monotonic index and read at exactly
230/// one monotonic index, so the acquire/release pairs above are the only
231/// cross-thread ordering the protocol needs.
232///
233/// # Single-producer / single-consumer contract
234///
235/// `push` is the producer side, `pop` the consumer side: at most one thread
236/// may push and at most one thread may pop concurrently. Concurrent `push`es
237/// or concurrent `pop`s are a contract violation, not dynamically enforced —
238/// this is the documented cost of the sanctioned exception. Under contention
239/// either side may transiently observe a stale peer index and report
240/// full/empty one step late; the caller retries.
241pub struct SpscRing<T> {
242 /// Slot buffer of exactly `capacity` `MaybeUninit` entries. All access
243 /// goes through the acquire/release protocol documented above.
244 buf: UnsafeCell<Vec<MaybeUninit<T>>>,
245 /// Fixed slot count (usize widened; `0` is refused in `new`).
246 capacity: u64,
247 /// Consumer-owned index: next slot to pop (monotonic).
248 head: AtomicU64,
249 /// Producer-owned index: next slot to push (monotonic).
250 tail: AtomicU64,
251}
252
253// SAFETY: `push` runs on the producer only, `pop` on the consumer only
254// (struct doc). `T: Send` makes values safe to hand off between those two
255// threads; buffer access is mediated by the acquire/release protocol
256// documented on [`SpscRing`] and model-checked under loom.
257#[allow(unsafe_code)] // sanctioned unsafe exception (crate docs, ds-kit AGENTS.md)
258unsafe impl<T: Send> Send for SpscRing<T> {}
259
260// SAFETY: shared access is split by role — the producer writes only `tail`
261// and empty slots, the consumer reads only `head` and full slots, and the
262// acquire/release pairs on the two indices order every buffer access.
263#[allow(unsafe_code)] // sanctioned unsafe exception (crate docs, ds-kit AGENTS.md)
264unsafe impl<T: Send> Sync for SpscRing<T> {}
265
266// SAFETY-free raw slot access lives inside this impl: `unsafe_code` is the
267// estate-sanctioned exception (crate docs, ds-kit AGENTS.md) — every unsafe
268// block below carries its own SAFETY comment citing the acquire/release
269// protocol documented on [`SpscRing`], model-checked under loom.
270#[allow(unsafe_code)]
271impl<T> SpscRing<T> {
272 /// New ring with `capacity` slots; `None` for capacity `0` (a ring with
273 /// no slots can never hand anything off, so it is refused at
274 /// construction rather than made a permanent no-op). The only
275 /// allocation in the ring's lifetime happens here.
276 #[must_use]
277 pub fn new(capacity: usize) -> Option<Self> {
278 if capacity == 0 {
279 return None;
280 }
281 let buf: Vec<MaybeUninit<T>> = (0..capacity).map(|_| MaybeUninit::uninit()).collect();
282 Some(Self {
283 capacity: capacity as u64, // usize -> u64: widening, lossless
284 buf: UnsafeCell::new(buf),
285 head: AtomicU64::new(0),
286 tail: AtomicU64::new(0),
287 })
288 }
289
290 /// Producer side: push one value. `Err(value)` when the ring is full
291 /// (transiently possible under contention — retry). Never allocates,
292 /// never panics.
293 ///
294 /// # Errors
295 ///
296 /// Returns `Err(value)` unchanged when the ring is full; the value is
297 /// not stored and the caller may retry or take it back.
298 pub fn push(&self, value: T) -> Result<(), T> {
299 let tail = self.tail.load(Ordering::Relaxed); // producer-owned index
300 // Acquire pairs with the consumer's Release store of `head`: before
301 // reusing a slot, the consumer's reads of it are complete.
302 let head = self.head.load(Ordering::Acquire);
303 if tail.wrapping_sub(head) >= self.capacity {
304 return Err(value);
305 }
306 // SAFETY: `slot = tail % capacity < capacity` and the buffer holds
307 // exactly `capacity` slots. `tail` is producer-owned and this exact
308 // monotonic index has never been written; `tail - head < capacity`
309 // (checked above, head Acquire-loaded) proves the previous occupant
310 // of this slot was already read by the consumer.
311 #[allow(clippy::cast_possible_truncation)] // slot < capacity <= usize::MAX
312 let slot = (tail % self.capacity) as usize;
313 // SAFETY: see above — in-bounds slot, never-written index, consumer
314 // has released the slot.
315 unsafe {
316 let buf = self.buf.get();
317 (*buf).as_mut_ptr().add(slot).write(MaybeUninit::new(value));
318 }
319 // Release publishes the slot write to the consumer's Acquire load
320 // of `tail`.
321 self.tail.store(tail.wrapping_add(1), Ordering::Release);
322 Ok(())
323 }
324
325 /// Consumer side: pop the oldest value, or `None` when empty
326 /// (transiently possible under contention — retry). Never allocates,
327 /// never panics.
328 pub fn pop(&self) -> Option<T> {
329 let head = self.head.load(Ordering::Relaxed); // consumer-owned index
330 // Acquire pairs with the producer's Release store of `tail`: the
331 // slot write is visible before this read.
332 let tail = self.tail.load(Ordering::Acquire);
333 if head == tail {
334 return None;
335 }
336 // SAFETY: `slot = head % capacity < capacity` and the buffer holds
337 // exactly `capacity` slots. `head` is consumer-owned; this exact
338 // monotonic index was written once by the producer, whose Release
339 // store of `tail` is paired with the Acquire load above.
340 #[allow(clippy::cast_possible_truncation)] // slot < capacity <= usize::MAX
341 let slot = (head % self.capacity) as usize;
342 // SAFETY: see above — in-bounds slot of a fully-written value.
343 // `assume_init_read` moves the value out; the slot stays logically
344 // uninitialized until the producer rewrites it (slot-reuse rule).
345 let value = unsafe {
346 let buf = self.buf.get();
347 (*(*buf).as_ptr().add(slot)).assume_init_read()
348 };
349 // Release publishes the read to the producer's Acquire load of
350 // `head` (slot-reuse safety on the producer side).
351 self.head.store(head.wrapping_add(1), Ordering::Release);
352 Some(value)
353 }
354
355 /// Values currently in the ring (atomic snapshot: `head` is loaded
356 /// before `tail`, so the difference cannot underflow; the pair may lag
357 /// concurrent progress but never over-reports).
358 #[must_use]
359 #[allow(clippy::cast_possible_truncation)] // len <= capacity <= usize::MAX
360 pub fn len(&self) -> usize {
361 let head = self.head.load(Ordering::Acquire);
362 let tail = self.tail.load(Ordering::Acquire);
363 tail.wrapping_sub(head) as usize
364 }
365
366 /// True when the ring holds no values (atomic snapshot, see [`len`]).
367 #[must_use]
368 pub fn is_empty(&self) -> bool {
369 self.len() == 0
370 }
371}
372
373impl<T> fmt::Debug for SpscRing<T> {
374 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
375 // Contents are never printed: reading slots here would race the
376 // producer/consumer roles and need unsafe.
377 f.debug_struct("SpscRing")
378 .field("len", &self.len())
379 .finish()
380 }
381}
382
383impl<T> Drop for SpscRing<T> {
384 fn drop(&mut self) {
385 // Remaining values drop in FIFO order; each `pop` advances `head`
386 // so the `MaybeUninit` buffer drops afterwards without double-drop.
387 while self.pop().is_some() {}
388 }
389}