1use crate::render::Tail;
2pub const CHANGE_CAPACITY: usize = 128;
4
5#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9#[non_exhaustive]
10pub struct PluginTiming {
11 pub latency: u32,
13 pub tail: Tail,
15 pub restart_required: bool,
17 pub latency_changed: bool,
20}
21
22impl PluginTiming {
23 #[must_use]
25 pub fn new(latency: u32, tail: Tail) -> PluginTiming {
26 PluginTiming {
27 latency,
28 tail,
29 restart_required: false,
30 latency_changed: false,
31 }
32 }
33}
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37#[non_exhaustive]
38pub struct SlotChange {
39 pub slot: usize,
41 pub timing: PluginTiming,
43}
44
45#[derive(Clone, Debug, Default, PartialEq, Eq)]
48#[non_exhaustive]
49#[must_use]
50pub struct ChangeBatch {
51 pub changes: Vec<SlotChange>,
53 pub resync_required: bool,
55 pub snapshot: Vec<Option<PluginTiming>>,
57}
58
59pub struct ChangeBuffer {
61 pending: Vec<SlotChange>,
62 snapshot: Vec<Option<PluginTiming>>,
63 overflow: bool,
64}
65
66impl Default for ChangeBuffer {
67 fn default() -> Self {
68 Self {
69 pending: Vec::with_capacity(CHANGE_CAPACITY),
70 snapshot: Vec::new(),
71 overflow: false,
72 }
73 }
74}
75
76impl ChangeBuffer {
77 pub fn observe(&mut self, slot: usize, timing: PluginTiming) {
79 if self.snapshot.len() <= slot {
80 self.snapshot.resize(slot + 1, None);
81 }
82 if self.snapshot[slot] == Some(timing) {
83 return;
84 }
85 self.snapshot[slot] = Some(timing);
86 self.pending.retain(|event| event.slot != slot);
87 if self.pending.len() == CHANGE_CAPACITY {
88 self.pending.remove(0);
89 self.overflow = true;
90 }
91 self.pending.push(SlotChange { slot, timing });
92 }
93
94 pub fn clear(&mut self) {
96 self.pending.clear();
97 self.snapshot.clear();
98 self.overflow = false;
99 }
100
101 pub fn take(&mut self) -> ChangeBatch {
103 let changes = self.pending.clone();
105 self.pending.clear();
106 ChangeBatch {
107 changes,
108 resync_required: std::mem::take(&mut self.overflow),
109 snapshot: self.snapshot.clone(),
110 }
111 }
112}
113
114#[cfg(test)]
115mod tests {
116 use super::*;
117
118 #[test]
119 fn change_notifications_coalesce_and_resynchronize_without_a_consumer() {
120 let mut events = ChangeBuffer::default();
121 let timing = |latency| PluginTiming {
122 latency,
123 tail: Tail::Samples(latency),
124 restart_required: false,
125 latency_changed: false,
126 };
127 for slot in 0..CHANGE_CAPACITY + 10 {
128 events.observe(slot, timing(slot as u32));
129 }
130 events.observe(0, timing(999));
131 let batch = events.take();
132 assert!(batch.resync_required);
133 assert_eq!(batch.changes.len(), CHANGE_CAPACITY);
134 assert_eq!(batch.changes.last().unwrap().slot, 0);
135 assert_eq!(batch.snapshot[0], Some(timing(999)));
136 assert_eq!(batch.snapshot.len(), CHANGE_CAPACITY + 10);
137 let empty = events.take();
138 assert!(!empty.resync_required);
139 assert!(empty.changes.is_empty());
140 assert_eq!(empty.snapshot, batch.snapshot);
141 }
142}