ds-ring 0.2.0

Fixed-capacity ring buffers: sample/latency ring and SPSC, loom-tested
Documentation
//! Differential properties: rings vs the forever-oracle.

#![forbid(unsafe_code)]
// Tests are not hot paths: they bridge value strategies and are allowed to
// panic on failure. The lib target keeps every deny.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]

use ds_ring::oracle::{OracleSampleRing, OracleSpsc};
use ds_ring::{SampleRing, SpscRing};
use proptest::prelude::*;

/// Ordered value sequences of arbitrary u64s (element value is irrelevant
/// to ring semantics; only order and count matter).
fn u64_vec(len: usize) -> impl Strategy<Value = Vec<u64>> {
    proptest::collection::vec(any::<u64>(), len)
}

/// Step `value` through both rings and compare every observable: eviction
/// return, iteration order, `len`, `is_empty`, `last`.
fn compare_step<const N: usize>(
    real: &mut SampleRing<u64, N>,
    oracle: &mut OracleSampleRing<u64, N>,
    value: u64,
    n: usize,
) {
    let evicted_real = real.push(value);
    let evicted_oracle = oracle.push(value);
    assert_eq!(
        evicted_real, evicted_oracle,
        "eviction mismatch on push({value}) at N={n}"
    );
    assert_eq!(
        real.iter().collect::<Vec<_>>(),
        oracle.iter().collect::<Vec<_>>(),
        "iter order mismatch at N={n}"
    );
    assert_eq!(real.len(), oracle.len(), "len mismatch at N={n}");
    assert_eq!(
        real.is_empty(),
        oracle.is_empty(),
        "is_empty mismatch at N={n}"
    );
    assert_eq!(real.last(), oracle.last(), "last mismatch at N={n}");
}

/// Values drained from a ring after `count` pushes; iter length for the
/// boundedness property.
fn push_all<const N: usize>(xs: &[u64]) -> usize {
    let mut ring = SampleRing::<u64, N>::new();
    for x in xs {
        ring.push(*x);
    }
    ring.iter().count()
}

proptest! {
    #![proptest_config(ProptestConfig::with_cases(256))]

    /// SampleRing eviction, iteration, and accessors match the oracle at
    /// N = 3 (odd, non-power-of-two, wraps many times).
    #[test]
    fn sample_ring_n3_matches_oracle(xs in u64_vec(48)) {
        let mut real = SampleRing::<u64, 3>::new();
        let mut oracle = OracleSampleRing::<u64, 3>::new();
        for x in xs {
            compare_step(&mut real, &mut oracle, x, 3);
        }
    }

    /// Same differential at N = 7 (non-power-of-two wraparound).
    #[test]
    fn sample_ring_n7_matches_oracle(xs in u64_vec(64)) {
        let mut real = SampleRing::<u64, 7>::new();
        let mut oracle = OracleSampleRing::<u64, 7>::new();
        for x in xs {
            compare_step(&mut real, &mut oracle, x, 7);
        }
    }

    /// SampleRing::iter never yields more than N, and never less than
    /// min(pushed, N).
    #[test]
    fn sample_ring_iter_bounded(xs in u64_vec(64)) {
        for (n, got) in [
            (1usize, push_all::<1>(&xs)),
            (2, push_all::<2>(&xs)),
            (3, push_all::<3>(&xs)),
            (5, push_all::<5>(&xs)),
            (8, push_all::<8>(&xs)),
        ] {
            prop_assert!(got <= n, "iter yielded {got} > N={n}");
            prop_assert_eq!(got, xs.len().min(n), "iter must yield exactly min(len, N)");
        }
    }

    /// SpscRing sequential try_push/try_pop is exactly the oracle FIFO at
    /// the power-of-two runtime capacities the const ring allows.
    #[test]
    fn spsc_sequential_matches_oracle(xs in u64_vec(48), cap in 1usize..=4usize) {
        let cap_pow2 = 1usize << cap; // 2, 4, 8, 16
        let real = SpscRing::<u64, 16>::new();
        let mut oracle = OracleSpsc::<u64>::new(cap_pow2).expect("cap >= 1");
        for x in xs {
            // Push: acceptance must match, and the refused value must come
            // back untouched (Some carries it).
            let real_push = real.try_push(x);
            let oracle_push = oracle.push(x);
            assert_eq!(
                real_push.is_some(),
                oracle_push.is_err(),
                "push acceptance mismatch at cap={cap_pow2}"
            );
            if let Some(back) = real_push {
                assert_eq!(back, x, "refused value must come back untouched");
            }
            // Pop: presence, value, and FIFO order.
            assert_eq!(real.try_pop(), oracle.pop(), "pop mismatch at cap={cap_pow2}");
            assert_eq!(real.len(), oracle.len(), "len mismatch at cap={cap_pow2}");
        }
        // Final drain agrees element-for-element until both run dry.
        loop {
            let r = real.try_pop();
            let o = oracle.pop();
            assert_eq!(r, o, "drain mismatch at cap={cap_pow2}");
            if r.is_none() {
                break;
            }
        }
    }

    /// SpscRing::len tracks the oracle after every operation.
    #[test]
    fn spsc_len_matches_oracle(xs in u64_vec(32)) {
        let real = SpscRing::<u64, 4>::new();
        let mut oracle = OracleSpsc::<u64>::new(4).expect("cap >= 1");
        for x in xs {
            if oracle.push(x).is_err() {
                // Ring full: pop one on both sides, then the push must fit.
                assert!(real.try_pop().is_some());
                oracle.pop();
                assert!(real.try_push(x).is_none());
                assert!(oracle.push(x).is_ok());
            } else {
                assert!(real.try_push(x).is_none());
            }
            assert_eq!(real.len(), oracle.len(), "len mismatch");
        }
    }
}

/// Wraparound: monotonic cursor arithmetic survives far past one lap
/// (sequence numbers advance by CAP per lap; u64/usize wrapping arithmetic
/// keeps the protocol panic-free).
#[test]
fn spsc_wraparound_past_many_laps() {
    let ring = SpscRing::<usize, 4>::new();
    for i in 0..10_000usize {
        assert_eq!(ring.try_push(i), None, "push {i} fits into a drained ring");
        assert_eq!(ring.try_pop(), Some(i), "FIFO order at {i}");
    }
    assert!(ring.is_empty());
}

/// Zero-capacity `SampleRing` stores nothing and bounces values back.
#[test]
fn zero_capacity_sample_ring_bounces_values() {
    let mut ring = SampleRing::<u64, 0>::new();
    assert!(ring.is_empty());
    assert_eq!(ring.push(1), Some(1));
    assert_eq!(ring.len(), 0);
    assert!(ring.iter().next().is_none());
    assert_eq!(ring.last(), None);
}

/// FIFO eviction order on the smallest real capacity.
#[test]
fn sample_ring_evicts_oldest_fifo_n2() {
    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)); // oldest evicted
    assert_eq!(ring.iter().copied().collect::<Vec<_>>(), vec![2, 3]);
    assert_eq!(ring.last(), Some(&3));
    assert_eq!(ring.len(), 2);
}