Skip to content

Commit

Permalink
TryFrom for General Midi enums
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexCharlton committed Jan 26, 2025
1 parent b4287b3 commit 7a44de9
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions src/general_midi.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use core::convert::TryFrom;

#[cfg(feature = "std")]
use strum::{Display, EnumIter, EnumString};

Expand Down Expand Up @@ -162,6 +164,17 @@ pub enum GMSoundSet {
Gunshot = 127,
}

impl TryFrom<u8> for GMSoundSet {
type Error = &'static str;

fn try_from(value: u8) -> Result<Self, Self::Error> {
if value > 127 {
return Err("Invalid value for GMSoundSet");
}
Ok(unsafe { std::mem::transmute(value) })
}
}

/// The General MIDI percussion sound to play for a given note number when targeting
/// Channel 10.
///
Expand Down Expand Up @@ -232,6 +245,17 @@ pub enum GMPercussionMap {
OpenTriangle = 81,
}

impl TryFrom<u8> for GMPercussionMap {
type Error = &'static str;

fn try_from(value: u8) -> Result<Self, Self::Error> {
if value < 35 || value > 81 {
return Err("Invalid value for GMPercussionMap");
}
Ok(unsafe { std::mem::transmute(value) })
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -278,6 +302,44 @@ mod tests {
assert_eq!(127, GMSoundSet::Gunshot as u8);
}

#[test]
fn gm_from_u8() {
assert_eq!(
GMSoundSet::AcousticGrandPiano,
GMSoundSet::try_from(0).unwrap()
);
assert_eq!(GMSoundSet::Gunshot, GMSoundSet::try_from(127).unwrap());
}

#[test]
fn gm_from_u8_invalid() {
assert!(GMSoundSet::try_from(128).is_err());
}

#[test]
fn gm_percussion_as_u8() {
assert_eq!(35, GMPercussionMap::AcousticBassDrum as u8);
assert_eq!(81, GMPercussionMap::OpenTriangle as u8);
}

#[test]
fn gm_percussion_from_u8() {
assert_eq!(
GMPercussionMap::AcousticBassDrum,
GMPercussionMap::try_from(35).unwrap()
);
assert_eq!(
GMPercussionMap::OpenTriangle,
GMPercussionMap::try_from(81).unwrap()
);
}

#[test]
fn gm_percussion_from_u8_invalid() {
assert!(GMPercussionMap::try_from(34).is_err());
assert!(GMPercussionMap::try_from(82).is_err());
}

#[cfg(feature = "std")]
#[test]
fn percussion_iter() {
Expand Down

0 comments on commit 7a44de9

Please sign in to comment.