sim_lib_pitch_core/model.rs
1use std::str::FromStr;
2
3use thiserror::Error;
4
5/// Error returned when a pitch, pitch class, or interval cannot be constructed
6/// or parsed.
7#[derive(Debug, Error, Clone, PartialEq, Eq)]
8pub enum PitchError {
9 /// A pitch-class value of 12 or greater was supplied where only `0..12` is valid.
10 #[error("invalid pitch class {0}")]
11 InvalidPitchClass(u8),
12 /// A pitch spelling could not be parsed into a letter, accidental, and octave.
13 #[error("invalid pitch spelling")]
14 InvalidPitch,
15 /// An interval spelling was not one of the recognized tokens.
16 #[error("invalid interval spelling")]
17 InvalidInterval,
18}
19
20/// A mod-12 pitch class, where `C = 0` and values increase by semitone to `B = 11`.
21///
22/// Pitch classes are octave-agnostic: every C, regardless of register, shares the
23/// pitch class `C`. The inner `u8` is always in the range `0..12`.
24///
25/// # Examples
26///
27/// ```
28/// use sim_lib_pitch_core::PitchClass;
29///
30/// assert_eq!(PitchClass::C.transpose(7), PitchClass::G);
31/// assert_eq!(PitchClass::E.interval_class(PitchClass::C), 4);
32/// ```
33#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
34pub struct PitchClass(pub u8);
35
36impl PitchClass {
37 /// The pitch class C (0).
38 pub const C: Self = Self(0);
39 /// The pitch class C-sharp / D-flat (1).
40 pub const CS: Self = Self(1);
41 /// The pitch class D (2).
42 pub const D: Self = Self(2);
43 /// The pitch class D-sharp / E-flat (3).
44 pub const DS: Self = Self(3);
45 /// The pitch class E (4).
46 pub const E: Self = Self(4);
47 /// The pitch class F (5).
48 pub const F: Self = Self(5);
49 /// The pitch class F-sharp / G-flat (6).
50 pub const FS: Self = Self(6);
51 /// The pitch class G (7).
52 pub const G: Self = Self(7);
53 /// The pitch class G-sharp / A-flat (8).
54 pub const GS: Self = Self(8);
55 /// The pitch class A (9).
56 pub const A: Self = Self(9);
57 /// The pitch class A-sharp / B-flat (10).
58 pub const AS: Self = Self(10);
59 /// The pitch class B (11).
60 pub const B: Self = Self(11);
61
62 /// Constructs a pitch class from a raw value, rejecting values of 12 or more.
63 pub fn new(value: u8) -> Result<Self, PitchError> {
64 if value < 12 {
65 Ok(Self(value))
66 } else {
67 Err(PitchError::InvalidPitchClass(value))
68 }
69 }
70
71 /// Returns this pitch class shifted up by `semitones` (or down if negative),
72 /// wrapping within the mod-12 octave.
73 pub fn transpose(self, semitones: i32) -> Self {
74 Self(((self.0 as i32 + semitones).rem_euclid(12)) as u8)
75 }
76
77 /// Returns the inversion of this pitch class about `axis`, wrapping within the
78 /// mod-12 octave.
79 pub fn invert(self, axis: PitchClass) -> Self {
80 Self(((2 * axis.0 as i32 - self.0 as i32).rem_euclid(12)) as u8)
81 }
82
83 /// Returns the interval class (0..=6) between this pitch class and `other`,
84 /// the smaller of the ascending and descending distances.
85 pub fn interval_class(self, other: PitchClass) -> u8 {
86 let delta = (other.0 as i32 - self.0 as i32).rem_euclid(12) as u8;
87 delta.min(12 - delta)
88 }
89
90 /// Returns the canonical sharp-spelled name of this pitch class (for example
91 /// `"C#"` for pitch class 1).
92 pub fn canonical_name(self) -> &'static str {
93 match self.0 {
94 0 => "C",
95 1 => "C#",
96 2 => "D",
97 3 => "D#",
98 4 => "E",
99 5 => "F",
100 6 => "F#",
101 7 => "G",
102 8 => "G#",
103 9 => "A",
104 10 => "A#",
105 11 => "B",
106 _ => unreachable!(),
107 }
108 }
109}
110
111/// An octave-aware pitch: a [`PitchClass`] together with an octave number.
112///
113/// The octave follows the MIDI convention in which middle C (`C4`) is MIDI note
114/// 60, so [`Pitch::semitone`] returns a continuous semitone index across octaves.
115#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
116pub struct Pitch {
117 /// The mod-12 pitch class.
118 pub class: PitchClass,
119 /// The octave number, with `C4` (MIDI 60) in octave 4.
120 pub octave: i16,
121}
122
123impl Pitch {
124 /// Returns the absolute semitone index of this pitch, where MIDI 60 (`C4`) is 60.
125 pub fn semitone(self) -> i32 {
126 (self.octave as i32 + 1) * 12 + self.class.0 as i32
127 }
128
129 /// Constructs a pitch from an absolute semitone index, the inverse of
130 /// [`Pitch::semitone`].
131 pub fn from_semitone(semitone: i32) -> Self {
132 Self {
133 class: PitchClass(semitone.rem_euclid(12) as u8),
134 octave: (semitone.div_euclid(12) - 1) as i16,
135 }
136 }
137
138 /// Returns the MIDI note number for this pitch, or `None` if it falls outside
139 /// the playable range `0..=127`.
140 pub fn to_midi(self) -> Option<u8> {
141 let semitone = self.semitone();
142 (0..=127).contains(&semitone).then_some(semitone as u8)
143 }
144
145 /// Constructs a pitch from a MIDI note number.
146 pub fn from_midi(value: u8) -> Self {
147 Self::from_semitone(value as i32)
148 }
149
150 /// Returns this pitch shifted by `semitones`, preserving the MIDI mapping.
151 pub fn transpose(self, semitones: i32) -> Self {
152 Self::from_semitone(self.semitone() + semitones)
153 }
154
155 /// Returns the inversion of this pitch about `axis`.
156 pub fn invert(self, axis: Pitch) -> Self {
157 Self::from_semitone(2 * axis.semitone() - self.semitone())
158 }
159}
160
161/// A diatonic letter name, independent of accidental.
162#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
163pub enum Letter {
164 /// The letter C.
165 C,
166 /// The letter D.
167 D,
168 /// The letter E.
169 E,
170 /// The letter F.
171 F,
172 /// The letter G.
173 G,
174 /// The letter A.
175 A,
176 /// The letter B.
177 B,
178}
179
180/// A spelled pitch: a diatonic [`Letter`], a chromatic accidental, and an octave.
181///
182/// Unlike [`Pitch`], a spelled pitch retains its enharmonic spelling, so `Cs4`
183/// and `Db4` are distinct even though they map to the same [`Pitch`].
184#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
185pub struct SpelledPitch {
186 /// The diatonic letter name.
187 pub letter: Letter,
188 /// The accidental offset in semitones (positive for sharps, negative for flats).
189 pub accidental: i8,
190 /// The octave number, following the MIDI convention.
191 pub octave: i16,
192}
193
194impl SpelledPitch {
195 /// Resolves this spelled pitch to its octave-aware [`Pitch`], discarding the
196 /// enharmonic spelling.
197 pub fn to_pitch(self) -> Pitch {
198 let base = match self.letter {
199 Letter::C => 0,
200 Letter::D => 2,
201 Letter::E => 4,
202 Letter::F => 5,
203 Letter::G => 7,
204 Letter::A => 9,
205 Letter::B => 11,
206 };
207 Pitch {
208 class: PitchClass((base + self.accidental as i32).rem_euclid(12) as u8),
209 octave: self.octave,
210 }
211 }
212}
213
214/// A pitch interval measured in semitones.
215///
216/// Positive values are ascending and negative values descending. The signed
217/// distance is preserved; use [`Interval::class`] to collapse to an interval class.
218#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
219pub struct Interval {
220 /// The signed distance in semitones.
221 pub semitones: i32,
222}
223
224impl Interval {
225 /// The perfect unison (0 semitones).
226 pub const UNISON: Self = Self { semitones: 0 };
227 /// The minor third (3 semitones).
228 pub const MINOR_3: Self = Self { semitones: 3 };
229 /// The major third (4 semitones).
230 pub const MAJOR_3: Self = Self { semitones: 4 };
231 /// The perfect fifth (7 semitones).
232 pub const PERFECT_5: Self = Self { semitones: 7 };
233 /// The tritone (6 semitones).
234 pub const TRITONE: Self = Self { semitones: 6 };
235 /// The major seventh (11 semitones).
236 pub const MAJOR_7: Self = Self { semitones: 11 };
237
238 /// Returns the directed interval from `a` to `b`.
239 pub fn between(a: Pitch, b: Pitch) -> Self {
240 Self {
241 semitones: b.semitone() - a.semitone(),
242 }
243 }
244
245 /// Returns the interval class (0..=6) of this interval, the smaller of the
246 /// ascending and descending mod-12 distances.
247 pub fn class(self) -> u8 {
248 let delta = self.semitones.rem_euclid(12) as u8;
249 delta.min(12 - delta)
250 }
251}
252
253impl FromStr for Pitch {
254 type Err = PitchError;
255
256 fn from_str(value: &str) -> Result<Self, Self::Err> {
257 parse_pitch(value)
258 }
259}
260
261impl FromStr for Interval {
262 type Err = PitchError;
263
264 fn from_str(value: &str) -> Result<Self, Self::Err> {
265 parse_interval(value)
266 }
267}
268
269/// Parses a pitch spelling such as `"C4"`, `"Eb5"`, or `"Cs4"` into a [`Pitch`].
270///
271/// Accidentals accept `#` or `s` for sharp and `b` for flat; an octave number is
272/// required. Returns [`PitchError::InvalidPitch`] on malformed input.
273///
274/// # Examples
275///
276/// ```
277/// use sim_lib_pitch_core::{parse_pitch, Pitch};
278///
279/// assert_eq!(parse_pitch("Eb5").unwrap(), Pitch::from_semitone(75));
280/// ```
281pub fn parse_pitch(value: &str) -> Result<Pitch, PitchError> {
282 let mut chars = value.chars();
283 let letter = match chars.next() {
284 Some('C') => Letter::C,
285 Some('D') => Letter::D,
286 Some('E') => Letter::E,
287 Some('F') => Letter::F,
288 Some('G') => Letter::G,
289 Some('A') => Letter::A,
290 Some('B') => Letter::B,
291 _ => return Err(PitchError::InvalidPitch),
292 };
293 let rest = chars.as_str();
294 let (accidental, octave_str) = if let Some(rest) = rest.strip_prefix('#') {
295 (1, rest)
296 } else if let Some(rest) = rest.strip_prefix('s') {
297 (1, rest)
298 } else if let Some(rest) = rest.strip_prefix('b') {
299 (-1, rest)
300 } else {
301 (0, rest)
302 };
303 if octave_str.is_empty() {
304 return Err(PitchError::InvalidPitch);
305 }
306 let octave = octave_str
307 .parse::<i16>()
308 .map_err(|_| PitchError::InvalidPitch)?;
309 Ok(SpelledPitch {
310 letter,
311 accidental,
312 octave,
313 }
314 .to_pitch())
315}
316
317/// Parses one of the recognized interval tokens (`"P5"`, `"m3"`, `"M7"`, `"TT"`)
318/// into an [`Interval`].
319///
320/// Returns [`PitchError::InvalidInterval`] for any unrecognized token.
321pub fn parse_interval(value: &str) -> Result<Interval, PitchError> {
322 match value {
323 "P5" => Ok(Interval::PERFECT_5),
324 "m3" => Ok(Interval::MINOR_3),
325 "M7" => Ok(Interval::MAJOR_7),
326 "TT" => Ok(Interval::TRITONE),
327 _ => Err(PitchError::InvalidInterval),
328 }
329}