Skip to main content

deepmind_midi/program/
name.rs

1//! The name of a program: sixteen characters, as the synthesizer displays them.
2
3use core::fmt;
4use core::str::FromStr;
5
6use crate::error::{Error, Result};
7
8/// A program's name.
9///
10/// Sixteen characters at most, printable ASCII, and no terminator: the
11/// terminator belongs to the field a name is stored in, not to the name.
12///
13/// ```
14/// use deepmind_midi::program::ProgramName;
15///
16/// let name = ProgramName::new("Bass Sweep")?;
17/// assert_eq!(name.as_str(), "Bass Sweep");
18/// assert_eq!(name.to_string(), "Bass Sweep");
19///
20/// assert!(ProgramName::new("Seventeen Charact").is_err());
21/// assert!(ProgramName::new("Caffè").is_err());
22/// # Ok::<(), deepmind_midi::Error>(())
23/// ```
24#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
25pub struct ProgramName {
26    bytes: [u8; ProgramName::MAX_CHARS],
27    len: u8,
28}
29
30impl ProgramName {
31    /// Characters a name holds at most.
32    pub const MAX_CHARS: usize = 16;
33
34    /// The empty name, which is what an unnamed program carries.
35    pub const EMPTY: Self = Self {
36        bytes: [0; Self::MAX_CHARS],
37        len: 0,
38    };
39
40    /// Builds a name from a string.
41    ///
42    /// # Errors
43    ///
44    /// Returns [`Error::ProgramNameTooLong`] past [`ProgramName::MAX_CHARS`] and
45    /// [`Error::ProgramNameCharacter`] for a character the synthesizer's display
46    /// has no glyph for, which is anything but printable ASCII.
47    pub fn new(text: &str) -> Result<Self> {
48        if text.chars().count() > Self::MAX_CHARS {
49            return Err(Error::ProgramNameTooLong(text.chars().count()));
50        }
51        let mut name = Self::EMPTY;
52        for (slot, character) in name.bytes.iter_mut().zip(text.chars()) {
53            if !character.is_ascii() || character.is_ascii_control() {
54                return Err(Error::ProgramNameCharacter(character));
55            }
56            *slot = u8::try_from(character).unwrap_or(b' ');
57            name.len = name.len.saturating_add(1);
58        }
59        Ok(name)
60    }
61
62    /// Reads a name out of the field that stores it, stopping at the
63    /// terminator.
64    ///
65    /// Lenient, because this is what arrives from a port or a file: a field with
66    /// no terminator is a full sixteen characters, and a byte the display has no
67    /// glyph for becomes a question mark. Nothing the synthesizer sends reaches
68    /// either case, since the name parameters stop at 127.
69    pub(super) fn from_field(field: &[u8]) -> Self {
70        let mut name = Self::EMPTY;
71        for (slot, byte) in name.bytes.iter_mut().zip(field) {
72            if *byte == 0 {
73                break;
74            }
75            *slot = if byte.is_ascii() && !byte.is_ascii_control() {
76                *byte
77            } else {
78                b'?'
79            };
80            name.len = name.len.saturating_add(1);
81        }
82        name
83    }
84
85    /// Returns the name as a string.
86    #[must_use]
87    pub fn as_str(&self) -> &str {
88        // Every stored byte is printable ASCII, which is valid UTF-8.
89        core::str::from_utf8(self.as_bytes()).unwrap_or_default()
90    }
91
92    /// Returns the characters the name holds, without a terminator.
93    #[must_use]
94    pub fn as_bytes(&self) -> &[u8] {
95        self.bytes.get(..usize::from(self.len)).unwrap_or_default()
96    }
97
98    /// Returns the number of characters in the name.
99    #[must_use]
100    pub const fn len(&self) -> usize {
101        self.len as usize
102    }
103
104    /// Returns whether the name is empty.
105    #[must_use]
106    pub const fn is_empty(&self) -> bool {
107        self.len == 0
108    }
109}
110
111/// Serializes as the string it displays as, so `"Bass Sweep"` is the whole of
112/// it in any format.
113#[cfg(feature = "serde")]
114#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
115impl serde::Serialize for ProgramName {
116    fn serialize<S: serde::Serializer>(
117        &self,
118        serializer: S,
119    ) -> core::result::Result<S::Ok, S::Error> {
120        serializer.serialize_str(self.as_str())
121    }
122}
123
124/// Deserializes from a string, through [`ProgramName::new`], so the length
125/// and character rules hold for a name that came out of a file too.
126#[cfg(feature = "serde")]
127#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
128impl<'de> serde::Deserialize<'de> for ProgramName {
129    fn deserialize<D: serde::Deserializer<'de>>(
130        deserializer: D,
131    ) -> core::result::Result<Self, D::Error> {
132        struct Visitor;
133
134        impl serde::de::Visitor<'_> for Visitor {
135            type Value = ProgramName;
136
137            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
138                f.write_str("a program name of up to sixteen printable ASCII characters")
139            }
140
141            fn visit_str<E: serde::de::Error>(
142                self,
143                text: &str,
144            ) -> core::result::Result<Self::Value, E> {
145                ProgramName::new(text).map_err(E::custom)
146            }
147        }
148
149        deserializer.deserialize_str(Visitor)
150    }
151}
152
153impl fmt::Display for ProgramName {
154    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
155        f.write_str(self.as_str())
156    }
157}
158
159impl fmt::Debug for ProgramName {
160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161        fmt::Debug::fmt(self.as_str(), f)
162    }
163}
164
165impl AsRef<str> for ProgramName {
166    fn as_ref(&self) -> &str {
167        self.as_str()
168    }
169}
170
171impl TryFrom<&str> for ProgramName {
172    type Error = Error;
173
174    fn try_from(text: &str) -> Result<Self> {
175        Self::new(text)
176    }
177}
178
179impl FromStr for ProgramName {
180    type Err = Error;
181
182    fn from_str(text: &str) -> Result<Self> {
183        Self::new(text)
184    }
185}
186
187#[cfg(test)]
188#[expect(
189    clippy::expect_used,
190    reason = "a failed expectation is the test failure"
191)]
192mod tests {
193    use super::*;
194
195    #[test]
196    fn a_name_is_sixteen_printable_characters_at_most() {
197        assert_eq!(
198            ProgramName::new("Sixteen Charactr")
199                .expect("sixteen characters")
200                .len(),
201            16
202        );
203        assert_eq!(
204            ProgramName::new("Seventeen Charact"),
205            Err(Error::ProgramNameTooLong(17))
206        );
207        assert_eq!(
208            ProgramName::new("Tab\there"),
209            Err(Error::ProgramNameCharacter('\t'))
210        );
211        assert_eq!(
212            ProgramName::new("Caffè"),
213            Err(Error::ProgramNameCharacter('è'))
214        );
215    }
216
217    #[test]
218    fn the_empty_name_is_the_default() {
219        let empty = ProgramName::default();
220        assert_eq!(empty, ProgramName::EMPTY);
221        assert!(empty.is_empty());
222        assert_eq!(empty.as_str(), "");
223        assert_eq!(ProgramName::new("").expect("the empty name"), empty);
224    }
225
226    #[test]
227    fn a_field_ends_at_its_terminator() {
228        assert_eq!(ProgramName::from_field(b"Bass\0rubbish").as_str(), "Bass");
229        assert_eq!(ProgramName::from_field(b"").as_str(), "");
230        assert_eq!(ProgramName::from_field(b"\0").as_str(), "");
231    }
232
233    /// Hardware never sends this, since the name parameters stop at 127, but a
234    /// file is not hardware.
235    #[test]
236    fn a_byte_with_no_glyph_becomes_a_question_mark() {
237        assert_eq!(ProgramName::from_field(&[b'A', 0xFF, b'B']).as_str(), "A?B");
238        assert_eq!(ProgramName::from_field(&[b'A', 0x07]).as_str(), "A?");
239    }
240
241    #[test]
242    fn a_field_with_no_terminator_is_a_full_name() {
243        let field = b"SixteenCharacterAndMore";
244        assert_eq!(ProgramName::from_field(field).as_str(), "SixteenCharacter");
245    }
246
247    #[test]
248    fn a_name_parses_from_a_string() {
249        assert_eq!(
250            "Bass"
251                .parse::<ProgramName>()
252                .expect("a valid name")
253                .as_str(),
254            "Bass"
255        );
256        assert_eq!(
257            ProgramName::try_from("Bass")
258                .expect("a valid name")
259                .as_str(),
260            "Bass"
261        );
262    }
263}