1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
use crate::{midi::MidiNote, note::Note, Interval, Natural};
use core::ops::{Add, Sub};
use core::{fmt, mem};
#[repr(u8)]
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum Pitch {
C,
CSharp,
D,
DSharp,
E,
F,
FSharp,
G,
GSharp,
A,
ASharp,
B,
}
impl Pitch {
pub const fn natural(letter: Natural) -> Self {
match letter {
Natural::C => Self::C,
Natural::D => Self::D,
Natural::E => Self::E,
Natural::F => Self::F,
Natural::G => Self::G,
Natural::A => Self::A,
Natural::B => Self::B,
}
}
pub const fn from_byte(byte: u8) -> Self {
unsafe { mem::transmute(byte % (Self::B.into_byte() + 1)) }
}
pub const fn add_interval(self, interval: Interval) -> Self {
unsafe { mem::transmute((self as u8 + interval.semitones()) % (Self::B as u8 + 1)) }
}
pub const fn sub_interval(self, interval: Interval) -> Self {
Self::from_byte((self as u8 as i8 - interval.semitones() as i8).abs() as u8)
}
pub const fn into_byte(self) -> u8 {
self as _
}
pub const fn sub(self, rhs: Self) -> Interval {
Interval::new(self as u8 - rhs as u8)
}
pub fn transpose(self, key: Pitch, to: Pitch) -> Pitch {
let f = self - key;
to + f
}
}
impl From<Natural> for Pitch {
fn from(letter: Natural) -> Self {
match letter {
Natural::C => Self::C,
Natural::D => Self::D,
Natural::E => Self::E,
Natural::F => Self::F,
Natural::G => Self::G,
Natural::A => Self::A,
Natural::B => Self::B,
}
}
}
impl From<Note> for Pitch {
fn from(note: Note) -> Self {
note.pitch()
}
}
impl From<MidiNote> for Pitch {
fn from(midi: MidiNote) -> Self {
midi.pitch()
}
}
impl From<Pitch> for u8 {
fn from(pitch: Pitch) -> Self {
pitch.into_byte()
}
}
impl Add<Interval> for Pitch {
type Output = Self;
fn add(self, interval: Interval) -> Self {
self.add_interval(interval)
}
}
impl Sub for Pitch {
type Output = Interval;
fn sub(self, rhs: Self) -> Interval {
self.sub(rhs)
}
}
impl fmt::Display for Pitch {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let s = match self {
Pitch::C => "C",
Pitch::CSharp => "C#",
Pitch::D => "D",
Pitch::DSharp => "D#",
Pitch::E => "E",
Pitch::F => "F",
Pitch::FSharp => "F#",
Pitch::G => "G",
Pitch::GSharp => "G#",
Pitch::A => "A",
Pitch::ASharp => "A#",
Pitch::B => "B",
};
f.write_str(s)
}
}