qualia_audio/midi/sequencer/
event_ring.rs1use core::cell::UnsafeCell;
16use core::sync::atomic::{AtomicUsize, Ordering};
17
18use super::track::TimedEvent;
19
20pub struct EventRing<const N: usize> {
22 buf: [UnsafeCell<TimedEvent>; N],
23 head: AtomicUsize,
25 tail: AtomicUsize,
27}
28
29unsafe 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 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 #[inline]
54 pub const fn capacity(&self) -> usize {
55 N - 1
56 }
57
58 #[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); }
67 unsafe {
70 *self.buf[tail].get() = event;
71 }
72 self.tail.store(next, Ordering::Release);
73 Ok(())
74 }
75
76 #[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; }
83 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 #[inline]
93 pub fn is_empty(&self) -> bool {
94 self.head.load(Ordering::Relaxed) == self.tail.load(Ordering::Acquire)
95 }
96
97 #[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(); 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}