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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
use std::fmt;
use std::ops::{Add, Sub};
use std::str::FromStr;

use crate::{Interval, PitchClass, Semitones, StaffPosition};

/// Custom error for strings that cannot be parsed into notes.
#[derive(Debug)]
pub struct ParseNoteError {
    name: String,
}

impl fmt::Display for ParseNoteError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Could not parse note name \"{}\"", self.name)
    }
}

/// A note such a C, C# and so on.
#[derive(Debug, Clone, Copy, Eq, PartialOrd, Ord)]
pub struct Note {
    pub pitch_class: PitchClass,
    staff_position: StaffPosition,
}

impl Note {
    pub fn new(pitch_class: PitchClass, staff_position: StaffPosition) -> Self {
        Self {
            pitch_class,
            staff_position,
        }
    }

    /// Return `true` if this note is a "white note", i.e. a note represented
    /// by a white key on the piano (i.e. the note is part of the C major scale).
    pub fn is_white_note(&self) -> bool {
        use PitchClass::*;

        matches!(self.pitch_class, C | D | E | F | G | A | B)
    }
}

impl PartialEq for Note {
    /// Treat two notes as equal if they have the same pitch class.
    /// For example, `B sharp`, `C` and `D double flat` should all match.
    fn eq(&self, other: &Self) -> bool {
        self.pitch_class == other.pitch_class
    }
}

impl fmt::Display for Note {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use PitchClass::*;
        use StaffPosition::*;

        let s = match (self.staff_position, self.pitch_class) {
            // Notes on staff position for C.
            (CPos, ASharp) => "Bb", // C double flat
            (CPos, B) => "B",       // Cb
            (CPos, C) => "C",
            (CPos, CSharp) => "C#",
            (CPos, D) => "D", // C double sharp
            // Notes on staff position for D.
            (DPos, C) => "C", // D double flat
            (DPos, CSharp) => "Db",
            (DPos, D) => "D",
            (DPos, DSharp) => "D#",
            (DPos, E) => "E", // D double sharp
            // Notes on staff position for E.
            (EPos, D) => "D", // E double flat
            (EPos, DSharp) => "Eb",
            (EPos, E) => "E",
            (EPos, F) => "F",       // E#
            (EPos, FSharp) => "F#", // E double sharp
            // Notes on staff position for F.
            (FPos, DSharp) => "Eb", // F double flat
            (FPos, E) => "E",       // Fb
            (FPos, F) => "F",
            (FPos, FSharp) => "F#",
            (FPos, G) => "G", // F double sharp
            // Notes on staff position for G.
            (GPos, F) => "F", // G double flat
            (GPos, FSharp) => "Gb",
            (GPos, G) => "G",
            (GPos, GSharp) => "G#",
            (GPos, A) => "A", // G double sharp
            // Notes on staff position for A.
            (APos, G) => "G", // A double flat
            (APos, GSharp) => "Ab",
            (APos, A) => "A",
            (APos, ASharp) => "A#",
            (APos, B) => "B", // A double sharp
            // Notes on staff position for B.
            (BPos, A) => "A", // B double flat
            (BPos, ASharp) => "Bb",
            (BPos, B) => "B",
            (BPos, C) => "C",       // B#
            (BPos, CSharp) => "C#", // B double sharp
            _ => panic!("Impossible combination of PitchClass and StaffPosition"),
        };

        write!(f, "{}", s)
    }
}

impl FromStr for Note {
    type Err = ParseNoteError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        use PitchClass::*;
        use StaffPosition::*;

        let name = s.to_string();

        let (pitch_class, staff_position) = match s {
            "C" => (C, CPos),
            "C#" => (CSharp, CPos),
            "Db" => (CSharp, DPos),
            "D" => (D, DPos),
            "D#" => (DSharp, DPos),
            "Eb" => (DSharp, EPos),
            "E" => (E, EPos),
            "F" => (F, FPos),
            "F#" => (FSharp, FPos),
            "Gb" => (FSharp, GPos),
            "G" => (G, GPos),
            "G#" => (GSharp, GPos),
            "Ab" => (GSharp, APos),
            "A" => (A, APos),
            "A#" => (ASharp, APos),
            "Bb" => (ASharp, BPos),
            "B" => (B, BPos),
            _ => return Err(ParseNoteError { name }),
        };

        Ok(Self::new(pitch_class, staff_position))
    }
}

impl From<PitchClass> for Note {
    /// Convert a pitch class into a note.
    /// For notes that can be sharp or flat use the sharp version.
    fn from(pitch_class: PitchClass) -> Self {
        use PitchClass::*;
        use StaffPosition::*;

        let staff_position = match pitch_class {
            C | CSharp => CPos,
            D | DSharp => DPos,
            E => EPos,
            F | FSharp => FPos,
            G | GSharp => GPos,
            A | ASharp => APos,
            B => BPos,
        };

        Self::new(pitch_class, staff_position)
    }
}

impl Add<Interval> for Note {
    type Output = Self;

    /// Get the next note when adding `interval` to the current note.
    fn add(self, interval: Interval) -> Self {
        let pitch_class = self.pitch_class + interval.to_semitones();
        let staff_position = self.staff_position + (interval.to_number() - 1);
        Self::new(pitch_class, staff_position)
    }
}

impl Add<Semitones> for Note {
    type Output = Self;

    fn add(self, n: Semitones) -> Self {
        let note = Self::from(self.pitch_class + n);

        // Make sure the staff position stays the same if the pitch class
        // stays the same (e.g. when adding 0 or 12 semitones).
        if note.pitch_class == self.pitch_class {
            return Self::new(self.pitch_class, self.staff_position);
        }

        // Otherwise, the staff position will by default be chosen so that
        // sharp/flat notes turn out sharp (e.g. C + 1 = C#).
        note
    }
}

impl Sub<Semitones> for Note {
    type Output = Self;

    fn sub(self, n: Semitones) -> Self {
        let note = Self::from(self.pitch_class - n);

        // Make sure the staff position stays the same if the pitch class
        // stays the same (e.g. when subtracting 0 or 12 semitones).
        if note.pitch_class == self.pitch_class {
            return Self::new(self.pitch_class, self.staff_position);
        }

        // Otherwise, make sure that the staff position will be chosen so that
        // sharp/flat notes turn out flat (e.g. D - 1 = Db).
        let staff_position = match note {
            n if n.is_white_note() => note.staff_position,
            _ => note.staff_position + 1,
        };

        Self::new(note.pitch_class, staff_position)
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;
    use Interval::*;
    use PitchClass::*;

    use super::*;

    #[rstest(
        s,
        case("C"),
        case("C#"),
        case("Db"),
        case("D"),
        case("D#"),
        case("Eb"),
        case("E"),
        case("F"),
        case("F#"),
        case("Gb"),
        case("G"),
        case("G#"),
        case("Ab"),
        case("A"),
        case("A#"),
        case("Bb"),
        case("B")
    )]
    fn test_from_and_to_str(s: &str) {
        let note = Note::from_str(s).unwrap();
        assert_eq!(format!("{}", note), s);
    }

    #[rstest(
        note,
        is_white_note,
        case("C", true),
        case("C#", false),
        case("Db", false),
        case("D", true),
        case("D#", false),
        case("Eb", false),
        case("E", true),
        case("F", true),
        case("F#", false),
        case("Gb", false),
        case("G", true),
        case("G#", false),
        case("Ab", false),
        case("A", true),
        case("A#", false),
        case("Bb", false),
        case("B", true)
    )]
    fn test_is_white_note(note: Note, is_white_note: bool) {
        assert_eq!(note.is_white_note(), is_white_note);
    }

    #[rstest(
        pitch_class,
        note,
        case(C, "C"),
        case(CSharp, "C#"),
        case(D, "D"),
        case(DSharp, "D#"),
        case(E, "E"),
        case(F, "F"),
        case(FSharp, "F#"),
        case(G, "G"),
        case(GSharp, "G#"),
        case(A, "A"),
        case(ASharp, "A#"),
        case(B, "B")
    )]
    fn test_from_pitch_class(pitch_class: PitchClass, note: Note) {
        assert_eq!(Note::from(pitch_class), note);
    }

    #[rstest(
        note1,
        interval,
        note2,
        case("C", PerfectUnison, "C"),
        case("C", MinorThird, "Eb"),
        case("C", MajorThird, "E"),
        case("C", PerfectFifth, "G"),
        case("C#", PerfectUnison, "C#"),
        case("C#", MajorThird, "F")
    )]
    fn test_add_interval(note1: Note, interval: Interval, note2: Note) {
        assert_eq!(note1 + interval, note2);
    }

    #[rstest(
        note1,
        n,
        note2,
        case("C", 0, "C"),
        case("C#", 0, "C#"),
        case("Db", 0, "Db"),
        case("C", 1, "C#"),
        case("C#", 1, "D"),
        case("Db", 1, "D"),
        case("C", 3, "D#"),
        case("C", 4, "E"),
        case("C", 7, "G"),
        case("A", 3, "C"),
        case("A", 12, "A"),
        case("A#", 12, "A#"),
        case("Ab", 12, "Ab")
    )]
    fn test_add_semitones(note1: Note, n: Semitones, note2: Note) {
        assert_eq!(note1 + n, note2);
    }

    #[rstest(
        note1,
        n,
        note2,
        case("C", 0, "C"),
        case("C#", 0, "C#"),
        case("Db", 0, "Db"),
        case("C", 1, "B"),
        case("C", 2, "Bb"),
        case("C#", 3, "Bb"),
        case("Db", 3, "Bb"),
        case("A", 3, "Gb"),
        case("A", 12, "A")
    )]
    fn test_subtract_semitones(note1: Note, n: Semitones, note2: Note) {
        assert_eq!(note1 - n, note2);
    }
}