Skip to main content

deepmind_midi/
error.rs

1//! Crate-wide error type.
2//!
3//! The library never panics on malformed input. Anything that arrives from a MIDI
4//! port or a `.syx` file is untrusted and every rejection carries the offending
5//! value so a host application can log something actionable.
6
7use core::fmt;
8
9/// Convenience alias for results produced by this crate.
10pub type Result<T, E = Error> = core::result::Result<T, E>;
11
12/// Everything that can go wrong while parsing or building `DeepMind` messages.
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14#[non_exhaustive]
15pub enum Error {
16    /// A device ID byte was neither `0..=15` nor `0x7F`.
17    InvalidDeviceId(u8),
18    /// A bank index was 8 or greater.
19    BankOutOfRange(u8),
20    /// A bank letter was outside `A..=H`.
21    BankLetter(char),
22    /// A program number was 128 or greater.
23    ProgramOutOfRange(u8),
24    /// A run of programs ended before it started.
25    EmptyRun {
26        /// Program number the run was to start at.
27        first: u8,
28        /// Program number it was to end at, which was lower.
29        last: u8,
30    },
31    /// A user pattern number was 32 or greater.
32    PatternOutOfRange(u8),
33    /// A MIDI channel was 16 or greater.
34    ChannelOutOfRange(u8),
35    /// A parameter offset was 242 or greater, so it names no parameter.
36    ParameterOutOfRange(u8),
37    /// An effect engine number was outside the four the synthesizer has.
38    EngineOutOfRange(u8),
39    /// A value was outside the range its parameter accepts.
40    ValueOutOfRange {
41        /// Offset of the parameter the value was meant for.
42        parameter: u8,
43        /// The value offered.
44        value: u16,
45        /// Highest value the parameter accepts. The lowest is always zero.
46        max: u16,
47    },
48    /// A dump carried a comms protocol version this build does not understand.
49    UnsupportedProtocolVersion(u8),
50    /// Program data was not as long as its comms protocol version calls for.
51    ProgramLength {
52        /// Bytes the version's program data occupies.
53        expected: usize,
54        /// Bytes that were offered.
55        found: usize,
56    },
57    /// A message that carries no program was read as one.
58    NotAProgramDump(u8),
59    /// A program name was longer than sixteen characters.
60    ProgramNameTooLong(usize),
61    /// A program name held a character the display has no glyph for.
62    ProgramNameCharacter(char),
63    /// A `SysEx` frame did not start with `F0` or did not end with `F7`.
64    Unframed,
65    /// A `SysEx` frame was too short to carry the header every message has.
66    ShortFrame(usize),
67    /// A `SysEx` frame carried another manufacturer's or another model's ID.
68    Foreign {
69        /// The three manufacturer ID bytes the frame carried.
70        manufacturer: [u8; 3],
71        /// The model ID byte the frame carried.
72        model: u8,
73    },
74    /// A command byte no documented message uses.
75    UnknownCommand(u8),
76    /// A payload was not the length its command requires.
77    PayloadLength {
78        /// Command byte of the message being parsed.
79        command: u8,
80        /// Payload length the command calls for.
81        expected: usize,
82        /// Payload length the frame actually carried.
83        found: usize,
84    },
85    /// A packed run ended in a high-bit byte with no data bytes to apply it to.
86    PackedRunLength(usize),
87    /// A byte meant for the inside of a `SysEx` frame had its high bit set.
88    NotSevenBit(u8),
89    /// An output buffer was too small for what had to be written into it.
90    BufferTooSmall {
91        /// Bytes the operation needed.
92        needed: usize,
93        /// Bytes the caller supplied.
94        available: usize,
95    },
96    /// A `SysEx` frame was longer than the decoder's buffer, and was dropped.
97    SysExTooLong(usize),
98    /// A status byte arrived before a `SysEx` frame's `F7`, ending it early.
99    SysExInterrupted,
100    /// An interface byte was neither MIDI (0), USB (1) nor Wi-Fi (2).
101    InvalidInterface(u8),
102    /// A universal `SysEx` frame was not a device inquiry request.
103    NotAnInquiryRequest,
104    /// A universal `SysEx` frame was not a `DeepMind` device inquiry response.
105    NotAnInquiryResponse,
106    /// An edit was made before any program was known, so nothing said what
107    /// changed.
108    ProgramNotKnown,
109    /// More was queued to send than the outbound queue had room for.
110    QueueFull {
111        /// Items the operation needed room for.
112        needed: usize,
113        /// Items the queue had room for.
114        available: usize,
115    },
116}
117
118impl fmt::Display for Error {
119    #[expect(clippy::too_many_lines, reason = "one arm per variant")]
120    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121        match self {
122            Self::InvalidDeviceId(byte) => {
123                write!(
124                    f,
125                    "invalid device ID {byte:#04X}, expected 0x00..=0x0F or 0x7F"
126                )
127            }
128            Self::BankOutOfRange(index) => write!(f, "bank {index} out of range, expected 0..=7"),
129            Self::BankLetter(letter) => write!(f, "bank {letter:?} is not a letter A..=H"),
130            Self::ProgramOutOfRange(number) => {
131                write!(f, "program {number} out of range, expected 0..=127")
132            }
133            Self::EmptyRun { first, last } => {
134                write!(
135                    f,
136                    "run from program {first} to {last} ends before it starts"
137                )
138            }
139            Self::PatternOutOfRange(number) => {
140                write!(f, "pattern {number} out of range, expected 0..=31")
141            }
142            Self::ChannelOutOfRange(channel) => {
143                write!(f, "MIDI channel {channel} out of range, expected 0..=15")
144            }
145            Self::ParameterOutOfRange(offset) => {
146                write!(
147                    f,
148                    "parameter offset {offset} out of range, expected 0..=241"
149                )
150            }
151            Self::EngineOutOfRange(engine) => {
152                write!(f, "effect engine {engine} out of range, expected 1..=4")
153            }
154            Self::ValueOutOfRange {
155                parameter,
156                value,
157                max,
158            } => write!(
159                f,
160                "value {value} out of range for parameter {parameter}, expected 0..={max}"
161            ),
162            Self::UnsupportedProtocolVersion(version) => {
163                write!(
164                    f,
165                    "unsupported comms protocol version {version}, expected 6 or 7"
166                )
167            }
168            Self::ProgramLength { expected, found } => {
169                write!(f, "program data of {found} bytes, expected {expected}")
170            }
171            Self::NotAProgramDump(command) => {
172                write!(f, "command {command:#04X} carries no program")
173            }
174            Self::ProgramNameTooLong(len) => {
175                write!(f, "program name of {len} characters, expected 16 or fewer")
176            }
177            Self::ProgramNameCharacter(character) => write!(
178                f,
179                "program name holds {character:?}, expected printable ASCII"
180            ),
181            Self::Unframed => f.write_str("not a SysEx frame: expected F0 ... F7"),
182            Self::ShortFrame(len) => {
183                write!(
184                    f,
185                    "SysEx frame of {len} bytes is too short to carry a header"
186                )
187            }
188            Self::Foreign {
189                manufacturer: [a, b, c],
190                model,
191            } => write!(
192                f,
193                "SysEx frame for manufacturer {a:02X} {b:02X} {c:02X} model {model:02X}, \
194                 not Behringer 00 20 32 model 20"
195            ),
196            Self::UnknownCommand(command) => {
197                write!(f, "unknown SysEx command {command:#04X}")
198            }
199            Self::PayloadLength {
200                command,
201                expected,
202                found,
203            } => write!(
204                f,
205                "command {command:#04X} carries a {found} byte payload, expected {expected}"
206            ),
207            Self::PackedRunLength(len) => write!(
208                f,
209                "packed run of {len} bytes ends in a high-bit byte with no data"
210            ),
211            Self::NotSevenBit(byte) => {
212                write!(f, "byte {byte:#04X} cannot travel inside a SysEx frame")
213            }
214            Self::BufferTooSmall { needed, available } => {
215                write!(f, "buffer of {available} bytes is too small, need {needed}")
216            }
217            Self::SysExTooLong(capacity) => {
218                write!(f, "SysEx frame longer than the {capacity} byte buffer")
219            }
220            Self::SysExInterrupted => {
221                f.write_str("SysEx frame interrupted by a status byte before its F7")
222            }
223            Self::InvalidInterface(byte) => write!(
224                f,
225                "invalid interface {byte}, expected 0 (MIDI), 1 (USB) or 2 (Wi-Fi)"
226            ),
227            Self::NotAnInquiryRequest => f.write_str("not a device inquiry request"),
228            Self::NotAnInquiryResponse => f.write_str("not a DeepMind device inquiry response"),
229            Self::ProgramNotKnown => f.write_str("no program known yet, nothing to edit"),
230            Self::QueueFull { needed, available } => {
231                write!(f, "queue has room for {available} items, need {needed}")
232            }
233        }
234    }
235}
236
237impl core::error::Error for Error {}