|
| 1 | +use std::convert::TryFrom; |
| 2 | + |
1 | 3 | #[cfg(feature = "std")]
|
2 | 4 | use strum::{Display, EnumIter, EnumString};
|
3 | 5 |
|
@@ -162,6 +164,17 @@ pub enum GMSoundSet {
|
162 | 164 | Gunshot = 127,
|
163 | 165 | }
|
164 | 166 |
|
| 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 | + |
165 | 178 | /// The General MIDI percussion sound to play for a given note number when targeting
|
166 | 179 | /// Channel 10.
|
167 | 180 | ///
|
@@ -232,6 +245,17 @@ pub enum GMPercussionMap {
|
232 | 245 | OpenTriangle = 81,
|
233 | 246 | }
|
234 | 247 |
|
| 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 | + |
235 | 259 | #[cfg(test)]
|
236 | 260 | mod tests {
|
237 | 261 | use super::*;
|
@@ -278,6 +302,44 @@ mod tests {
|
278 | 302 | assert_eq!(127, GMSoundSet::Gunshot as u8);
|
279 | 303 | }
|
280 | 304 |
|
| 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 | + |
281 | 343 | #[cfg(feature = "std")]
|
282 | 344 | #[test]
|
283 | 345 | fn percussion_iter() {
|
|
0 commit comments