ds-ring 0.1.0

Fixed-capacity ring buffers: sample/latency ring and SPSC, loom-tested
Documentation
//! 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: every domain crate may depend on it (layering L1, no
//! 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**: raw slot
//! access into a `MaybeUninit` buffer behind `UnsafeCell`, 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 core::sync::atomic::{AtomicU64, Ordering};
#[cfg(loom)]
use loom::sync::atomic::{AtomicU64, Ordering};

use alloc::vec::Vec;
use core::cell::UnsafeCell;
use core::fmt;
use core::mem::MaybeUninit;

/// 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 with fixed capacity.
///
/// The slot buffer is allocated exactly once in [`SpscRing::new`]; `push`,
/// `pop`, and `len` never allocate or panic. Indices are monotonic `u64`s —
/// 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 it `Relaxed` (own index), writes the
///   slot, then stores `tail + 1` with `Release`.
/// - **Consumer** owns `head`: reads it `Relaxed` (own index), loads `tail`
///   with `Acquire` — pairing with the producer's `Release` store so the
///   slot write is visible before the read — then stores `head + 1` with
///   `Release`.
/// - **Slot reuse**: before overwriting a slot the producer loads `head`
///   with `Acquire`, pairing with the consumer's `Release` store of `head`,
///   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 `push`es
/// or concurrent `pop`s 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.
pub struct SpscRing<T> {
    /// Slot buffer of exactly `capacity` `MaybeUninit` entries. All access
    /// goes through the acquire/release protocol documented above.
    buf: UnsafeCell<Vec<MaybeUninit<T>>>,
    /// Fixed slot count (usize widened; `0` is refused in `new`).
    capacity: u64,
    /// Consumer-owned index: next slot to pop (monotonic).
    head: AtomicU64,
    /// Producer-owned index: next slot to push (monotonic).
    tail: AtomicU64,
}

// SAFETY: `push` runs on the producer only, `pop` on the consumer only
// (struct doc). `T: Send` makes values safe to hand off between those two
// threads; buffer 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> Send for SpscRing<T> {}

// SAFETY: shared access is split by role — the producer writes only `tail`
// and empty slots, the consumer reads only `head` and full slots, and the
// acquire/release pairs on the two indices order every buffer access.
#[allow(unsafe_code)] // sanctioned unsafe exception (crate docs, ds-kit AGENTS.md)
unsafe impl<T: Send> Sync for SpscRing<T> {}

// SAFETY-free 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 acquire/release
// protocol documented on [`SpscRing`], model-checked under loom.
#[allow(unsafe_code)]
impl<T> SpscRing<T> {
    /// 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.
    #[must_use]
    pub fn new(capacity: usize) -> Option<Self> {
        if capacity == 0 {
            return None;
        }
        let buf: Vec<MaybeUninit<T>> = (0..capacity).map(|_| MaybeUninit::uninit()).collect();
        Some(Self {
            capacity: capacity as u64, // usize -> u64: widening, lossless
            buf: UnsafeCell::new(buf),
            head: AtomicU64::new(0),
            tail: AtomicU64::new(0),
        })
    }

    /// 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.
    pub fn push(&self, value: T) -> Result<(), T> {
        let tail = self.tail.load(Ordering::Relaxed); // producer-owned index
                                                      // Acquire pairs with the consumer's Release store of `head`: before
                                                      // reusing a slot, the consumer's reads of it are complete.
        let head = self.head.load(Ordering::Acquire);
        if tail.wrapping_sub(head) >= self.capacity {
            return Err(value);
        }
        // SAFETY: `slot = tail % capacity < capacity` and the buffer holds
        // exactly `capacity` slots. `tail` is producer-owned and this exact
        // monotonic index has never been written; `tail - head < capacity`
        // (checked above, head Acquire-loaded) proves the previous occupant
        // of this slot was already read by the consumer.
        #[allow(clippy::cast_possible_truncation)] // slot < capacity <= usize::MAX
        let slot = (tail % self.capacity) as usize;
        // SAFETY: see above — in-bounds slot, never-written index, consumer
        // has released the slot.
        unsafe {
            let buf = self.buf.get();
            (*buf).as_mut_ptr().add(slot).write(MaybeUninit::new(value));
        }
        // Release publishes the slot write to the consumer's Acquire load
        // of `tail`.
        self.tail.store(tail.wrapping_add(1), Ordering::Release);
        Ok(())
    }

    /// Consumer side: pop the oldest value, or `None` when empty
    /// (transiently possible under contention — retry). Never allocates,
    /// never panics.
    pub fn pop(&self) -> Option<T> {
        let head = self.head.load(Ordering::Relaxed); // consumer-owned index
                                                      // Acquire pairs with the producer's Release store of `tail`: the
                                                      // slot write is visible before this read.
        let tail = self.tail.load(Ordering::Acquire);
        if head == tail {
            return None;
        }
        // SAFETY: `slot = head % capacity < capacity` and the buffer holds
        // exactly `capacity` slots. `head` is consumer-owned; this exact
        // monotonic index was written once by the producer, whose Release
        // store of `tail` is paired with the Acquire load above.
        #[allow(clippy::cast_possible_truncation)] // slot < capacity <= usize::MAX
        let slot = (head % self.capacity) as usize;
        // SAFETY: see above — in-bounds slot of a fully-written value.
        // `assume_init_read` moves the value out; the slot stays logically
        // uninitialized until the producer rewrites it (slot-reuse rule).
        let value = unsafe {
            let buf = self.buf.get();
            (*(*buf).as_ptr().add(slot)).assume_init_read()
        };
        // Release publishes the read to the producer's Acquire load of
        // `head` (slot-reuse safety on the producer side).
        self.head.store(head.wrapping_add(1), Ordering::Release);
        Some(value)
    }

    /// Values currently in the ring (atomic snapshot: `head` is loaded
    /// before `tail`, so the difference cannot underflow; the pair may lag
    /// concurrent progress but never over-reports).
    #[must_use]
    #[allow(clippy::cast_possible_truncation)] // len <= capacity <= usize::MAX
    pub fn len(&self) -> usize {
        let head = self.head.load(Ordering::Acquire);
        let tail = self.tail.load(Ordering::Acquire);
        tail.wrapping_sub(head) as usize
    }

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

impl<T> fmt::Debug for SpscRing<T> {
    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("len", &self.len())
            .finish()
    }
}

impl<T> Drop for SpscRing<T> {
    fn drop(&mut self) {
        // Remaining values drop in FIFO order; each `pop` advances `head`
        // so the `MaybeUninit` buffer drops afterwards without double-drop.
        while self.pop().is_some() {}
    }
}