1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//! The MIDI connection, as the driver loop needs to see it.
/// A MIDI connection the driver loop can read from and write to.
///
/// Two methods, which is what driving the state machine takes. Everything else a
/// real backend has (port enumeration, virtual ports, connection state,
/// reconnection) stays on the host's side of this trait.
///
/// # Implementing it
///
/// Most backends deliver inbound bytes on a callback thread rather than to a
/// reader, so the usual shape is a queue the callback fills and
/// [`receive`](Port::receive) drains:
///
/// ```
/// use std::sync::mpsc::{Receiver, TryRecvError};
///
/// use deepmind_midi::transport::Port;
///
/// struct Connection {
/// outbound: Vec<Vec<u8>>, // whatever the backend sends with
/// inbound: Receiver<Vec<u8>>, // filled by the backend's callback thread
/// partial: Vec<u8>, // what did not fit in the last read
/// }
///
/// impl Port for Connection {
/// type Error = std::io::Error;
///
/// fn send(&mut self, bytes: &[u8]) -> Result<(), Self::Error> {
/// self.outbound.push(bytes.to_vec());
/// Ok(())
/// }
///
/// fn receive(&mut self, into: &mut [u8]) -> Result<usize, Self::Error> {
/// if self.partial.is_empty() {
/// match self.inbound.try_recv() {
/// Ok(message) => self.partial = message,
/// Err(TryRecvError::Empty) => return Ok(0),
/// // A gone connection is an error, never a quiet one.
/// Err(TryRecvError::Disconnected) => {
/// return Err(std::io::ErrorKind::BrokenPipe.into());
/// }
/// }
/// }
/// let taken = self.partial.len().min(into.len());
/// into[..taken].copy_from_slice(&self.partial[..taken]);
/// self.partial.drain(..taken);
/// Ok(taken)
/// }
/// }
/// ```
///
/// The buffer a [`Transport`](super::Transport) offers is as long as the
/// decoder's frame buffer, so the longest frame the library can read fits in one
/// call and the `partial` above never holds anything in practice. Keep it
/// anyway: the contract is "as much as fits", not "all or nothing".