Skip to main content

plughost_core/event/
events.rs

1//! Events kept as fixed-size records, with their system exclusive bytes in one area, as the
2//! helper's shared memory and the native formats keep them.
3
4use std::collections::TryReserveError;
5use std::fmt;
6
7use super::{Event, EventData, MAX_BLOCK_EVENTS, MAX_BLOCK_SYSEX_BYTES, Note, NoteExpression};
8use crate::InputError;
9
10/// Events in the order they were pushed: fixed records, with the system exclusive bytes of all of
11/// them in one area, so a system exclusive message costs no allocation of its own. Iterating
12/// gives [`Event`]s that borrow those bytes.
13///
14/// [`Events::for_block`] holds what one processing block takes, at most [`MAX_BLOCK_EVENTS`]
15/// events and [`MAX_BLOCK_SYSEX_BYTES`] system exclusive bytes, with room for both reserved, so
16/// pushing never allocates and fails beyond them. [`Events::new`] grows without that limit, for
17/// the events of a whole render.
18#[derive(Default)]
19pub struct Events {
20    records: Vec<Record>,
21    sysex: Vec<u8>,
22    bounded: bool,
23}
24
25#[derive(Clone, Copy, Debug)]
26struct Record {
27    offset: usize,
28    port: usize,
29    data: RecordData,
30}
31
32/// An event's data, with system exclusive bytes as a range of the area.
33#[derive(Clone, Copy, Debug)]
34enum RecordData {
35    Midi([u8; 3]),
36    SysEx { start: usize, length: usize },
37    NoteOn(Note),
38    NoteOff(Note),
39    Expression(NoteExpression),
40}
41
42impl Events {
43    /// Events of any number, which grow as they are pushed: the input or output of a render.
44    #[must_use]
45    pub fn new() -> Events {
46        Events::default()
47    }
48
49    /// Room for one block's events and system exclusive bytes, reserved now: pushing within it
50    /// never allocates, and beyond it fails.
51    #[must_use]
52    pub fn for_block() -> Events {
53        Events {
54            records: Vec::with_capacity(MAX_BLOCK_EVENTS),
55            sysex: Vec::with_capacity(MAX_BLOCK_SYSEX_BYTES),
56            bounded: true,
57        }
58    }
59
60    /// As [`Events::for_block`], failing instead of aborting when the room cannot be allocated.
61    pub fn try_for_block() -> Result<Events, TryReserveError> {
62        let mut records = Vec::new();
63        records.try_reserve_exact(MAX_BLOCK_EVENTS)?;
64        let mut sysex = Vec::new();
65        sysex.try_reserve_exact(MAX_BLOCK_SYSEX_BYTES)?;
66        Ok(Events {
67            records,
68            sysex,
69            bounded: true,
70        })
71    }
72
73    /// Appends `event`, copying its system exclusive bytes. Events of a block go in offset
74    /// order; processing refuses others with [`InputError::Events`]. Fails with
75    /// [`InputError::EventCapacity`], keeping the events as they are, when the events come from
76    /// [`Events::for_block`] and would go beyond one block's.
77    pub fn push(&mut self, event: Event<'_>) -> Result<(), InputError> {
78        let bytes = match event.data {
79            EventData::SysEx(bytes) => bytes.len(),
80            _ => 0,
81        };
82        if self.bounded
83            && (self.records.len() >= MAX_BLOCK_EVENTS
84                || bytes > MAX_BLOCK_SYSEX_BYTES - self.sysex.len())
85        {
86            return Err(InputError::EventCapacity);
87        }
88        self.append(event);
89        Ok(())
90    }
91
92    /// Appends `event` only when the room already reserved holds it, so that it allocates
93    /// nothing; returns whether it did. Internal to the plughost crates; exempt from semver.
94    #[doc(hidden)]
95    pub fn push_within_capacity(&mut self, event: Event<'_>) -> bool {
96        let bytes = match event.data {
97            EventData::SysEx(bytes) => bytes.len(),
98            _ => 0,
99        };
100        let fits = self.has_room(bytes);
101        if fits {
102            self.append(event);
103        }
104        fits
105    }
106
107    /// Appends a system exclusive event of `length` bytes that `fill` writes, for bytes that
108    /// cannot be borrowed as a slice, such as memory another process shares. As
109    /// [`Events::push_within_capacity`].
110    pub(crate) fn push_sysex_within_capacity(
111        &mut self,
112        offset: usize,
113        port: usize,
114        length: usize,
115        fill: impl FnOnce(&mut [u8]),
116    ) -> bool {
117        let fits = self.has_room(length);
118        if fits {
119            let start = self.sysex.len();
120            self.sysex.resize(start + length, 0);
121            fill(&mut self.sysex[start..]);
122            self.records.push(Record {
123                offset,
124                port,
125                data: RecordData::SysEx { start, length },
126            });
127        }
128        fits
129    }
130
131    /// Whether the reserved room, and a block's budget when bounded, holds one more event
132    /// carrying `bytes` system exclusive bytes.
133    fn has_room(&self, bytes: usize) -> bool {
134        self.records.len() < self.records.capacity()
135            && bytes <= self.sysex.capacity() - self.sysex.len()
136            && (!self.bounded
137                || (self.records.len() < MAX_BLOCK_EVENTS
138                    && bytes <= MAX_BLOCK_SYSEX_BYTES - self.sysex.len()))
139    }
140
141    fn append(&mut self, event: Event<'_>) {
142        let data = match event.data {
143            EventData::Midi(bytes) => RecordData::Midi(bytes),
144            EventData::SysEx(bytes) => {
145                let start = self.sysex.len();
146                self.sysex.extend_from_slice(bytes);
147                RecordData::SysEx {
148                    start,
149                    length: bytes.len(),
150                }
151            }
152            EventData::NoteOn(note) => RecordData::NoteOn(note),
153            EventData::NoteOff(note) => RecordData::NoteOff(note),
154            EventData::Expression(expression) => RecordData::Expression(expression),
155        };
156        self.records.push(Record {
157            offset: event.offset,
158            port: event.port,
159            data,
160        });
161    }
162
163    /// Puts the events in offset order, keeping the order of events at one offset. Events
164    /// already in order are left as they are without allocating.
165    pub fn sort_by_offset(&mut self) {
166        if !self.records.is_sorted_by_key(|record| record.offset) {
167            self.records.sort_by_key(|record| record.offset);
168        }
169    }
170
171    /// Removes every event, keeping the room reserved.
172    pub fn clear(&mut self) {
173        self.records.clear();
174        self.sysex.clear();
175    }
176
177    /// How many events there are.
178    pub fn len(&self) -> usize {
179        self.records.len()
180    }
181
182    /// Whether there are no events.
183    pub fn is_empty(&self) -> bool {
184        self.records.is_empty()
185    }
186
187    /// The system exclusive bytes of all the events.
188    pub fn sysex_bytes(&self) -> usize {
189        self.sysex.len()
190    }
191
192    /// The event at `index`.
193    pub fn get(&self, index: usize) -> Option<Event<'_>> {
194        self.records.get(index).map(|record| self.event(record))
195    }
196
197    /// The events in order.
198    pub fn iter(&self) -> Iter<'_> {
199        Iter {
200            records: self.records.iter(),
201            sysex: &self.sysex,
202        }
203    }
204
205    fn event<'a>(&'a self, record: &Record) -> Event<'a> {
206        event(record, &self.sysex)
207    }
208
209    /// Appends `other`'s events whatever this one holds. Only for events of any number.
210    pub(crate) fn extend_from(&mut self, other: &Events) {
211        for event in other {
212            self.append(event);
213        }
214    }
215
216    /// The number of the events from the first whose offset `before` does not take, as for
217    /// `slice::partition_point`: with events in offset order, those before an offset.
218    pub(crate) fn partition_point(&self, before: impl Fn(usize) -> bool) -> usize {
219        self.records.partition_point(|record| before(record.offset))
220    }
221
222    /// The system exclusive bytes of the events in `range`.
223    pub(crate) fn sysex_bytes_in(&self, range: std::ops::Range<usize>) -> usize {
224        self.records[range]
225            .iter()
226            .map(|record| match record.data {
227                RecordData::SysEx { length, .. } => length,
228                _ => 0,
229            })
230            .sum()
231    }
232}
233
234fn event<'a>(record: &Record, sysex: &'a [u8]) -> Event<'a> {
235    let data = match record.data {
236        RecordData::Midi(bytes) => EventData::Midi(bytes),
237        RecordData::SysEx { start, length } => EventData::SysEx(&sysex[start..start + length]),
238        RecordData::NoteOn(note) => EventData::NoteOn(note),
239        RecordData::NoteOff(note) => EventData::NoteOff(note),
240        RecordData::Expression(expression) => EventData::Expression(expression),
241    };
242    Event {
243        offset: record.offset,
244        port: record.port,
245        data,
246    }
247}
248
249impl Clone for Events {
250    /// A copy of the events, with one block's room reserved again when they hold one block's.
251    fn clone(&self) -> Events {
252        let mut copy = if self.bounded {
253            Events::for_block()
254        } else {
255            Events::new()
256        };
257        copy.records.extend_from_slice(&self.records);
258        copy.sysex.extend_from_slice(&self.sysex);
259        copy
260    }
261}
262
263impl PartialEq for Events {
264    /// Events are equal when they hold equal events in the same order, whatever their room.
265    fn eq(&self, other: &Events) -> bool {
266        self.len() == other.len() && self.iter().eq(other.iter())
267    }
268}
269
270impl<'a> PartialEq<[Event<'a>]> for Events {
271    fn eq(&self, other: &[Event<'a>]) -> bool {
272        self.len() == other.len() && self.iter().eq(other.iter().copied())
273    }
274}
275
276impl<'a, const N: usize> PartialEq<[Event<'a>; N]> for Events {
277    fn eq(&self, other: &[Event<'a>; N]) -> bool {
278        *self == other[..]
279    }
280}
281
282impl<'a> PartialEq<Vec<Event<'a>>> for Events {
283    fn eq(&self, other: &Vec<Event<'a>>) -> bool {
284        *self == other[..]
285    }
286}
287
288impl fmt::Debug for Events {
289    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
290        f.debug_list().entries(self.iter()).finish()
291    }
292}
293
294impl<'a> FromIterator<Event<'a>> for Events {
295    /// Events of any number, as [`Events::new`] holds.
296    fn from_iter<I: IntoIterator<Item = Event<'a>>>(events: I) -> Events {
297        let mut collected = Events::new();
298        for event in events {
299            collected.append(event);
300        }
301        collected
302    }
303}
304
305impl<'a> IntoIterator for &'a Events {
306    type Item = Event<'a>;
307    type IntoIter = Iter<'a>;
308
309    fn into_iter(self) -> Iter<'a> {
310        self.iter()
311    }
312}
313
314/// The events of an [`Events`], in order.
315#[derive(Clone, Debug)]
316pub struct Iter<'a> {
317    records: std::slice::Iter<'a, Record>,
318    sysex: &'a [u8],
319}
320
321impl<'a> Iterator for Iter<'a> {
322    type Item = Event<'a>;
323
324    fn next(&mut self) -> Option<Event<'a>> {
325        self.records.next().map(|record| event(record, self.sysex))
326    }
327
328    fn size_hint(&self) -> (usize, Option<usize>) {
329        self.records.size_hint()
330    }
331
332    fn nth(&mut self, n: usize) -> Option<Event<'a>> {
333        self.records.nth(n).map(|record| event(record, self.sysex))
334    }
335}
336
337impl DoubleEndedIterator for Iter<'_> {
338    fn next_back(&mut self) -> Option<Self::Item> {
339        self.records
340            .next_back()
341            .map(|record| event(record, self.sysex))
342    }
343}
344
345impl ExactSizeIterator for Iter<'_> {}
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350
351    #[test]
352    fn events_keep_their_system_exclusive_bytes_apart_and_in_order() {
353        let mut events = Events::new();
354        events.push(Event::note_on(0, 0, 60, 100)).unwrap();
355        events
356            .push(Event::sysex(3, &[0xF0, 1, 0xF7]).on_port(1))
357            .unwrap();
358        events.push(Event::sysex(5, &[0xF0, 2, 3, 0xF7])).unwrap();
359        assert_eq!(events.len(), 3);
360        assert_eq!(events.sysex_bytes(), 7);
361        assert_eq!(
362            events.iter().collect::<Vec<_>>(),
363            [
364                Event::note_on(0, 0, 60, 100),
365                Event::sysex(3, &[0xF0, 1, 0xF7]).on_port(1),
366                Event::sysex(5, &[0xF0, 2, 3, 0xF7]),
367            ]
368        );
369        assert_eq!(events.get(2), Some(Event::sysex(5, &[0xF0, 2, 3, 0xF7])));
370        assert_eq!(events, events.iter().collect::<Events>());
371        events.clear();
372        assert!(events.is_empty() && events.sysex_bytes() == 0);
373    }
374
375    #[test]
376    fn a_block_takes_its_budget_without_allocating_and_refuses_more() {
377        let mut events = Events::for_block();
378        let (records, sysex) = (events.records.capacity(), events.sysex.capacity());
379        let message = [0xF0, 0x7D, 0xF7];
380        for _ in 0..MAX_BLOCK_EVENTS {
381            events.push(Event::sysex(0, &message[..])).unwrap();
382        }
383        assert_eq!(
384            events.push(Event::note_on(0, 0, 60, 1)),
385            Err(InputError::EventCapacity)
386        );
387        assert_eq!(events.len(), MAX_BLOCK_EVENTS);
388        events.clear();
389        let mut large = vec![0; MAX_BLOCK_SYSEX_BYTES];
390        (large[0], large[MAX_BLOCK_SYSEX_BYTES - 1]) = (0xF0, 0xF7);
391        events.push(Event::sysex(0, &large)).unwrap();
392        assert_eq!(
393            events.push(Event::sysex(0, &message[..])),
394            Err(InputError::EventCapacity)
395        );
396        assert!(!events.push_within_capacity(Event::sysex(0, &message[..])));
397        assert_eq!(
398            (events.records.capacity(), events.sysex.capacity()),
399            (records, sysex)
400        );
401        // Unbounded events grow, but push within their room only without allocating.
402        let mut events = Events::new();
403        assert!(!events.push_within_capacity(Event::note_on(0, 0, 60, 1)));
404        events.push(Event::note_on(0, 0, 60, 1)).unwrap();
405    }
406}