music_note/midi/
octave.rs

1use super::MidiNote;
2use crate::Pitch;
3use core::fmt;
4
5/// A note's octave in MIDI.
6#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
7pub struct Octave(i8);
8
9impl Octave {
10    /// Octave -1
11    pub const NEGATIVE_ONE: Self = Self(-1);
12    /// Octave 0
13    pub const ZERO: Self = Self(0);
14    /// Octave 1
15    pub const ONE: Self = Self(1);
16    /// Octave 2
17    pub const TWO: Self = Self(2);
18    /// Octave 3
19    pub const THREE: Self = Self(3);
20    /// Octave 4
21    pub const FOUR: Self = Self(4);
22    /// Octave 5
23    pub const FIVE: Self = Self(5);
24    /// Octave 6
25    pub const SIX: Self = Self(6);
26    /// Octave 7
27    pub const SEVEN: Self = Self(7);
28    /// Octave 8
29    pub const EIGHT: Self = Self(8);
30
31    pub fn new_unchecked(num: i8) -> Self {
32        Self(num)
33    }
34
35    /// Return the `Octave` of the given midinote.
36    pub const fn from_midi(note: MidiNote) -> Self {
37        Self((note.into_byte() / (Pitch::B.into_byte() + 1)) as i8 - 1)
38    }
39
40    /// Return the i8 representation of `self`.
41    pub const fn into_i8(self) -> i8 {
42        self.0
43    }
44}
45
46impl fmt::Display for Octave {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        write!(f, "{}", self.0)
49    }
50}