Skip to content

Commit 35a75f1

Browse files
committed
TryFrom for General Midi enums
1 parent b4287b3 commit 35a75f1

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

src/general_midi.rs

+62
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::convert::TryFrom;
2+
13
#[cfg(feature = "std")]
24
use strum::{Display, EnumIter, EnumString};
35

@@ -162,6 +164,17 @@ pub enum GMSoundSet {
162164
Gunshot = 127,
163165
}
164166

167+
impl TryFrom<u8> for GMSoundSet {
168+
type Error = &'static str;
169+
170+
fn try_from(value: u8) -> Result<Self, Self::Error> {
171+
if value > 127 {
172+
return Err("Invalid value for GMSoundSet");
173+
}
174+
Ok(unsafe { std::mem::transmute(value) })
175+
}
176+
}
177+
165178
/// The General MIDI percussion sound to play for a given note number when targeting
166179
/// Channel 10.
167180
///
@@ -232,6 +245,17 @@ pub enum GMPercussionMap {
232245
OpenTriangle = 81,
233246
}
234247

248+
impl TryFrom<u8> for GMPercussionMap {
249+
type Error = &'static str;
250+
251+
fn try_from(value: u8) -> Result<Self, Self::Error> {
252+
if value < 35 || value > 81 {
253+
return Err("Invalid value for GMPercussionMap");
254+
}
255+
Ok(unsafe { std::mem::transmute(value) })
256+
}
257+
}
258+
235259
#[cfg(test)]
236260
mod tests {
237261
use super::*;
@@ -278,6 +302,44 @@ mod tests {
278302
assert_eq!(127, GMSoundSet::Gunshot as u8);
279303
}
280304

305+
#[test]
306+
fn gm_from_u8() {
307+
assert_eq!(
308+
GMSoundSet::AcousticGrandPiano,
309+
GMSoundSet::try_from(0).unwrap()
310+
);
311+
assert_eq!(GMSoundSet::Gunshot, GMSoundSet::try_from(127).unwrap());
312+
}
313+
314+
#[test]
315+
fn gm_from_u8_invalid() {
316+
assert!(GMSoundSet::try_from(128).is_err());
317+
}
318+
319+
#[test]
320+
fn gm_percussion_as_u8() {
321+
assert_eq!(35, GMPercussionMap::AcousticBassDrum as u8);
322+
assert_eq!(81, GMPercussionMap::OpenTriangle as u8);
323+
}
324+
325+
#[test]
326+
fn gm_percussion_from_u8() {
327+
assert_eq!(
328+
GMPercussionMap::AcousticBassDrum,
329+
GMPercussionMap::try_from(35).unwrap()
330+
);
331+
assert_eq!(
332+
GMPercussionMap::OpenTriangle,
333+
GMPercussionMap::try_from(81).unwrap()
334+
);
335+
}
336+
337+
#[test]
338+
fn gm_percussion_from_u8_invalid() {
339+
assert!(GMPercussionMap::try_from(34).is_err());
340+
assert!(GMPercussionMap::try_from(82).is_err());
341+
}
342+
281343
#[cfg(feature = "std")]
282344
#[test]
283345
fn percussion_iter() {

0 commit comments

Comments
 (0)