Skip to main content

qualia_audio/midi/sequencer/
event_ring.rs

1//! A bounded, wait-free single-producer / single-consumer (SPSC) ring buffer
2//! for scheduled [`TimedEvent`]s.
3//!
4//! One thread (e.g. the sequencer / loader) pushes events; one thread (the
5//! audio thread) pops them. Producer and consumer touch disjoint atomics — the
6//! producer owns `tail`, the consumer owns `head` — so neither ever blocks or
7//! allocates. One slot of the `N`-element buffer is kept empty to distinguish
8//! "full" from "empty", giving a usable capacity of `N - 1`.
9//!
10//! The events are all-integer `Copy` PODs, so the plain data writes carry no
11//! interior pointers; the `Acquire`/`Release` ordering on the indices is what
12//! publishes a written slot to the consumer. This mirrors the `rtrb`-style
13//! discipline the Qualia hot path uses without pulling in a dependency.
14
15use core::cell::UnsafeCell;
16use core::sync::atomic::{AtomicUsize, Ordering};
17
18use super::track::TimedEvent;
19
20/// A fixed-capacity SPSC ring of `N` slots (usable capacity `N - 1`).
21pub struct EventRing<const N: usize> {
22    buf: [UnsafeCell<TimedEvent>; N],
23    /// Next slot the consumer will read.
24    head: AtomicUsize,
25    /// Next slot the producer will write.
26    tail: AtomicUsize,
27}
28
29// SAFETY: access is disciplined SPSC — the producer only writes the slot at
30// `tail` (which the consumer will not read until `tail` is published), and the
31// consumer only reads the slot at `head`. `TimedEvent` is `Copy` POD, so there
32// are no interior pointers or drop concerns.
33unsafe impl<const N: usize> Sync for EventRing<N> {}
34
35impl<const N: usize> Default for EventRing<N> {
36    fn default() -> Self {
37        Self::new()
38    }
39}
40
41impl<const N: usize> EventRing<N> {
42    /// Create an empty ring. `N` must be at least 2 (one slot is a sentinel).
43    pub fn new() -> Self {
44        assert!(N >= 2, "EventRing needs at least 2 slots");
45        Self {
46            buf: core::array::from_fn(|_| UnsafeCell::new(TimedEvent::ZERO)),
47            head: AtomicUsize::new(0),
48            tail: AtomicUsize::new(0),
49        }
50    }
51
52    /// Usable capacity (one slot is reserved as the full/empty sentinel).
53    #[inline]
54    pub const fn capacity(&self) -> usize {
55        N - 1
56    }
57
58    /// Producer side: enqueue an event. Returns the event back as `Err` if the
59    /// ring is full. Wait-free and allocation-free.
60    #[inline]
61    pub fn push(&self, event: TimedEvent) -> Result<(), TimedEvent> {
62        let tail = self.tail.load(Ordering::Relaxed);
63        let next = if tail + 1 == N { 0 } else { tail + 1 };
64        if next == self.head.load(Ordering::Acquire) {
65            return Err(event); // full
66        }
67        // SAFETY: SPSC — this slot is not being read by the consumer until we
68        // publish `tail` below.
69        unsafe {
70            *self.buf[tail].get() = event;
71        }
72        self.tail.store(next, Ordering::Release);
73        Ok(())
74    }
75
76    /// Consumer side: dequeue the oldest event, or `None` if empty. Wait-free.
77    #[inline]
78    pub fn pop(&self) -> Option<TimedEvent> {
79        let head = self.head.load(Ordering::Relaxed);
80        if head == self.tail.load(Ordering::Acquire) {
81            return None; // empty
82        }
83        // SAFETY: SPSC — the producer has published this slot and will not
84        // overwrite it until `head` advances past it below.
85        let event = unsafe { *self.buf[head].get() };
86        let next = if head + 1 == N { 0 } else { head + 1 };
87        self.head.store(next, Ordering::Release);
88        Some(event)
89    }
90
91    /// Whether the ring currently holds no events (consumer-side view).
92    #[inline]
93    pub fn is_empty(&self) -> bool {
94        self.head.load(Ordering::Relaxed) == self.tail.load(Ordering::Acquire)
95    }
96
97    /// Number of events currently queued.
98    #[inline]
99    pub fn len(&self) -> usize {
100        let tail = self.tail.load(Ordering::Acquire);
101        let head = self.head.load(Ordering::Acquire);
102        if tail >= head {
103            tail - head
104        } else {
105            N - head + tail
106        }
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    #[test]
115    fn fifo_order() {
116        let ring: EventRing<8> = EventRing::new();
117        for i in 0..5u64 {
118            ring.push(TimedEvent::new(i, 0x90, i as u8, 64)).unwrap();
119        }
120        for i in 0..5u64 {
121            assert_eq!(ring.pop().unwrap().tick, i);
122        }
123        assert!(ring.pop().is_none());
124    }
125
126    #[test]
127    fn reports_full_at_capacity() {
128        let ring: EventRing<4> = EventRing::new(); // capacity 3
129        assert_eq!(ring.capacity(), 3);
130        ring.push(TimedEvent::ZERO).unwrap();
131        ring.push(TimedEvent::ZERO).unwrap();
132        ring.push(TimedEvent::ZERO).unwrap();
133        assert!(ring.push(TimedEvent::new(99, 0, 0, 0)).is_err());
134        assert_eq!(ring.len(), 3);
135    }
136
137    #[test]
138    fn wraps_around() {
139        let ring: EventRing<4> = EventRing::new();
140        for round in 0..10u64 {
141            ring.push(TimedEvent::new(round, 0x90, 1, 1)).unwrap();
142            assert_eq!(ring.pop().unwrap().tick, round);
143            assert!(ring.is_empty());
144        }
145    }
146}