Skip to main content

oscyl_midi/
push.rs

1//! A link whose bytes the platform moves (Android `MidiManager`, CoreMIDI):
2//! output goes to a closure, input is pushed in through an [`InputSender`].
3
4use std::sync::mpsc::Sender;
5use std::sync::{Arc, Mutex};
6use std::time::Instant;
7
8use crate::{Error, Feed, Inbox, Link, inbox};
9
10/// Where a [`PushLink`]'s output goes.
11pub type Output = Box<dyn FnMut(&[u8]) -> Result<(), Error> + Send>;
12
13/// Output through a closure; input pushed by the platform through the
14/// paired [`InputSender`] and framed into SysEx messages here.
15pub struct PushLink {
16    send: Output,
17    inbox: Inbox,
18}
19
20/// The input end of a [`PushLink`]: the platform pushes received bytes
21/// (in any fragments) and closes it when the port goes away.
22#[derive(Clone)]
23pub struct InputSender(Arc<Mutex<Option<Feed>>>);
24
25impl PushLink {
26    /// A link that sends through `send` (one call per [`Link::send`],
27    /// bytes unchanged), with the sender its input is pushed through.
28    pub fn new(send: Output) -> (PushLink, InputSender) {
29        let (inbox, feed) = inbox();
30        (
31            PushLink { send, inbox },
32            InputSender(Arc::new(Mutex::new(Some(feed)))),
33        )
34    }
35}
36
37impl Link for PushLink {
38    fn send(&mut self, bytes: &[u8]) -> Result<(), Error> {
39        (self.send)(bytes)
40    }
41
42    fn recv_until(&mut self, deadline: Instant) -> Result<Option<Vec<u8>>, Error> {
43        self.inbox.recv_until(deadline)
44    }
45
46    fn ring_on_input(&mut self, bell: Sender<()>) {
47        self.inbox.ring_on_input(bell);
48    }
49}
50
51impl InputSender {
52    /// Queue received bytes and ring the link's bell. Ignored once closed.
53    pub fn push(&self, bytes: &[u8]) {
54        if let Some(feed) = self.0.lock().unwrap_or_else(|e| e.into_inner()).as_ref() {
55            feed.push(bytes);
56        }
57    }
58
59    /// The port is gone: once queued input is read, the link reports
60    /// [`Error::Disconnected`]. The bell rings so a waiting worker sees it.
61    /// Dropping the last sender does the same.
62    pub fn close(&self) {
63        let feed = self.0.lock().unwrap_or_else(|e| e.into_inner()).take();
64        drop(feed);
65    }
66}
67
68#[cfg(test)]
69mod tests {
70    use super::*;
71    use std::sync::mpsc::channel;
72    use std::time::Duration;
73
74    fn link() -> (PushLink, InputSender) {
75        PushLink::new(Box::new(|_| Ok(())))
76    }
77
78    fn soon() -> Instant {
79        Instant::now() + Duration::from_secs(1)
80    }
81
82    #[test]
83    fn fragments_are_framed_in_order() {
84        let (mut link, input) = link();
85        input.push(&[0xF0, 0x42, 0x30]);
86        input.push(&[0x00, 0x01, 0xF7, 0xF0, 0x7E]);
87        input.push(&[0x01, 0xF7]);
88        assert_eq!(
89            link.recv_until(soon()).unwrap(),
90            Some(vec![0xF0, 0x42, 0x30, 0x00, 0x01, 0xF7])
91        );
92        assert_eq!(
93            link.recv_until(soon()).unwrap(),
94            Some(vec![0xF0, 0x7E, 0x01, 0xF7])
95        );
96        assert_eq!(link.recv_until(Instant::now()).unwrap(), None);
97    }
98
99    #[test]
100    fn close_disconnects_after_queued_input() {
101        let (mut link, input) = link();
102        input.push(&[0xF0, 0x01, 0xF7]);
103        input.clone().close();
104        assert_eq!(
105            link.recv_until(soon()).unwrap(),
106            Some(vec![0xF0, 0x01, 0xF7])
107        );
108        assert!(matches!(
109            link.recv_until(soon()),
110            Err(Error::Disconnected(_))
111        ));
112        // Pushing after close is ignored.
113        input.push(&[0xF0, 0x02, 0xF7]);
114        assert!(matches!(
115            link.recv_until(soon()),
116            Err(Error::Disconnected(_))
117        ));
118    }
119
120    #[test]
121    fn push_rings_the_bell() {
122        let (mut link, input) = link();
123        let (tx, rx) = channel();
124        link.ring_on_input(tx);
125        let t = std::thread::spawn(move || input.push(&[0xF0, 0x01, 0xF7]));
126        rx.recv().unwrap();
127        t.join().unwrap();
128        assert_eq!(
129            link.recv_until(soon()).unwrap(),
130            Some(vec![0xF0, 0x01, 0xF7])
131        );
132    }
133
134    #[test]
135    fn send_goes_to_closure() {
136        let sent = Arc::new(Mutex::new(Vec::<Vec<u8>>::new()));
137        let log = sent.clone();
138        let (mut link, _input) = PushLink::new(Box::new(move |b| {
139            log.lock().unwrap().push(b.to_vec());
140            Ok(())
141        }));
142        link.send(&[1, 2]).unwrap();
143        assert_eq!(*sent.lock().unwrap(), vec![vec![1, 2]]);
144    }
145}