Skip to main content

music21/key/
keysignature.rs

1use crate::{
2    defaults::{IntegerType, UnsignedIntegerType},
3    error::{Error, Result},
4    interval::Interval,
5    pitch::{Accidental, Pitch},
6    scale::{FIFTHS_ORDER_SHARP, Scale, ScaleType},
7};
8
9use super::Key;
10
11use crate::interval::constants::{
12    PERFECT_FIFTH_DOWN, PERFECT_FIFTH_UP, PERFECT_FIFTH_UP as PERFECT_FIFTH, PERFECT_FOURTH_UP,
13    PERFECT_FOURTH_UP as PERFECT_FOURTH,
14};
15
16const MODE_SHARPS_ALTER: [(&str, IntegerType); 9] = [
17    ("major", 0),
18    ("ionian", 0),
19    ("minor", -3),
20    ("aeolian", -3),
21    ("dorian", -2),
22    ("phrygian", -4),
23    ("lydian", 1),
24    ("mixolydian", -1),
25    ("locrian", -5),
26];
27
28fn canonical_mode_for_offset(offset: IntegerType) -> Option<&'static str> {
29    match offset {
30        0 => Some("ionian"),
31        -1 => Some("mixolydian"),
32        -2 => Some("dorian"),
33        -3 => Some("aeolian"),
34        -4 => Some("phrygian"),
35        -5 => Some("locrian"),
36        1 => Some("lydian"),
37        _ => None,
38    }
39}
40
41/// Returns the circle-of-fifths sharp-count offset for a mode name.
42pub fn mode_sharps_alter(mode: &str) -> Option<IntegerType> {
43    MODE_SHARPS_ALTER
44        .iter()
45        .find_map(|(name, value)| (*name == mode.to_lowercase()).then_some(*value))
46}
47
48/// The most sharps or flats a signature is read with. music21 sets no
49/// limit, but every count is a walk round the circle of fifths, and past
50/// quadruple sharps its spellings only repeat.
51const MOST_SHARPS: IntegerType = 1000;
52
53/// How many fifths a count of sharps walks, refusing one past
54/// [`MOST_SHARPS`].
55fn fifths_walked(sharps: IntegerType) -> Result<UnsignedIntegerType> {
56    let walked = sharps.unsigned_abs();
57    if walked > MOST_SHARPS.unsigned_abs() {
58        return Err(Error::Key(format!(
59            "a signature of {sharps} sharps is more than {MOST_SHARPS} either way"
60        )));
61    }
62    Ok(walked)
63}
64
65/// Returns the major-key tonic pitch for a key-signature sharp count.
66pub fn sharps_to_pitch(sharp_count: IntegerType) -> Result<Pitch> {
67    if sharp_count == 0 {
68        return Pitch::from_name("C");
69    }
70
71    let walked = fifths_walked(sharp_count)?;
72    let mut pitch = Pitch::from_name("C")?;
73    pitch.octave_setter(None);
74
75    let interval = if sharp_count > 0 {
76        &*PERFECT_FIFTH
77    } else {
78        &*PERFECT_FIFTH_DOWN
79    };
80
81    for _ in 0..walked {
82        pitch = interval.transpose_pitch(&pitch)?;
83        pitch.octave_setter(None);
84    }
85    Ok(pitch)
86}
87
88/// Returns the key-signature sharp count for a tonic pitch and optional mode.
89pub fn pitch_to_sharps(pitch_value: &Pitch, mode: Option<&str>) -> Result<IntegerType> {
90    let step_index = FIFTHS_ORDER_SHARP
91        .iter()
92        .position(|step| *step == pitch_value.step())
93        .ok_or_else(|| Error::StepName("cannot map step to circle of fifths".to_string()))?;
94
95    let mut sharps = step_index as IntegerType - 1;
96    if !pitch_value.accidental().is_twelve_tone() {
97        return Err(Error::Key(
98            "Cannot determine sharps for quarter-tone keys! silly!".to_string(),
99        ));
100    }
101    sharps += 7 * pitch_value.accidental().alter() as IntegerType;
102
103    // A mode nobody has a signature alteration for leaves the signature
104    // where the major key put it, which is what music21 does: `C
105    // hypomixolydian` is written with no sharps and no flats.
106    if let Some(offset) = mode.and_then(mode_sharps_alter) {
107        sharps += offset;
108    }
109
110    Ok(sharps)
111}
112
113/// Returns the key-signature sharp count for a tonic pitch name and optional mode.
114pub fn pitch_name_to_sharps(pitch_name: &str, mode: Option<&str>) -> Result<IntegerType> {
115    let pitch = Pitch::from_name(pitch_name)?;
116    pitch_to_sharps(&pitch, mode)
117}
118
119#[derive(Clone, Debug)]
120#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
121#[cfg_attr(feature = "serde", serde(from = "SavedKeySignature"))]
122/// A key signature represented by the number of sharps.
123///
124/// Flats are represented as negative sharps, so B-flat major has `-2`.
125/// A non-traditional signature, `E-` and `G#` together, is flagged as one
126/// and lists its pitches; it keeps a count as well, as music21's does
127/// since 14acfa0f2.
128#[must_use]
129pub struct KeySignature {
130    sharps: IntegerType,
131    /// music21's `isNonTraditional`, set on its own.
132    #[cfg_attr(feature = "serde", serde(default))]
133    non_traditional: bool,
134    /// Pitches written over the ones the count implies: music21's
135    /// `_alteredPitches`, which a traditional signature may carry too.
136    altered: Option<Vec<Pitch>>,
137    accidentals_apply_only_to_octave: bool,
138    #[cfg_attr(feature = "serde", serde(default))]
139    color: Option<String>,
140    /// A mode given the signature by hand, as music21 lets one be set on
141    /// any of its signatures, which MusicXML writes beside the count.
142    #[cfg_attr(feature = "serde", serde(default))]
143    mode: Option<String>,
144}
145
146/// A key signature as it was saved before the count was always a count:
147/// a missing count was a non-traditional signature.
148#[cfg(feature = "serde")]
149#[derive(serde::Deserialize)]
150struct SavedKeySignature {
151    sharps: Option<IntegerType>,
152    #[serde(default)]
153    non_traditional: bool,
154    altered: Option<Vec<Pitch>>,
155    accidentals_apply_only_to_octave: bool,
156    #[serde(default)]
157    color: Option<String>,
158    #[serde(default)]
159    mode: Option<String>,
160}
161
162#[cfg(feature = "serde")]
163impl From<SavedKeySignature> for KeySignature {
164    fn from(saved: SavedKeySignature) -> Self {
165        Self {
166            sharps: saved.sharps.unwrap_or(0),
167            non_traditional: saved.non_traditional || saved.sharps.is_none(),
168            altered: saved.altered,
169            accidentals_apply_only_to_octave: saved.accidentals_apply_only_to_octave,
170            color: saved.color,
171            mode: saved.mode,
172        }
173    }
174}
175
176impl PartialEq for KeySignature {
177    /// music21's `equalityAttributes`: the count and the flag.
178    fn eq(&self, other: &Self) -> bool {
179        self.sharps == other.sharps && self.non_traditional == other.non_traditional
180    }
181}
182
183impl KeySignature {
184    /// Creates a key signature from a sharp count.
185    pub fn new(sharps: IntegerType) -> Self {
186        Self {
187            sharps,
188            non_traditional: false,
189            altered: None,
190            accidentals_apply_only_to_octave: false,
191            color: None,
192            mode: None,
193        }
194    }
195
196    /// The colour the signature is drawn in, if one was said.
197    pub fn color(&self) -> Option<&str> {
198        self.color.as_deref()
199    }
200
201    /// Sets the colour the signature is drawn in.
202    pub fn set_color(&mut self, color: Option<String>) {
203        self.color = color;
204    }
205
206    /// The mode given the signature by hand, if any: music21's `mode`,
207    /// which a signature has only once it is set. A [`crate::Key`] has
208    /// its own.
209    pub fn mode(&self) -> Option<&str> {
210        self.mode.as_deref()
211    }
212
213    /// Gives the signature a mode, which does not change its count.
214    pub fn set_mode(&mut self, mode: Option<String>) {
215        self.mode = mode;
216    }
217
218    /// Creates a non-traditional key signature from the pitches it alters:
219    /// `E-` and `G#` together, say, which no count of sharps can express.
220    /// Its count is nought.
221    pub fn from_altered_pitches(pitches: Vec<Pitch>) -> Self {
222        let mut signature = Self::new(0);
223        signature.non_traditional = true;
224        signature.altered = Some(pitches);
225        signature
226    }
227
228    /// Returns the number of sharps, with flats as negative values.
229    pub fn sharps(&self) -> IntegerType {
230        self.sharps
231    }
232
233    /// Replaces the sharp count, leaving the flag and any pitches written
234    /// over it as they are, as music21's `sharps` setter does.
235    pub fn set_sharps(&mut self, sharps: IntegerType) {
236        self.sharps = sharps;
237    }
238
239    /// Writes pitches over the ones the count implies, as music21's
240    /// `alteredPitches` setter does. It does not make the signature
241    /// non-traditional; [`Self::set_non_traditional`] does that.
242    pub fn set_altered_pitches(&mut self, pitches: Vec<Pitch>) {
243        self.altered = Some(pitches);
244    }
245
246    /// Whether the signature is a list of altered pitches rather than a
247    /// count of sharps or flats: music21's `isNonTraditional`.
248    pub fn is_non_traditional(&self) -> bool {
249        self.non_traditional
250    }
251
252    /// Flags the signature non-traditional or traditional, its count and
253    /// pitches left as they are.
254    pub fn set_non_traditional(&mut self, non_traditional: bool) {
255        self.non_traditional = non_traditional;
256    }
257
258    /// Whether the altered pitches of a non-traditional signature carry
259    /// octaves that limit where they apply, as `F#4` altering only that
260    /// octave. music21 records the flag; applying it is a stream's job.
261    pub fn accidentals_apply_only_to_octave(&self) -> bool {
262        self.accidentals_apply_only_to_octave
263    }
264
265    /// Sets whether the altered pitches apply only in their own octave.
266    pub fn set_accidentals_apply_only_to_octave(&mut self, value: bool) {
267        self.accidentals_apply_only_to_octave = value;
268    }
269
270    /// The description music21 prints after `of`: `3 sharps`, `1 flat`,
271    /// `no sharps or flats`, or `pitches: [E-, G#]`.
272    pub fn description(&self) -> String {
273        if self.non_traditional {
274            let names: Vec<String> = self
275                .altered
276                .as_deref()
277                .unwrap_or_default()
278                .iter()
279                .map(Pitch::to_string)
280                .collect();
281            return format!("pitches: [{}]", names.join(", "));
282        }
283        match self.sharps {
284            0 => "no sharps or flats".to_string(),
285            1 => "1 sharp".to_string(),
286            -1 => "1 flat".to_string(),
287            n if n > 1 => format!("{n} sharps"),
288            n => format!("{} flats", -n),
289        }
290    }
291
292    /// Returns the pitches this signature alters, in circle-of-fifths order
293    /// and without octaves: `F# C# G#` for three sharps, `B- E- A-` for three
294    /// flats; a non-traditional signature answers the pitches it was given.
295    pub fn altered_pitches(&self) -> Result<Vec<Pitch>> {
296        if let Some(altered) = &self.altered {
297            return Ok(altered.clone());
298        }
299        if self.non_traditional {
300            return Ok(Vec::new());
301        }
302        let sharps = self.sharps;
303        let (start, interval) = if sharps > 0 {
304            ("B", &*PERFECT_FIFTH)
305        } else {
306            ("F", &*PERFECT_FOURTH)
307        };
308        let walked = fifths_walked(sharps)?;
309        let mut current = Pitch::from_name(start)?;
310        let mut altered = Vec::with_capacity(walked as usize);
311        for _ in 0..walked {
312            current = interval.transpose_pitch(&current)?;
313            current.octave_setter(None);
314            altered.push(current.clone());
315        }
316        Ok(altered)
317    }
318
319    /// Returns the accidental this signature puts on a step letter, if any.
320    pub fn accidental_by_step(&self, step: char) -> Result<Option<Accidental>> {
321        let step = crate::stepname::StepName::try_from(step)?;
322        Ok(self
323            .altered_pitches()?
324            .into_iter()
325            .rev()
326            .find(|pitch| pitch.step() == step)
327            .and_then(|pitch| pitch.written_accidental().cloned()))
328    }
329
330    /// Returns the signature of the major key this one's major tonic moves
331    /// to by the interval, drawn in the colour this one is.
332    pub fn transpose(&self, interval: &Interval) -> Result<Self> {
333        let tonic = self.try_as_key(Some("major"), None)?.tonic();
334        let mut transposed = interval.transpose_pitch(&tonic)?;
335        if interval.implicit_diatonic && pitch_to_sharps(&transposed, None)?.abs() > 6 {
336            transposed = transposed.get_enharmonic()?;
337        }
338        // music21 transposes the object, so only the count moves: its colour,
339        // its flag and any pitches written over it stay.
340        let mut moved = self.clone();
341        moved.sharps = pitch_to_sharps(&transposed, None)?;
342        Ok(moved)
343    }
344
345    /// Transposes a pitch spelled in C into this key signature the way
346    /// music21's `transposePitchFromC` does: up a fifth per sharp, or up a
347    /// fourth per flat, keeping the pitch's own octave, so `E4` in two sharps
348    /// is `F#4` and in three flats `G4`.
349    pub fn transpose_pitch_from_c(&self, pitch: &Pitch) -> Result<Pitch> {
350        let sharps = self.sharps;
351        if sharps == 0 {
352            return Ok(pitch.clone());
353        }
354        let step = if sharps < 0 {
355            &*PERFECT_FOURTH_UP
356        } else {
357            &*PERFECT_FIFTH_UP
358        };
359        let walked = fifths_walked(sharps)?;
360        let mut transposed = pitch.clone();
361        for _ in 0..walked {
362            transposed = step.transpose_pitch_with_options(&transposed, false, None)?;
363        }
364        transposed.octave_setter(pitch.octave());
365        Ok(transposed)
366    }
367
368    /// Returns the major or minor scale this signature implies.
369    pub fn scale(&self, mode: &str) -> Result<Scale> {
370        let scale_type = match mode {
371            "major" => ScaleType::Major,
372            "minor" => ScaleType::Minor,
373            other => {
374                return Err(Error::Key(format!(
375                    "no mapping to a scale exists for this mode yet: {other}"
376                )));
377            }
378        };
379        Ok(Scale::new(
380            scale_type,
381            self.try_as_key(Some(mode), None)?.tonic(),
382        ))
383    }
384
385    /// Converts this signature to a key in the given mode.
386    pub fn as_key(&self, mode: &str) -> Key {
387        self.try_as_key(Some(mode), None).unwrap_or_else(|_| {
388            Key::new(Pitch::from_name("C").expect("C is valid pitch"), "major", 0)
389        })
390    }
391
392    /// Converts this signature to a key, optionally inferring mode from tonic.
393    pub fn try_as_key(&self, mode: Option<&str>, tonic: Option<&str>) -> Result<Key> {
394        let our_sharps = self.sharps;
395
396        let resolved_mode = if mode.is_none() && tonic.is_none() {
397            "major".to_string()
398        } else if mode.is_none() && tonic.is_some() {
399            let tonic_name = tonic.expect("checked is_some above");
400            let major_sharps = pitch_name_to_sharps(tonic_name, None)?;
401            canonical_mode_for_offset(our_sharps.saturating_sub(major_sharps))
402                .ok_or_else(|| {
403                    Error::Key(format!(
404                        "Could not solve for mode from sharps={our_sharps}, tonic={tonic_name}"
405                    ))
406                })?
407                .to_string()
408        } else {
409            mode.expect("checked is_some above").to_lowercase()
410        };
411
412        let sharp_alteration_from_major = mode_sharps_alter(&resolved_mode)
413            .ok_or_else(|| Error::Key(format!("Mode {resolved_mode} is unknown")))?;
414
415        let tonic_pitch = sharps_to_pitch(our_sharps.saturating_sub(sharp_alteration_from_major))?;
416        Ok(Key::new(tonic_pitch, &resolved_mode, our_sharps))
417    }
418}
419
420impl std::fmt::Display for KeySignature {
421    /// `KeySignature of 3 sharps`, `KeySignature of pitches: [E-, G#]`.
422    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
423        write!(f, "KeySignature of {}", self.description())
424    }
425}
426
427#[cfg(test)]
428mod non_traditional_tests {
429    use super::*;
430
431    /// The flag turns on and off again and the count stays through both.
432    #[test]
433    fn a_signature_can_be_made_non_traditional_and_back() {
434        let mut signature = KeySignature::new(3);
435        assert!(!signature.is_non_traditional());
436
437        signature.set_non_traditional(true);
438        assert!(signature.is_non_traditional());
439        assert_eq!(signature.sharps(), 3);
440
441        signature.set_non_traditional(false);
442        assert!(!signature.is_non_traditional());
443        assert_eq!(signature.sharps(), 3);
444    }
445
446    fn pitches(names: &[&str]) -> Vec<Pitch> {
447        names
448            .iter()
449            .map(|name| Pitch::from_name(*name).unwrap())
450            .collect()
451    }
452
453    /// music21 14acfa0f2: `sharps` is always a count, and `isNonTraditional`
454    /// is a flag of its own.
455    #[test]
456    fn a_pitch_list_makes_a_non_traditional_signature() {
457        let unusual = KeySignature::from_altered_pitches(pitches(&["Eb", "G#"]));
458        assert!(unusual.is_non_traditional());
459        assert_eq!(unusual.sharps(), 0);
460        assert_eq!(unusual.to_string(), "KeySignature of pitches: [Eb, G#]");
461        assert_eq!(
462            unusual.accidental_by_step('G').unwrap().unwrap().name(),
463            "sharp"
464        );
465        assert_eq!(unusual.accidental_by_step('A').unwrap(), None);
466        // Its count still names a key and still transposes.
467        assert_eq!(
468            unusual
469                .try_as_key(Some("major"), None)
470                .unwrap()
471                .tonic()
472                .name(),
473            "C"
474        );
475        assert_eq!(
476            unusual
477                .transpose_pitch_from_c(&Pitch::from_name("C4").unwrap())
478                .unwrap()
479                .name_with_octave(),
480            "C4"
481        );
482    }
483
484    /// Each of the three is set on its own, as music21's attributes are.
485    #[test]
486    fn sharps_flag_and_pitches_are_set_apart() {
487        // Pitches written over a traditional signature leave it traditional.
488        let mut signature = KeySignature::new(2);
489        signature.set_altered_pitches(pitches(&["Eb"]));
490        assert!(!signature.is_non_traditional());
491        assert_eq!(signature.sharps(), 2);
492        assert_eq!(signature.to_string(), "KeySignature of 2 sharps");
493        assert_eq!(signature.altered_pitches().unwrap(), pitches(&["Eb"]));
494        signature.set_sharps(3);
495        assert_eq!(signature.altered_pitches().unwrap(), pitches(&["Eb"]));
496
497        // The flag keeps the count; the count keeps the flag.
498        let mut flagged = KeySignature::new(2);
499        flagged.set_non_traditional(true);
500        assert_eq!(flagged.sharps(), 2);
501        assert_eq!(flagged.to_string(), "KeySignature of pitches: []");
502        assert_eq!(flagged.try_as_key(None, None).unwrap().tonic().name(), "D");
503        flagged.set_sharps(3);
504        assert!(flagged.is_non_traditional());
505        flagged.set_non_traditional(false);
506        assert_eq!(flagged.to_string(), "KeySignature of 3 sharps");
507
508        assert!(!signature.accidentals_apply_only_to_octave());
509        signature.set_accidentals_apply_only_to_octave(true);
510        assert!(signature.accidentals_apply_only_to_octave());
511        assert_eq!(
512            KeySignature::new(0).to_string(),
513            "KeySignature of no sharps or flats"
514        );
515        assert_eq!(KeySignature::new(-4).description(), "4 flats");
516    }
517
518    /// A transposed signature keeps its flag and its pitches; only the count
519    /// moves.
520    #[test]
521    fn transposing_moves_only_the_count() {
522        let mut unusual = KeySignature::new(2);
523        unusual.set_non_traditional(true);
524        unusual.set_altered_pitches(pitches(&["B-", "F#"]));
525        let moved = unusual
526            .transpose(&Interval::from_name("M2").unwrap())
527            .unwrap();
528        assert_eq!(moved.sharps(), 4);
529        assert!(moved.is_non_traditional());
530        assert_eq!(moved.altered_pitches().unwrap(), pitches(&["B-", "F#"]));
531    }
532
533    /// A non-traditional signature is not the C-major one it shares a count
534    /// with.
535    #[test]
536    fn the_flag_counts_in_equality() {
537        let mut flagged = KeySignature::new(2);
538        flagged.set_non_traditional(true);
539        assert_ne!(flagged, KeySignature::new(2));
540        assert_eq!(KeySignature::new(2), KeySignature::new(2));
541    }
542
543    #[test]
544    fn traditional_altered_pitches_carry_explicit_accidentals() {
545        let three_sharps = KeySignature::new(3);
546        let altered = three_sharps.altered_pitches().unwrap();
547        assert!(
548            altered
549                .iter()
550                .all(|pitch| pitch.written_accidental().is_some())
551        );
552        assert_eq!(
553            three_sharps
554                .accidental_by_step('F')
555                .unwrap()
556                .unwrap()
557                .name(),
558            "sharp"
559        );
560    }
561}
562
563#[cfg(test)]
564mod tests {
565
566    #[test]
567    fn a_signature_names_a_key_in_a_mode_or_from_a_tonic() {
568        let two_sharps = KeySignature::new(2);
569        assert_eq!(two_sharps.as_key("major").tonic().name(), "D");
570        assert_eq!(two_sharps.as_key("minor").tonic().name(), "B");
571        let from_tonic = two_sharps.try_as_key(None, Some("b")).unwrap();
572        assert_eq!(
573            (from_tonic.tonic().name(), from_tonic.mode()),
574            ("B".to_string(), "aeolian")
575        );
576        assert_eq!(
577            two_sharps.try_as_key(None, None).unwrap().tonic().name(),
578            "D"
579        );
580        // A mode given beside a tonic wins, and the tonic is not consulted.
581        assert_eq!(
582            two_sharps
583                .try_as_key(Some("major"), Some("C"))
584                .unwrap()
585                .tonic()
586                .name(),
587            "D"
588        );
589        let altered = KeySignature::from_altered_pitches(vec![Pitch::from_name("F#").unwrap()]);
590        assert_eq!(altered.as_key("major").tonic().name(), "C");
591        assert_eq!(
592            pitch_to_sharps(&Pitch::from_name("D").unwrap(), Some("major")).unwrap(),
593            2
594        );
595        assert_eq!(
596            pitch_to_sharps(&Pitch::from_name("D").unwrap(), Some("minor")).unwrap(),
597            -1
598        );
599        // A mode with no signature alteration leaves the major key's count.
600        assert_eq!(
601            pitch_to_sharps(&Pitch::from_name("D").unwrap(), Some("nonsense")).unwrap(),
602            2
603        );
604    }
605
606    #[test]
607    fn transpose_pitch_from_c_matches_music21() {
608        let cases: [(i32, [&str; 5]); 7] = [
609            (0, ["C4", "E4", "Bb3", "F#5", "G"]),
610            (1, ["G4", "B4", "F3", "C#5", "D"]),
611            (2, ["D4", "F#4", "C3", "G#5", "A"]),
612            (-1, ["F4", "A4", "Eb3", "B5", "C"]),
613            (-3, ["Eb4", "G4", "Db3", "A5", "Bb"]),
614            (7, ["C#4", "E#4", "B3", "F##5", "G#"]),
615            (-7, ["Cb4", "Eb4", "Bbb3", "F5", "Gb"]),
616        ];
617        for (sharps, expected) in cases {
618            let signature = KeySignature::new(sharps);
619            let actual = ["C4", "E4", "Bb3", "F#5", "G"].map(|name| {
620                signature
621                    .transpose_pitch_from_c(&Pitch::from_name(name).unwrap())
622                    .unwrap()
623                    .name_with_octave()
624            });
625            assert_eq!(actual, expected, "{sharps} sharps");
626        }
627    }
628    use super::*;
629
630    #[test]
631    fn altered_pitches_and_transpositions_match_music21() {
632        type Row = (
633            i32,
634            &'static [&'static str],
635            [Option<&'static str>; 3],
636            [i32; 3],
637            &'static str,
638            &'static str,
639        );
640        let cases: [Row; 15] = [
641            (
642                -7,
643                &["Bb", "Eb", "Ab", "Db", "Gb", "Cb", "Fb"],
644                [Some("flat"), Some("flat"), Some("flat")],
645                [-6, -8, -12],
646                "Cb",
647                "Ab",
648            ),
649            (
650                -6,
651                &["Bb", "Eb", "Ab", "Db", "Gb", "Cb"],
652                [None, Some("flat"), Some("flat")],
653                [-5, -7, -11],
654                "Gb",
655                "Eb",
656            ),
657            (
658                -5,
659                &["Bb", "Eb", "Ab", "Db", "Gb"],
660                [None, Some("flat"), None],
661                [-4, -6, -10],
662                "Db",
663                "Bb",
664            ),
665            (
666                -4,
667                &["Bb", "Eb", "Ab", "Db"],
668                [None, Some("flat"), None],
669                [-3, -5, -9],
670                "Ab",
671                "F",
672            ),
673            (
674                -3,
675                &["Bb", "Eb", "Ab"],
676                [None, Some("flat"), None],
677                [-2, -4, -8],
678                "Eb",
679                "C",
680            ),
681            (
682                -2,
683                &["Bb", "Eb"],
684                [None, Some("flat"), None],
685                [-1, -3, -7],
686                "Bb",
687                "G",
688            ),
689            (
690                -1,
691                &["Bb"],
692                [None, Some("flat"), None],
693                [0, -2, -6],
694                "F",
695                "D",
696            ),
697            (0, &[], [None, None, None], [1, -1, -5], "C", "A"),
698            (
699                1,
700                &["F#"],
701                [Some("sharp"), None, None],
702                [2, 0, -4],
703                "G",
704                "E",
705            ),
706            (
707                2,
708                &["F#", "C#"],
709                [Some("sharp"), None, Some("sharp")],
710                [3, 1, -3],
711                "D",
712                "B",
713            ),
714            (
715                3,
716                &["F#", "C#", "G#"],
717                [Some("sharp"), None, Some("sharp")],
718                [4, 2, -2],
719                "A",
720                "F#",
721            ),
722            (
723                4,
724                &["F#", "C#", "G#", "D#"],
725                [Some("sharp"), None, Some("sharp")],
726                [5, 3, -1],
727                "E",
728                "C#",
729            ),
730            (
731                5,
732                &["F#", "C#", "G#", "D#", "A#"],
733                [Some("sharp"), None, Some("sharp")],
734                [6, 4, 0],
735                "B",
736                "G#",
737            ),
738            (
739                6,
740                &["F#", "C#", "G#", "D#", "A#", "E#"],
741                [Some("sharp"), None, Some("sharp")],
742                [7, 5, 1],
743                "F#",
744                "D#",
745            ),
746            (
747                7,
748                &["F#", "C#", "G#", "D#", "A#", "E#", "B#"],
749                [Some("sharp"), Some("sharp"), Some("sharp")],
750                [8, 6, 2],
751                "C#",
752                "A#",
753            ),
754        ];
755        for (sharps, altered, by_step, transposed, major, minor) in cases {
756            let signature = KeySignature::new(sharps);
757            let names = signature
758                .altered_pitches()
759                .unwrap()
760                .iter()
761                .map(Pitch::name)
762                .collect::<Vec<_>>();
763            assert_eq!(names, altered, "{sharps} altered");
764            for (step, expected) in ['F', 'B', 'C'].into_iter().zip(by_step) {
765                let accidental = signature.accidental_by_step(step).unwrap();
766                assert_eq!(
767                    accidental.as_ref().map(Accidental::name),
768                    expected,
769                    "{sharps} {step}"
770                );
771            }
772            for (name, expected) in ["P5", "-P5", "m2"].into_iter().zip(transposed) {
773                let moved = signature
774                    .transpose(&Interval::from_name(name).unwrap())
775                    .unwrap();
776                assert_eq!(moved.sharps(), expected, "{sharps} by {name}");
777            }
778            assert_eq!(signature.scale("major").unwrap().tonic().name(), major);
779            assert_eq!(signature.scale("minor").unwrap().tonic().name(), minor);
780        }
781        assert!(KeySignature::new(0).scale("dorian").is_err());
782        assert!(KeySignature::new(0).accidental_by_step('H').is_err());
783    }
784    #[test]
785    fn keysignature_as_key_major_minor() {
786        let ks = KeySignature::new(2);
787        assert_eq!(ks.as_key("major").tonic().name(), "D");
788        assert_eq!(ks.as_key("minor").tonic().name(), "B");
789    }
790
791    #[test]
792    fn keysignature_mode_inference_from_tonic() {
793        let ks = KeySignature::new(0);
794        let key = ks.try_as_key(None, Some("D")).unwrap();
795        assert_eq!(key.mode(), "dorian");
796        assert_eq!(key.tonic().name(), "D");
797    }
798
799    #[test]
800    fn sharps_to_pitch_roundtrip() {
801        let f_sharp = sharps_to_pitch(6).unwrap();
802        assert_eq!(f_sharp.name(), "F#");
803        let b_flat = sharps_to_pitch(-2).unwrap();
804        assert_eq!(b_flat.name(), "Bb");
805        assert_eq!(sharps_to_pitch(-7).unwrap().name(), "Cb");
806        assert_eq!(sharps_to_pitch(7).unwrap().name(), "C#");
807        assert_eq!(KeySignature::new(-7).as_key("major").tonic().name(), "Cb");
808    }
809
810    #[test]
811    fn a_count_of_sharps_past_the_limit_is_refused() {
812        for sharps in [MOST_SHARPS + 1, IntegerType::MAX, IntegerType::MIN] {
813            let signature = KeySignature::new(sharps);
814            assert!(sharps_to_pitch(sharps).is_err(), "{sharps}");
815            assert!(signature.altered_pitches().is_err(), "{sharps}");
816            assert!(
817                signature.try_as_key(Some("minor"), None).is_err(),
818                "{sharps}"
819            );
820            let c = Pitch::from_name("C4").unwrap();
821            assert!(signature.transpose_pitch_from_c(&c).is_err(), "{sharps}");
822        }
823        assert!(sharps_to_pitch(MOST_SHARPS).is_ok());
824    }
825}