ph-eventing 0.3.0

Deterministic zero-allocation SPSC primitives for no-std embedded targets — ring buffers, a latest-value snapshot channel, condition flags, saturating counters, and complete sample blocks: bounded behaviour, measured cost, Loom-verified orderings
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
//! Fixed-size, stack-allocated ring buffer — no heap, no alloc, no atomics.
//!
//! [`RingBuf`] is a single-owner (`&mut self`) ring that overwrites the
//! oldest element when full. It requires only `T: Copy` and is ideal for
//! sample windows, local event logs, and anywhere a simple circular buffer
//! is needed without cross-thread sharing.
//!
//! Slots are `MaybeUninit<T>` and only live entries are ever read, which is
//! what lets the `Default` bound go. The cost is that this type is no longer
//! free of `unsafe`: see the safety note on [`RingBuf`].
//!
//! For a lock-free SPSC ring with sequence tracking, see [`crate::SeqRing`].
//! For a lock-free SPSC ring with backpressure, see [`crate::EventBuf`].
//!
//! # Example
//! ```
//! use ph_eventing::RingBuf;
//!
//! let mut r = RingBuf::<u32, 4>::new();
//! r.push(10);
//! r.push(20);
//! assert_eq!(r.latest(), Some(20));
//! assert_eq!(r.get(0), Some(10)); // oldest
//! ```

use core::mem::MaybeUninit;

/// A ring buffer of `N` elements stored entirely on the stack.
///
/// Once full, new pushes overwrite the oldest entry. Iteration with
/// [`iter()`](RingBuf::iter) yields elements from oldest to newest.
///
/// # Safety note
/// Slots are stored as `MaybeUninit<T>` so that `T: Default` is not required.
/// Exactly one invariant makes every read sound: **the `len` entries ending at
/// `head` have all been written by [`push`](RingBuf::push)**. Every read goes
/// through the private `index` helper, which addresses only that range, and
/// every public accessor checks `len` before calling it. A change that lets
/// `len` outrun the number of writes is undefined behaviour, not a logic bug.
pub struct RingBuf<T: Copy, const N: usize> {
    buf: [MaybeUninit<T>; N],
    /// Write cursor — always points to the *next* slot to write.
    head: usize,
    /// Number of elements currently stored (≤ N).
    len: usize,
}

impl<T: Copy, const N: usize> RingBuf<T, N> {
    /// Create a new, empty ring buffer.
    ///
    /// This is a `const fn`, so the buffer can be built in a `const` or
    /// `static` initialiser. Note that `push` and `clear` take
    /// `&mut self`, so a bare `static RingBuf` is read-only and of little use,
    /// and `static mut` is a hard error to reference under edition 2024. The
    /// pattern this actually enables is const-initialising the buffer *inside*
    /// an interior-mutability wrapper, which is how a single-owner buffer is
    /// reached from an interrupt context:
    ///
    /// ```text
    /// // with critical-section, cortex-m, or similar:
    /// static LOG: Mutex<RefCell<RingBuf<u32, 64>>> =
    ///     Mutex::new(RefCell::new(RingBuf::new()));
    /// ```
    ///
    /// Without a const `new` that initialiser is impossible and you need a
    /// `StaticCell` or a `OnceCell` and a runtime init step.
    ///
    /// # Capacity `0` is a build failure
    /// The `N > 0` check is a *const* assertion, so a zero-capacity ring cannot
    /// be constructed at all -- there is no runtime panic left to catch, and
    /// therefore no way to write the negative case as a `#[test]`
    /// (`zero_capacity_panics` was deleted for exactly this reason). This
    /// `compile_fail` doctest is that coverage, and pinning the error code
    /// keeps it honest: a bare `compile_fail` would also pass on a typo.
    ///
    /// ```compile_fail,E0080
    /// let _ = ph_eventing::RingBuf::<u32, 0>::new();
    /// ```
    ///
    /// # Panics
    /// Does not panic.
    pub const fn new() -> Self {
        const {
            assert!(N > 0, "RingBuf capacity N must be > 0");
        }
        Self {
            buf: [const { MaybeUninit::uninit() }; N],
            head: 0,
            len: 0,
        }
    }

    /// Append a value, overwriting the oldest entry once the ring is full.
    ///
    /// This never fails and never blocks; if losing the oldest entry is not
    /// acceptable, use [`crate::EventBuf`], whose `push` reports when full.
    pub fn push(&mut self, val: T) {
        self.buf[self.head] = MaybeUninit::new(val);
        self.head = (self.head + 1) % N;
        if self.len < N {
            self.len += 1;
        }
    }

    /// Number of elements currently stored, always in `0..=N`.
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns `true` if the ring holds no elements.
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns `true` if the ring is at capacity, so the next
    /// [`push`](Self::push) will overwrite the oldest entry.
    pub fn is_full(&self) -> bool {
        self.len == N
    }

    /// Number of elements the ring can hold.
    #[inline]
    pub const fn capacity(&self) -> usize {
        N
    }

    /// Drop every element, resetting the ring to empty.
    ///
    /// The backing array is left as-is; only the cursors are reset, so this is
    /// O(1) and does not touch the stored values.
    pub fn clear(&mut self) {
        self.head = 0;
        self.len = 0;
    }

    /// Index of the `i`-th live element, 0 = oldest.
    ///
    /// Callers must ensure `i < self.len`; the result is only a valid slot
    /// under that precondition.
    ///
    /// Steps back from `head` rather than computing `(head + N - len + i) % N`.
    /// That form is easier to read but forms an intermediate up to `3N`, which
    /// overflows for a large `N` -- and a large `N` is reachable, because a
    /// zero-sized `T` makes `RingBuf<(), { usize::MAX }>` constructible. An
    /// accessor that panics in an overflow-checking build would break the
    /// no-panic guarantee. Here nothing exceeds `N`.
    #[inline(always)]
    const fn index(&self, i: usize) -> usize {
        let back = self.len - i; // 1..=len, so no underflow given i < len
        if self.head >= back {
            self.head - back
        } else {
            N - (back - self.head)
        }
    }

    /// Read the `i`-th element (0 = oldest).
    pub fn get(&self, i: usize) -> Option<T> {
        if i >= self.len {
            return None;
        }
        let idx = self.index(i);
        // SAFETY: `i < len`, so `index` addresses one of the `len` slots
        // written by `push`.
        Some(unsafe { self.buf[idx].assume_init() })
    }

    /// Most recently pushed element.
    pub fn latest(&self) -> Option<T> {
        if self.len == 0 {
            return None;
        }
        // Routed through `index` like every other read. The open-coded
        // `head - 1` it replaces was correct, but it was a second, independent
        // slot calculation -- so a future change to the cursor representation
        // could fix `get` and silently invalidate this one. One indexing path
        // means one unsafe proof.
        let idx = self.index(self.len - 1);
        // SAFETY: `len > 0`, so `index(len - 1)` is the newest live slot,
        // written by `push`.
        Some(unsafe { self.buf[idx].assume_init() })
    }

    /// Iterate over elements oldest→newest.
    pub fn iter(&self) -> RingIter<'_, T, N> {
        RingIter { ring: self, pos: 0 }
    }
}

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

impl<T: Copy, const N: usize> core::fmt::Debug for RingBuf<T, N> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("RingBuf")
            .field("len", &self.len)
            .field("capacity", &N)
            .finish()
    }
}

/// Iterator over [`RingBuf`] elements from oldest to newest.
pub struct RingIter<'a, T: Copy, const N: usize> {
    ring: &'a RingBuf<T, N>,
    pos: usize,
}

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

    fn next(&mut self) -> Option<T> {
        let val = self.ring.get(self.pos)?;
        self.pos += 1;
        Some(val)
    }

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

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

impl<T: Copy, const N: usize> core::fmt::Debug for RingIter<'_, T, N> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.debug_struct("RingIter")
            .field("remaining", &(self.ring.len().saturating_sub(self.pos)))
            .finish()
    }
}

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

    fn into_iter(self) -> RingIter<'a, T, N> {
        self.iter()
    }
}

impl<T: Copy, const N: usize> crate::traits::Sink<T> for RingBuf<T, N> {
    type Error = core::convert::Infallible;

    #[inline]
    fn try_push(&mut self, val: T) -> Result<(), core::convert::Infallible> {
        self.push(val);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Deliberately does not derive `Default`. If the bound ever comes back,
    /// this stops compiling -- which is the point: the whole value of storing
    /// slots as `MaybeUninit` is that `T` no longer has to have a meaningless
    /// "zero" value invented for it.
    #[derive(Copy, Clone, Debug, PartialEq, Eq)]
    struct NoDefault(u32);

    #[test]
    fn new_ring_is_empty() {
        let r = RingBuf::<u32, 4>::new();
        assert!(r.is_empty());
        assert!(!r.is_full());
        assert_eq!(r.len(), 0);
        assert_eq!(r.latest(), None);
        assert_eq!(r.get(0), None);
    }

    #[test]
    fn push_and_get() {
        let mut r = RingBuf::<u32, 4>::new();
        r.push(10);
        r.push(20);
        r.push(30);
        assert_eq!(r.len(), 3);
        assert_eq!(r.get(0), Some(10));
        assert_eq!(r.get(1), Some(20));
        assert_eq!(r.get(2), Some(30));
        assert_eq!(r.get(3), None);
        assert_eq!(r.latest(), Some(30));
    }

    #[test]
    fn overwrite_oldest_when_full() {
        let mut r = RingBuf::<u32, 3>::new();
        r.push(1);
        r.push(2);
        r.push(3);
        assert!(r.is_full());

        r.push(4); // overwrites 1
        assert_eq!(r.len(), 3);
        assert_eq!(r.get(0), Some(2));
        assert_eq!(r.get(1), Some(3));
        assert_eq!(r.get(2), Some(4));
        assert_eq!(r.latest(), Some(4));
    }

    #[test]
    fn clear_resets_state() {
        let mut r = RingBuf::<u32, 4>::new();
        r.push(1);
        r.push(2);
        r.clear();
        assert!(r.is_empty());
        assert_eq!(r.len(), 0);
        assert_eq!(r.latest(), None);
    }

    #[test]
    fn iter_oldest_to_newest() {
        let mut r = RingBuf::<u32, 4>::new();
        for i in 1..=6 {
            r.push(i);
        }
        // capacity 4, pushed 6 → oldest is 3
        let v: std::vec::Vec<u32> = r.iter().collect();
        assert_eq!(v, [3, 4, 5, 6]);
    }

    #[test]
    fn iter_exact_size() {
        let mut r = RingBuf::<u32, 4>::new();
        r.push(1);
        r.push(2);
        let it = r.iter();
        assert_eq!(it.len(), 2);
    }

    #[test]
    fn default_is_new() {
        let r: RingBuf<u8, 8> = RingBuf::default();
        assert!(r.is_empty());
    }

    // `zero_capacity_panics` used to live here and could not survive the const
    // assertion: `RingBuf::<u32, 0>::new()` no longer builds, so there is no
    // runtime panic left to catch and no way to write the negative case as a
    // `#[test]`. The rejection is now enforced by the compiler instead, which
    // is stronger -- but it means nothing in this suite covers it, so the
    // const assertion itself is the only thing keeping N > 0 true.

    #[test]
    fn const_new_works_in_const_context() {
        // The const initialiser is the feature. A `static RingBuf` is itself
        // near-useless because every mutator needs `&mut self` -- the real
        // shape is this one nested inside an interior-mutability wrapper, and
        // that is exactly what a non-const `new` makes impossible.
        const EMPTY: RingBuf<u32, 4> = RingBuf::new();
        static LOG: RingBuf<u32, 8> = RingBuf::new();

        assert!(EMPTY.is_empty());
        assert_eq!(EMPTY.capacity(), 4);
        assert!(LOG.is_empty());
        assert_eq!(LOG.capacity(), 8);

        // Const-constructed and runtime-constructed rings behave identically.
        let mut r = EMPTY;
        r.push(1);
        assert_eq!(r.get(0), Some(1));
    }

    /// A zero-sized `T` makes an enormous `N` genuinely constructible, since
    /// the backing array is zero-sized too. The earlier `(head + N - len + i)`
    /// index formed an intermediate up to `3N` and panicked here in an
    /// overflow-checking build -- which unit tests are. Accessors must stay
    /// panic-free.
    #[test]
    fn huge_capacity_does_not_overflow_the_index() {
        let mut r = RingBuf::<(), { usize::MAX }>::new();
        r.push(());
        assert_eq!(r.len(), 1);
        assert_eq!(r.get(0), Some(()));
        assert_eq!(r.latest(), Some(()));
        r.push(());
        assert_eq!(r.get(1), Some(()));
        assert_eq!(r.latest(), Some(()));
    }

    #[test]
    fn works_without_default_bound() {
        let mut r = RingBuf::<NoDefault, 2>::new();
        r.push(NoDefault(1));
        r.push(NoDefault(2));
        assert_eq!(r.get(0), Some(NoDefault(1)));
        assert_eq!(r.latest(), Some(NoDefault(2)));
        r.push(NoDefault(3)); // overwrites
        assert_eq!(r.get(0), Some(NoDefault(2)));
        assert_eq!(r.latest(), Some(NoDefault(3)));
    }

    #[test]
    fn capacity_returns_n() {
        let r = RingBuf::<u32, 8>::new();
        assert_eq!(r.capacity(), 8);
    }

    #[test]
    fn into_iter_for_ref() {
        let mut r = RingBuf::<u32, 4>::new();
        r.push(1);
        r.push(2);
        r.push(3);
        let v: std::vec::Vec<u32> = (&r).into_iter().collect();
        assert_eq!(v, [1, 2, 3]);
    }
}