dimi/midi/
note.rs

1// Copyright © 2021 The Dimi Crate Developers
2//
3// Licensed under any of:
4// - Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0)
5// - Boost Software License, Version 1.0 (https://www.boost.org/LICENSE_1_0.txt)
6// - MIT License (https://mit-license.org/)
7// At your option (See accompanying files LICENSE_APACHE_2_0.txt,
8// LICENSE_MIT.txt and LICENSE_BOOST_1_0.txt).  This file may not be copied,
9// modified, or distributed except according to those terms.
10
11use core::convert::TryFrom;
12
13/// A note and octave of the Western scale.
14///
15///  In this library, C4 is middle C and octaves range from -1 to 9
16#[derive(Debug, Copy, Clone, PartialEq, Eq)]
17pub enum Note {
18    /// The C Note in the Western Scale
19    C(i8),
20    /// The D-Flat Note in the Western Scale
21    Db(i8),
22    /// The D Note in the Western Scale
23    D(i8),
24    /// The E-Flat Note in the Western Scale
25    Eb(i8),
26    /// The E Note in the Western Scale
27    E(i8),
28    /// The F Note in the Western Scale
29    F(i8),
30    /// The G-Flat Note in the Western Scale
31    Gb(i8),
32    /// The G Note in the Western Scale
33    G(i8),
34    /// The A-Flat Note in the Western Scale
35    Ab(i8),
36    /// The A Note in the Western Scale
37    A(i8),
38    /// The B-Flat Note in the Western Scale
39    Bb(i8),
40    /// The B Note in the Western Scale
41    B(i8),
42}
43
44impl TryFrom<u8> for Note {
45    type Error = std::num::TryFromIntError;
46
47    fn try_from(note: u8) -> Result<Self, Self::Error> {
48        let note = i8::try_from(note)?;
49        let octave = note / 12;
50        let note = match note % 12 {
51            0 => Note::C,
52            1 => Note::Db,
53            2 => Note::D,
54            3 => Note::Eb,
55            4 => Note::E,
56            5 => Note::F,
57            6 => Note::Gb,
58            7 => Note::G,
59            8 => Note::Ab,
60            9 => Note::A,
61            10 => Note::Bb,
62            11 => Note::B,
63            _ => unreachable!(),
64        };
65        Ok(note(octave - 1))
66    }
67}