Skip to main content

music21/common/
numbertools.rs

1//! music21's `common.numberTools`: quarter lengths kept exact, numbers
2//! rounded and written the way music21 writes them, Roman numerals and
3//! ordinals.
4
5use std::convert::TryFrom;
6use std::fmt::{self, Display};
7use std::ops::Range;
8use std::sync::LazyLock;
9
10use num::bigint::BigInt;
11use num::rational::BigRational;
12use num::{FromPrimitive, Integer, One, Signed, ToPrimitive, Zero};
13use num_traits::Float;
14
15use crate::defaults::{FloatType, UnsignedIntegerType};
16use crate::error::{Error, Result};
17
18macro_rules! define_ordinals {
19    (
20        $(#[$meta:meta])*
21        $vis:vis enum $name:ident {
22            $($variant:ident => ($display:expr, $lower:expr)),* $(,)?
23        }
24    ) => {
25        $(#[$meta])*
26        #[derive(Debug, Copy, Clone, PartialEq, Eq)]
27        #[repr(u8)]
28        $vis enum $name {
29            $($variant),*
30        }
31
32        impl TryFrom<UnsignedIntegerType> for $name {
33            type Error = crate::error::Error;
34            fn try_from(value: UnsignedIntegerType) -> Result<Self, Self::Error> {
35                const VARIANTS: &[$name] = &[$($name::$variant),*];
36                let idx = value as usize;
37                if idx < VARIANTS.len() {
38                    Ok(VARIANTS[idx])
39                } else {
40                    Err(Error::Ordinal(format!(
41                        "Invalid {} value: {}",
42                        stringify!($name),
43                        value
44                    )))
45                }
46            }
47        }
48
49        impl TryFrom<&str> for $name {
50            type Error = crate::error::Error;
51            fn try_from(value: &str) -> Result<Self, Self::Error> {
52                match value.to_lowercase().as_str() {
53                    $(
54                        $lower => Ok($name::$variant),
55                    )*
56                    _ => Err(Error::Ordinal(format!(
57                        "Invalid {} string: {}",
58                        stringify!($name),
59                        value
60                    ))),
61                }
62            }
63        }
64
65        impl Display for $name {
66            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67                let s = match self {
68                    $(
69                        $name::$variant => $display,
70                    )*
71                };
72                write!(f, "{}", s)
73            }
74        }
75    };
76}
77
78// Define the musical ordinals (override a few names)
79define_ordinals! {
80    pub(crate) enum MusicOrdinals {
81        Zeroth      => ("Zeroth", "zeroth"),
82        Unison      => ("Unison", "unison"),          // instead of First
83        Second      => ("Second", "second"),
84        Third       => ("Third", "third"),
85        Fourth      => ("Fourth", "fourth"),
86        Fifth       => ("Fifth", "fifth"),
87        Sixth       => ("Sixth", "sixth"),
88        Seventh     => ("Seventh", "seventh"),
89        Octave      => ("Octave", "octave"),           // instead of Eighth
90        Ninth       => ("Ninth", "ninth"),
91        Tenth       => ("Tenth", "tenth"),
92        Eleventh    => ("Eleventh", "eleventh"),
93        Twelfth     => ("Twelfth", "twelfth"),
94        Thirteenth  => ("Thirteenth", "thirteenth"),
95        Fourteenth  => ("Fourteenth", "fourteenth"),
96        DoubleOctave=> ("Double-octave", "double-octave"), // instead of Fifteenth
97        Sixteenth   => ("Sixteenth", "sixteenth"),
98        Seventeenth => ("Seventeenth", "seventeenth"),
99        Eighteenth  => ("Eighteenth", "eighteenth"),
100        Nineteenth  => ("Nineteenth", "nineteenth"),
101        Twentieth   => ("Twentieth", "twentieth"),
102        TwentyFirst => ("Twenty-first", "twenty-first"),
103        TripleOctave=> ("Triple-octave", "triple-octave"), // instead of Twenty-second
104    }
105}
106
107/// music21's plain `ordinals` list, as far as any chord inversion can reach.
108pub(crate) const ORDINALS: [&str; 8] = [
109    "Zeroth", "First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh",
110];
111
112pub(crate) static MUSICAL_ORDINAL_STRINGS: LazyLock<[String; 23]> = LazyLock::new(|| {
113    std::array::from_fn(|i| {
114        let val: UnsignedIntegerType = i as UnsignedIntegerType;
115        let ordinal = MusicOrdinals::try_from(val).unwrap();
116        format!("{ordinal}")
117    })
118});
119
120/// The same names lowered, for the case-insensitive search an interval name
121/// does over all twenty-three of them.
122pub(crate) static MUSICAL_ORDINAL_STRINGS_LOWER: LazyLock<[String; 23]> =
123    LazyLock::new(|| std::array::from_fn(|i| MUSICAL_ORDINAL_STRINGS[i].to_ascii_lowercase()));
124
125/// music21's `defaults.limitOffsetDenominator`: the largest denominator
126/// [`op_frac`] keeps a quarter length as a fraction over.
127pub const DENOM_LIMIT: u64 = 65535;
128
129/// music21's `ordinals`: the names of the numbers from nought to
130/// twenty-two, in English.
131pub const ORDINAL_NAMES: [&str; 23] = [
132    "Zeroth",
133    "First",
134    "Second",
135    "Third",
136    "Fourth",
137    "Fifth",
138    "Sixth",
139    "Seventh",
140    "Eighth",
141    "Ninth",
142    "Tenth",
143    "Eleventh",
144    "Twelfth",
145    "Thirteenth",
146    "Fourteenth",
147    "Fifteenth",
148    "Sixteenth",
149    "Seventeenth",
150    "Eighteenth",
151    "Nineteenth",
152    "Twentieth",
153    "Twenty-first",
154    "Twenty-second",
155];
156
157/// music21's `musicOrdinals`: [`ORDINAL_NAMES`] with an interval's own
158/// names for the first, the eighth, the fifteenth and the twenty-second.
159pub const MUSIC_ORDINAL_NAMES: [&str; 23] = [
160    "Zeroth",
161    "Unison",
162    "Second",
163    "Third",
164    "Fourth",
165    "Fifth",
166    "Sixth",
167    "Seventh",
168    "Octave",
169    "Ninth",
170    "Tenth",
171    "Eleventh",
172    "Twelfth",
173    "Thirteenth",
174    "Fourteenth",
175    "Double-octave",
176    "Sixteenth",
177    "Seventeenth",
178    "Eighteenth",
179    "Nineteenth",
180    "Twentieth",
181    "Twenty-first",
182    "Triple-octave",
183];
184
185/// A quarter length or an offset as music21 keeps one: a float where a
186/// float says it exactly, a fraction where none does.
187#[derive(Clone, Copy, Debug, PartialEq)]
188#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
189pub enum OffsetQL {
190    /// A value a float holds exactly.
191    Float(FloatType),
192    /// A value in lowest terms whose denominator is not a power of two.
193    Fraction {
194        /// The numerator, which carries the sign.
195        numerator: i64,
196        /// The denominator, always positive.
197        denominator: i64,
198    },
199}
200
201impl OffsetQL {
202    /// The value as the nearest float.
203    pub fn to_f64(self) -> FloatType {
204        match self {
205            Self::Float(value) => value,
206            Self::Fraction {
207                numerator,
208                denominator,
209            } => numerator as FloatType / denominator as FloatType,
210        }
211    }
212}
213
214/// A whole number or a float, which is what music21's `numToIntOrFloat`
215/// and `roundToHalfInteger` give back.
216#[derive(Clone, Debug, PartialEq)]
217pub enum IntOrFloat {
218    /// A whole number, of any size.
219    Int(BigInt),
220    /// Anything else.
221    Float(FloatType),
222}
223
224/// Python's `math.isclose(a, b, abs_tol=abs_tol)`, with its relative
225/// tolerance of one in a billion.
226///
227/// ```
228/// use music21::common::numbertools::is_close;
229///
230/// assert!(is_close(0.1 + 0.2, 0.3, 0.0));
231/// assert!(!is_close(1.0, 1.1, 0.01));
232/// ```
233pub fn is_close(a: FloatType, b: FloatType, abs_tol: FloatType) -> bool {
234    if a == b {
235        return true;
236    }
237    if a.is_infinite() || b.is_infinite() {
238        return false;
239    }
240    let difference = (b - a).abs();
241    difference <= (1e-9 * b).abs() || difference <= (1e-9 * a).abs() || difference <= abs_tol
242}
243
244/// A float written as Python's `repr` writes it: the shortest digits that
245/// read back as the same float, `1.0` for a whole number, and an exponent
246/// below a ten-thousandth or from 1e16 up.
247///
248/// ```
249/// use music21::common::numbertools::float_repr;
250///
251/// assert_eq!(float_repr(1.0), "1.0");
252/// assert_eq!(float_repr(0.125), "0.125");
253/// assert_eq!(float_repr(1e16), "1e+16");
254/// assert_eq!(float_repr(0.00001), "1e-05");
255/// ```
256pub fn float_repr(value: FloatType) -> String {
257    if value.is_nan() {
258        return "nan".to_string();
259    }
260    if value.is_infinite() {
261        return if value > 0.0 { "inf" } else { "-inf" }.to_string();
262    }
263    let scientific = format!("{value:e}");
264    let (mantissa, exponent) = scientific
265        .split_once('e')
266        .unwrap_or((scientific.as_str(), "0"));
267    let exponent: i32 = exponent.parse().unwrap_or(0);
268    let (sign, mantissa) = match mantissa.strip_prefix('-') {
269        Some(rest) => ("-", rest),
270        None => ("", mantissa),
271    };
272    let digits: String = mantissa.chars().filter(char::is_ascii_digit).collect();
273    if (-4..16).contains(&exponent) {
274        let point = exponent + 1;
275        if point <= 0 {
276            let zeros = "0".repeat(point.unsigned_abs() as usize);
277            return format!("{sign}0.{zeros}{digits}");
278        }
279        let point = point as usize;
280        if digits.len() <= point {
281            let zeros = "0".repeat(point - digits.len());
282            return format!("{sign}{digits}{zeros}.0");
283        }
284        return format!("{sign}{}.{}", &digits[..point], &digits[point..]);
285    }
286    let rest = if digits.len() > 1 {
287        format!(".{}", &digits[1..])
288    } else {
289        String::new()
290    };
291    let exponent_sign = if exponent < 0 { '-' } else { '+' };
292    format!(
293        "{sign}{}{rest}e{exponent_sign}{:02}",
294        &digits[..1],
295        exponent.unsigned_abs()
296    )
297}
298
299/// Python's `round(value, digits)` for a float: the value written out to
300/// that many decimal places, correctly rounded, and read back.
301pub(crate) fn round_digits(value: FloatType, digits: usize) -> FloatType {
302    if !value.is_finite() {
303        return value;
304    }
305    format!("{value:.digits$}").parse().unwrap_or(value)
306}
307
308/// Python's `divmod` for floats: the floored quotient, and the remainder
309/// with the sign of the divisor.
310pub(crate) fn float_divmod(x: FloatType, y: FloatType) -> (FloatType, FloatType) {
311    let mut modulo = x % y;
312    let mut division = (x - modulo) / y;
313    if modulo != 0.0 {
314        if (y < 0.0) != (modulo < 0.0) {
315            modulo += y;
316            division -= 1.0;
317        }
318    } else {
319        modulo = 0.0f64.copysign(y);
320    }
321    if division == 0.0 {
322        return (0.0f64.copysign(x / y), modulo);
323    }
324    let mut floored = division.floor();
325    if division - floored > 0.5 {
326        floored += 1.0;
327    }
328    (floored, modulo)
329}
330
331/// The exact fraction a float stands for, in lowest terms, as Python's
332/// `float.as_integer_ratio` gives it.
333///
334/// ```
335/// use music21::common::numbertools::float_ratio;
336/// use num::BigInt;
337///
338/// assert_eq!(float_ratio(0.75), Some((BigInt::from(3), BigInt::from(4))));
339/// assert_eq!(float_ratio(f64::NAN), None);
340/// ```
341pub fn float_ratio(value: FloatType) -> Option<(BigInt, BigInt)> {
342    if !value.is_finite() {
343        return None;
344    }
345    let (mantissa, exponent, sign) = Float::integer_decode(value);
346    if mantissa == 0 {
347        return Some((BigInt::zero(), BigInt::one()));
348    }
349    let zeros = mantissa.trailing_zeros();
350    let mantissa = BigInt::from(mantissa >> zeros) * BigInt::from(sign);
351    let exponent = i32::from(exponent) + zeros as i32;
352    if exponent >= 0 {
353        return Some((mantissa << exponent as usize, BigInt::one()));
354    }
355    Some((mantissa, BigInt::one() << exponent.unsigned_abs() as usize))
356}
357
358/// The fraction nearest `numerator / denominator` whose denominator is at
359/// most `limit`: Python's `Fraction.limit_denominator`, which music21's
360/// `_preFracLimitDenominator` copies. A fraction already within the limit
361/// comes back as it is.
362///
363/// ```
364/// use music21::common::numbertools::limit_denominator;
365/// use num::BigInt;
366///
367/// let third = limit_denominator(&100_001.into(), &300_001.into(), &65535.into())?;
368/// assert_eq!(third, (BigInt::from(1), BigInt::from(3)));
369/// # Ok::<(), music21::Error>(())
370/// ```
371///
372/// # Errors
373///
374/// A limit below one, which no denominator meets.
375pub fn limit_denominator(
376    numerator: &BigInt,
377    denominator: &BigInt,
378    limit: &BigInt,
379) -> Result<(BigInt, BigInt)> {
380    if *limit < BigInt::one() {
381        return Err(Error::Value(
382            "max_denominator should be at least 1".to_string(),
383        ));
384    }
385    if denominator <= limit {
386        return Ok((numerator.clone(), denominator.clone()));
387    }
388    let (mut p0, mut q0, mut p1, mut q1) =
389        (BigInt::zero(), BigInt::one(), BigInt::one(), BigInt::zero());
390    let (mut n, mut d) = (numerator.clone(), denominator.clone());
391    loop {
392        // Only a fraction not in lowest terms runs out before the limit.
393        if d.is_zero() {
394            return Ok((p1, q1));
395        }
396        let a = n.div_floor(&d);
397        let q2 = &q0 + &a * &q1;
398        if q2 > *limit {
399            break;
400        }
401        let p2 = &p0 + &a * &p1;
402        (p0, q0, p1, q1) = (p1, q1, p2, q2);
403        let next = &n - &a * &d;
404        n = d;
405        d = next;
406    }
407    let k = (limit - &q0).div_floor(&q1);
408    let far_n = &p0 + &k * &p1;
409    let far_d = &q0 + &k * &q1;
410    let far_off = (&far_n * denominator - numerator * &far_d).abs();
411    let near_off = (&p1 * denominator - numerator * &q1).abs();
412    if far_off * (denominator * &q1) - near_off * (denominator * &far_d) >= BigInt::zero() {
413        return Ok((p1, q1));
414    }
415    Ok((far_n, far_d))
416}
417
418fn is_power_of_two(value: &BigInt) -> bool {
419    value.is_positive() && (value & (value - BigInt::one())).is_zero()
420}
421
422/// music21's `opFrac` for a float: the float itself where its exact
423/// fraction has a denominator up to [`DENOM_LIMIT`], and otherwise the
424/// nearest fraction within the limit, written as a float again where its
425/// denominator is a power of two.
426///
427/// It is what keeps three triplet eighths summing to exactly one beat.
428///
429/// ```
430/// use music21::common::numbertools::{op_frac, OffsetQL};
431///
432/// assert_eq!(op_frac(0.25)?, OffsetQL::Float(0.25));
433/// assert_eq!(
434///     op_frac(1.0 / 3.0)?,
435///     OffsetQL::Fraction { numerator: 1, denominator: 3 }
436/// );
437/// assert_eq!(op_frac(0.99999999842)?, OffsetQL::Float(1.0));
438/// # Ok::<(), music21::Error>(())
439/// ```
440///
441/// # Errors
442///
443/// A value that is not finite, which has no fraction.
444pub fn op_frac(value: FloatType) -> Result<OffsetQL> {
445    let (numerator, denominator) = float_ratio(value).ok_or_else(|| {
446        let which = if value.is_nan() { "NaN" } else { "Infinity" };
447        Error::Value(format!("cannot convert {which} to integer ratio"))
448    })?;
449    let limit = BigInt::from(DENOM_LIMIT);
450    if denominator <= limit {
451        return Ok(OffsetQL::Float(value));
452    }
453    let (numerator, denominator) = limit_denominator(&numerator, &denominator, &limit)?;
454    // Within the limit, a numerator is far inside an `i64`: a float with
455    // bits below 2^-16 is under 2^37.
456    let numerator = numerator.to_i64().unwrap_or(i64::MAX);
457    let denominator = denominator.to_i64().unwrap_or(1);
458    if denominator & (denominator - 1) == 0 {
459        return Ok(OffsetQL::Float(
460            numerator as FloatType / denominator as FloatType,
461        ));
462    }
463    Ok(OffsetQL::Fraction {
464        numerator,
465        denominator,
466    })
467}
468
469/// Whether `denominator` is a power of two, which is when music21's
470/// `opFrac` turns a fraction into a float.
471pub fn is_binary_denominator(denominator: &BigInt) -> bool {
472    is_power_of_two(denominator)
473}
474
475/// A value close enough to a whole number, within a millionth, as that
476/// whole number, and anything else as it is: music21's `numToIntOrFloat`.
477///
478/// ```
479/// use music21::common::numbertools::{num_to_int_or_float, IntOrFloat};
480///
481/// assert_eq!(num_to_int_or_float(0.999999999)?, IntOrFloat::Int(1.into()));
482/// assert_eq!(num_to_int_or_float(1.5)?, IntOrFloat::Float(1.5));
483/// # Ok::<(), music21::Error>(())
484/// ```
485///
486/// # Errors
487///
488/// A value that is not finite, which rounds to no whole number.
489pub fn num_to_int_or_float(value: FloatType) -> Result<IntOrFloat> {
490    let rounded = whole(value.round_ties_even())?;
491    let back = rounded.to_f64().unwrap_or(FloatType::INFINITY);
492    if is_close(back, value, 1e-6) {
493        return Ok(IntOrFloat::Int(rounded));
494    }
495    Ok(IntOrFloat::Float(value))
496}
497
498/// A whole float as a whole number, refused as Python's `int` refuses it.
499fn whole(value: FloatType) -> Result<BigInt> {
500    if value.is_nan() {
501        return Err(Error::Value(
502            "cannot convert float NaN to integer".to_string(),
503        ));
504    }
505    BigInt::from_f64(value.trunc())
506        .ok_or_else(|| Error::Value("cannot convert float infinity to integer".to_string()))
507}
508
509/// A fraction as Python's `str` writes one: `3/7`, or `3` over one.
510fn fraction_text(numerator: &BigInt, denominator: &BigInt) -> String {
511    if denominator.is_one() {
512        return numerator.to_string();
513    }
514    format!("{numerator}/{denominator}")
515}
516
517fn mixed_text(quotient: &BigInt, remainder: &BigRational) -> String {
518    let fraction = fraction_text(remainder.numer(), remainder.denom());
519    if !quotient.is_zero() {
520        if remainder.is_zero() {
521            return quotient.to_string();
522        }
523        return format!("{quotient} {fraction}");
524    }
525    if !remainder.is_zero() {
526        return fraction;
527    }
528    "0".to_string()
529}
530
531/// A number as a whole number and a fraction, `1 1/3`, with the fraction's
532/// denominator limited to `limit`: music21's `mixedNumeral` for a float.
533///
534/// ```
535/// use music21::common::numbertools::mixed_numeral;
536///
537/// assert_eq!(mixed_numeral(1.333333, 65535)?, "1 1/3");
538/// assert_eq!(mixed_numeral(-0.333333, 65535)?, "-1/3");
539/// assert_eq!(mixed_numeral(2.0000001, 65535)?, "2");
540/// # Ok::<(), music21::Error>(())
541/// ```
542///
543/// # Errors
544///
545/// A value that is not finite, or a limit below one.
546pub fn mixed_numeral(value: FloatType, limit: u64) -> Result<String> {
547    let (mut quotient, remainder) = float_divmod(value, 1.0);
548    let (numerator, denominator) = float_ratio(remainder)
549        .ok_or_else(|| Error::Value("cannot convert NaN to integer ratio".to_string()))?;
550    let (numerator, denominator) =
551        limit_denominator(&numerator, &denominator, &BigInt::from(limit))?;
552    let mut fraction = BigRational::new(numerator, denominator);
553    if quotient < -1.0 {
554        quotient += 1.0;
555        fraction = BigRational::one() - fraction;
556    } else if quotient == -1.0 {
557        quotient = 0.0;
558        fraction -= BigRational::one();
559    }
560    Ok(mixed_text(&whole(quotient)?, &fraction))
561}
562
563/// [`mixed_numeral`] for an exact fraction, whose denominator is not
564/// limited: `-4 3/7` for -31/7.
565///
566/// ```
567/// use music21::common::numbertools::mixed_numeral_fraction;
568///
569/// assert_eq!(mixed_numeral_fraction(&31.into(), &7.into())?, "4 3/7");
570/// assert_eq!(mixed_numeral_fraction(&(-4).into(), &5.into())?, "-4/5");
571/// # Ok::<(), music21::Error>(())
572/// ```
573///
574/// # Errors
575///
576/// A denominator of nought, or a fraction too large for a float, which
577/// music21 passes through on the way.
578pub fn mixed_numeral_fraction(numerator: &BigInt, denominator: &BigInt) -> Result<String> {
579    if denominator.is_zero() {
580        return Err(Error::Value("Fraction(_, 0)".to_string()));
581    }
582    let value = BigRational::new(numerator.clone(), denominator.clone());
583    let quotient = whole(value.to_f64().unwrap_or(FloatType::NAN))?;
584    let mut remainder = &value - BigRational::from_integer(quotient.clone());
585    if quotient.is_negative() {
586        remainder = -remainder;
587    }
588    Ok(mixed_text(&quotient, &remainder))
589}
590
591/// A number rounded to the nearest half, a quarter rounding up, as
592/// music21's `roundToHalfInteger` does: a whole number where it lands on
593/// one, and a float on a half.
594///
595/// ```
596/// use music21::common::numbertools::{round_to_half_integer, IntOrFloat};
597///
598/// assert_eq!(round_to_half_integer(1.35)?, IntOrFloat::Float(1.5));
599/// assert_eq!(round_to_half_integer(1.75)?, IntOrFloat::Int(2.into()));
600/// assert_eq!(round_to_half_integer(-0.25)?, IntOrFloat::Int(0.into()));
601/// # Ok::<(), music21::Error>(())
602/// ```
603///
604/// # Errors
605///
606/// A value that is not finite.
607pub fn round_to_half_integer(value: FloatType) -> Result<IntOrFloat> {
608    let (floor, fraction) = float_divmod(value, 1.0);
609    let floor = whole(floor)?;
610    if fraction < 0.25 {
611        return Ok(IntOrFloat::Int(floor));
612    }
613    if fraction < 0.75 {
614        let floor = floor.to_f64().unwrap_or(FloatType::INFINITY);
615        return Ok(IntOrFloat::Float(floor + 0.5));
616    }
617    Ok(IntOrFloat::Int(floor + 1))
618}
619
620/// The third or sixth a value is within `grain` of, as [`op_frac`] gives
621/// it, or nothing for a value near neither: music21's
622/// `addFloatPrecision`, which leaves such a value alone.
623///
624/// ```
625/// use music21::common::numbertools::{add_float_precision, OffsetQL};
626///
627/// assert_eq!(
628///     add_float_precision(0.33, 1e-2),
629///     Some(OffsetQL::Fraction { numerator: 1, denominator: 3 })
630/// );
631/// assert_eq!(add_float_precision(0.2, 1e-2), None);
632/// ```
633pub fn add_float_precision(value: FloatType, grain: FloatType) -> Option<OffsetQL> {
634    [1.0 / 3.0, 2.0 / 3.0, 1.0 / 6.0, 5.0 / 6.0]
635        .into_iter()
636        .find(|candidate| is_close(value, *candidate, grain))
637        .and_then(|candidate| op_frac(candidate).ok())
638}
639
640/// A float written with `max_digits` decimals and its trailing zeros
641/// dropped, one decimal always kept: music21's `strTrimFloat`.
642///
643/// ```
644/// use music21::common::numbertools::str_trim_float;
645///
646/// assert_eq!(str_trim_float(42.3333333333, 4)?, "42.3333");
647/// assert_eq!(str_trim_float(6.66666666666666, 2)?, "6.67");
648/// assert_eq!(str_trim_float(2.0, 4)?, "2.0");
649/// # Ok::<(), music21::Error>(())
650/// ```
651///
652/// # Errors
653///
654/// No decimals asked for, or a value that is not finite: neither is
655/// written with a decimal point, which music21 looks for.
656pub fn str_trim_float(value: FloatType, max_digits: usize) -> Result<String> {
657    let written = format!("{value:.max_digits$}");
658    let point = written
659        .find('.')
660        .ok_or_else(|| Error::Value("substring not found".to_string()))?;
661    let bytes = written.as_bytes();
662    let mut length = written.len();
663    for index in (point + 2..written.len()).rev() {
664        if bytes[index] != b'0' {
665            break;
666        }
667        length -= 1;
668    }
669    Ok(written[..length].to_string())
670}
671
672/// The multiple of a unit nearest a value, as [`nearest_multiple`] finds
673/// it.
674#[derive(Clone, Copy, Debug, PartialEq)]
675pub struct NearestMultiple {
676    /// The multiple itself.
677    pub multiple: FloatType,
678    /// How far the value is from it, to seven decimals.
679    pub error: FloatType,
680    /// The value less the multiple, to seven decimals.
681    pub signed_error: FloatType,
682}
683
684/// The multiple of `unit` nearest a value that is not negative, how far
685/// off it is and which way: music21's `nearestMultiple`. Half way rounds
686/// down.
687///
688/// ```
689/// use music21::common::numbertools::nearest_multiple;
690///
691/// let found = nearest_multiple(0.4, 0.25)?;
692/// assert_eq!(found.multiple, 0.5);
693/// assert_eq!(found.signed_error, -0.1);
694/// # Ok::<(), music21::Error>(())
695/// ```
696///
697/// # Errors
698///
699/// A negative value, or one that falls between no two multiples.
700pub fn nearest_multiple(value: FloatType, unit: FloatType) -> Result<NearestMultiple> {
701    if value < 0.0 {
702        return Err(Error::Value(format!(
703            "n ({}) is less than zero. Thus, cannot find the nearest multiple for a value \
704             less than the unit, {}",
705            float_repr(value),
706            float_repr(unit)
707        )));
708    }
709    // Python's `math.floor` gives a whole number, which has no sign.
710    let multiple = (value / unit).floor() + 0.0;
711    let low = unit * multiple;
712    let high = unit * (multiple + 1.0);
713    if low >= value && value >= high {
714        return Err(Error::Value(format!(
715            "cannot place n between multiples: {}, {}",
716            float_repr(low),
717            float_repr(high)
718        )));
719    }
720    if low <= value && value <= low + unit / 2.0 {
721        let error = round_digits(value - low, 7);
722        return Ok(NearestMultiple {
723            multiple: low,
724            error,
725            signed_error: error,
726        });
727    }
728    Ok(NearestMultiple {
729        multiple: high,
730        error: round_digits(high - value, 7),
731        signed_error: round_digits(value - high, 7),
732    })
733}
734
735/// music21's `_DOT_LOOKUP`: what one to eight dots multiply a length by.
736const DOT_MULTIPLIERS: [FloatType; 9] = [
737    1.0, 1.5, 1.75, 1.875, 1.9375, 1.96875, 1.984375, 1.9921875, 1.99609375,
738];
739
740/// What `dots` dots multiply a note's length by: music21's
741/// `dotMultiplier`. It is always exact, since its denominator is a power
742/// of two.
743///
744/// ```
745/// use music21::common::numbertools::dot_multiplier;
746///
747/// assert_eq!(dot_multiplier(0), 1.0);
748/// assert_eq!(dot_multiplier(2), 1.75);
749/// ```
750pub fn dot_multiplier(dots: u32) -> FloatType {
751    if let Some(found) = DOT_MULTIPLIERS.get(dots as usize) {
752        return *found;
753    }
754    let dots = FloatType::from(dots);
755    (2.0f64.powf(dots + 1.0) - 1.0) / 2.0f64.powf(dots)
756}
757
758/// The tuplet ratio, in lowest terms, that a simple decimal stands for:
759/// music21's `decimalToTuplet`. Below one, the denominator is the larger.
760///
761/// ```
762/// use music21::common::numbertools::decimal_to_tuplet;
763///
764/// assert_eq!(decimal_to_tuplet(1.25)?, (5, 4));
765/// assert_eq!(decimal_to_tuplet(0.8)?, (4, 5));
766/// # Ok::<(), music21::Error>(())
767/// ```
768///
769/// # Errors
770///
771/// A value not above nought, or one no ratio with a denominator under a
772/// thousand comes within a ten-millionth of.
773pub fn decimal_to_tuplet(value: FloatType) -> Result<(i128, i128)> {
774    if value <= 0.0 {
775        return Err(Error::Value("number must be greater than zero".to_string()));
776    }
777    let flipped = value < 1.0;
778    let value = if flipped { 1.0 / value } else { value };
779    let multiplier = value.trunc();
780    let working = value / multiplier;
781    let (numerator, denominator) =
782        simple_fraction(working).ok_or_else(|| Error::Value("No such luck".to_string()))?;
783    let scaled = FloatType::from(numerator) * multiplier;
784    let divisor = num::integer::gcd(scaled as i128, i128::from(denominator));
785    let numerator = (scaled / divisor as FloatType) as i128;
786    let denominator = (FloatType::from(denominator) / divisor as FloatType) as i128;
787    if flipped {
788        return Ok((denominator, numerator));
789    }
790    Ok((numerator, denominator))
791}
792
793/// The first `j / i`, `i` under a thousand and `j` from `i` to under twice
794/// it, within a ten-millionth of `value`.
795fn simple_fraction(value: FloatType) -> Option<(u32, u32)> {
796    for index in 1..1000u32 {
797        for numerator in index..index * 2 {
798            if is_close(
799                value,
800                FloatType::from(numerator) / FloatType::from(index),
801                1e-7,
802            ) {
803                return Some((numerator, index));
804            }
805        }
806    }
807    None
808}
809
810/// Each value as its share of their sum: music21's
811/// `unitNormalizeProportion`.
812///
813/// ```
814/// use music21::common::numbertools::unit_normalize_proportion;
815///
816/// assert_eq!(unit_normalize_proportion(&[1.0, 1.0, 2.0])?, [0.25, 0.25, 0.5]);
817/// # Ok::<(), music21::Error>(())
818/// ```
819///
820/// # Errors
821///
822/// A negative value. Values summing to nought give no finite shares.
823pub fn unit_normalize_proportion(values: &[FloatType]) -> Result<Vec<FloatType>> {
824    let mut sum = 0.0;
825    for value in values {
826        if *value < 0.0 {
827            return Err(Error::Value("value members must be positive".to_string()));
828        }
829        sum += value;
830    }
831    Ok(values.iter().map(|value| value / sum).collect())
832}
833
834/// The span of the unit interval each value's share of their sum takes,
835/// one after another, the last ending at exactly one: music21's
836/// `unitBoundaryProportion`.
837///
838/// ```
839/// use music21::common::numbertools::unit_boundary_proportion;
840///
841/// assert_eq!(
842///     unit_boundary_proportion(&[1.0, 1.0, 2.0])?,
843///     [(0.0, 0.25), (0.25, 0.5), (0.5, 1.0)]
844/// );
845/// # Ok::<(), music21::Error>(())
846/// ```
847///
848/// # Errors
849///
850/// A negative value.
851pub fn unit_boundary_proportion(values: &[FloatType]) -> Result<Vec<(FloatType, FloatType)>> {
852    let shares = unit_normalize_proportion(values)?;
853    let mut bounds = Vec::with_capacity(shares.len());
854    let mut sum = 0.0;
855    for (index, share) in shares.iter().enumerate() {
856        if index == shares.len() - 1 {
857            bounds.push((sum, 1.0));
858            break;
859        }
860        bounds.push((sum, sum + share));
861        sum += share;
862    }
863    Ok(bounds)
864}
865
866/// Which of the weighted choices a draw `draw` from the unit interval
867/// lands on, as music21's `weightedSelection` picks one: the last where it
868/// lands on none.
869///
870/// ```
871/// use music21::common::numbertools::weighted_index;
872///
873/// assert_eq!(weighted_index(&[1.0, 3.0], 0.2)?, 0);
874/// assert_eq!(weighted_index(&[1.0, 3.0], 0.3)?, 1);
875/// # Ok::<(), music21::Error>(())
876/// ```
877///
878/// # Errors
879///
880/// A negative weight.
881pub fn weighted_index(weights: &[FloatType], draw: FloatType) -> Result<usize> {
882    let bounds = unit_boundary_proportion(weights)?;
883    let found = bounds
884        .iter()
885        .position(|(low, high)| *low <= draw && draw < *high);
886    Ok(found.unwrap_or(bounds.len().saturating_sub(1)))
887}
888
889/// The greatest length that goes a whole number of times, to within
890/// `grain`, into every one of `values`: music21's `approximateGCD`, which
891/// tries the smallest value, then each value divided by one to sixteen.
892///
893/// ```
894/// use music21::common::numbertools::approximate_gcd;
895///
896/// assert_eq!(approximate_gcd(&[2.5, 10.0, 0.25], 1e-4)?, 0.25);
897/// assert_eq!(approximate_gcd(&[1.5, 5.0, 2.0, 7.0], 1e-4)?, 0.5);
898/// # Ok::<(), music21::Error>(())
899/// ```
900///
901/// # Errors
902///
903/// No values, or no length that goes into them all. The smallest value
904/// being nought gives no finite answer.
905pub fn approximate_gcd(values: &[FloatType], grain: FloatType) -> Result<FloatType> {
906    let lowest = values
907        .iter()
908        .copied()
909        .reduce(FloatType::min)
910        .ok_or_else(|| Error::Value("min() iterable argument is empty".to_string()))?;
911    let divides = values.iter().all(|value| {
912        let adjusted = value / lowest;
913        is_close(adjusted - adjusted.trunc(), 0.0, grain)
914    });
915    if divides {
916        return Ok(lowest);
917    }
918    let divisions: Vec<Vec<FloatType>> = values
919        .iter()
920        .map(|value| (1..=16).map(|d| value / FloatType::from(d)).collect())
921        .collect();
922    divisions
923        .iter()
924        .flatten()
925        .copied()
926        .filter(|candidate| {
927            divisions
928                .iter()
929                .all(|row| row.iter().any(|x| is_close(*x, *candidate, grain)))
930        })
931        .reduce(FloatType::max)
932        .ok_or_else(|| Error::Value("cannot find a common divisor".to_string()))
933}
934
935/// Whether each value is one more than the one before: music21's
936/// `contiguousList`, which wants them sorted first. An empty list is
937/// contiguous here; music21 cannot look at its first value.
938///
939/// ```
940/// use music21::common::numbertools::contiguous_list;
941///
942/// assert!(contiguous_list(&[3, 4, 5, 6]));
943/// assert!(!contiguous_list(&[3, 4, 5, 6, 8]));
944/// ```
945pub fn contiguous_list<T>(values: &[T]) -> bool
946where
947    T: Copy + PartialEq + std::ops::Add<Output = T> + One,
948{
949    values.windows(2).all(|pair| pair[1] == pair[0] + T::one())
950}
951
952/// The runs of sorted values each one more than the one before, as ranges
953/// of their positions: what music21's `groupContiguousIntegers` groups.
954///
955/// ```
956/// use music21::common::numbertools::contiguous_runs;
957///
958/// assert_eq!(contiguous_runs(&[3, 4, 6, 7, 20]), [0..2, 2..4, 4..5]);
959/// ```
960pub fn contiguous_runs<T>(sorted: &[T]) -> Vec<Range<usize>>
961where
962    T: Copy + PartialEq + std::ops::Add<Output = T> + One,
963{
964    let mut runs = Vec::new();
965    let mut start = 0;
966    for index in 1..=sorted.len() {
967        let ends = index == sorted.len() || sorted[index] != sorted[index - 1] + T::one();
968        if ends {
969            runs.push(start..index);
970            start = index;
971        }
972    }
973    runs
974}
975
976/// A Roman numeral, upper or lower case, read as a number: music21's
977/// `fromRoman`. The medieval `IIII` and `IC` are read too, unless
978/// `strict_modern` refuses a subtraction of less than a tenth.
979///
980/// ```
981/// use music21::common::numbertools::from_roman;
982///
983/// assert_eq!(from_roman("MCDLXXXIX", false)?, 1489);
984/// assert_eq!(from_roman("ic", false)?, 99);
985/// assert!(from_roman("ic", true).is_err());
986/// # Ok::<(), music21::Error>(())
987/// ```
988///
989/// # Errors
990///
991/// A letter that is not a numeral, or a subtraction no Roman wrote.
992pub fn from_roman(text: &str, strict_modern: bool) -> Result<i64> {
993    let upper = text.to_uppercase();
994    let value_of = |letter: char| match letter {
995        'M' => Some(1000),
996        'D' => Some(500),
997        'C' => Some(100),
998        'L' => Some(50),
999        'X' => Some(10),
1000        'V' => Some(5),
1001        'I' => Some(1),
1002        _ => None,
1003    };
1004    let values: Vec<i64> = upper
1005        .chars()
1006        .map(value_of)
1007        .collect::<Option<_>>()
1008        .ok_or_else(|| Error::Value(format!("value is not a valid roman numeral: {upper}")))?;
1009    let mut sum = 0;
1010    for (index, value) in values.iter().enumerate() {
1011        let mut value = *value;
1012        if let Some(next) = values.get(index + 1).copied() {
1013            if next > value && [1, 10, 100].contains(&value) {
1014                if strict_modern && next >= value * 10 {
1015                    return Err(Error::Value(format!(
1016                        "input contains an invalid subtraction element (modern interpretation): \
1017                         {text}"
1018                    )));
1019                }
1020                value = -value;
1021            } else if next > value {
1022                return Err(Error::Value(format!(
1023                    "input contains an invalid subtraction element: {text}"
1024                )));
1025            }
1026        }
1027        sum += value;
1028    }
1029    Ok(sum)
1030}
1031
1032/// A number from 1 to 3999 as a Roman numeral: music21's `toRoman`.
1033///
1034/// ```
1035/// use music21::common::numbertools::to_roman;
1036///
1037/// assert_eq!(to_roman(1999)?, "MCMXCIX");
1038/// assert!(to_roman(0).is_err());
1039/// # Ok::<(), music21::Error>(())
1040/// ```
1041///
1042/// # Errors
1043///
1044/// A number outside that range.
1045pub fn to_roman(number: i64) -> Result<String> {
1046    if !(1..4000).contains(&number) {
1047        return Err(Error::Value(
1048            "Argument must be between 1 and 3999".to_string(),
1049        ));
1050    }
1051    const NUMERALS: [(i64, &str); 13] = [
1052        (1000, "M"),
1053        (900, "CM"),
1054        (500, "D"),
1055        (400, "CD"),
1056        (100, "C"),
1057        (90, "XC"),
1058        (50, "L"),
1059        (40, "XL"),
1060        (10, "X"),
1061        (9, "IX"),
1062        (5, "V"),
1063        (4, "IV"),
1064        (1, "I"),
1065    ];
1066    let mut rest = number;
1067    let mut written = String::new();
1068    for (value, numeral) in NUMERALS {
1069        let count = rest / value;
1070        written.push_str(&numeral.repeat(count as usize));
1071        rest -= value * count;
1072    }
1073    Ok(written)
1074}
1075
1076/// The letters written after a number to make it an ordinal, `st`, `nd`,
1077/// `rd` or `th`, with an `s` after all but `st` for `plural`: music21's
1078/// `ordinalAbbreviation`.
1079///
1080/// ```
1081/// use music21::common::numbertools::ordinal_abbreviation;
1082///
1083/// assert_eq!(ordinal_abbreviation(3, false), "rd");
1084/// assert_eq!(ordinal_abbreviation(12, false), "th");
1085/// assert_eq!(ordinal_abbreviation(255, true), "ths");
1086/// ```
1087pub fn ordinal_abbreviation(value: i64, plural: bool) -> &'static str {
1088    let suffix = if (11..=13).contains(&value.rem_euclid(100)) {
1089        "th"
1090    } else {
1091        match value.rem_euclid(10) {
1092            1 => "st",
1093            2 => "nd",
1094            3 => "rd",
1095            _ => "th",
1096        }
1097    };
1098    if !plural || suffix == "st" {
1099        return suffix;
1100    }
1101    match suffix {
1102        "nd" => "nds",
1103        "rd" => "rds",
1104        _ => "ths",
1105    }
1106}
1107
1108/// music21's `ordinalsToNumbers`, in the order it fills it: each ordinal
1109/// name, lowered and not, and abbreviated, `1st`, and each interval name
1110/// that differs from it, mapped to its number.
1111pub fn ordinals_to_numbers() -> Vec<(String, usize)> {
1112    let mut entries = Vec::new();
1113    for (index, name) in ORDINAL_NAMES.iter().enumerate() {
1114        entries.push(((*name).to_string(), index));
1115        entries.push((name.to_lowercase(), index));
1116        let abbreviation = ordinal_abbreviation(index as i64, false);
1117        entries.push((format!("{index}{abbreviation}"), index));
1118        let music = MUSIC_ORDINAL_NAMES[index];
1119        if music != *name {
1120            entries.push((music.to_string(), index));
1121            entries.push((music.to_lowercase(), index));
1122        }
1123    }
1124    entries
1125}
1126
1127#[cfg(test)]
1128mod tests {
1129    use super::*;
1130    use std::convert::TryFrom;
1131
1132    #[test]
1133    fn floats_past_the_limit_snap_to_a_fraction() {
1134        assert_eq!(
1135            op_frac(0.123456789).unwrap(),
1136            OffsetQL::Fraction {
1137                numerator: 10,
1138                denominator: 81
1139            }
1140        );
1141        assert_eq!(op_frac(0.000001).unwrap(), OffsetQL::Float(0.0));
1142        assert_eq!(op_frac(-1.0 / 3.0).unwrap().to_f64(), -1.0 / 3.0);
1143        assert!(op_frac(f64::NAN).is_err());
1144        assert!(op_frac(f64::INFINITY).is_err());
1145    }
1146
1147    #[test]
1148    fn music21s_own_limit_matches_pythons() {
1149        let limited = limit_denominator(&100_001.into(), &300_001.into(), &65535.into()).unwrap();
1150        assert_eq!(limited, (BigInt::from(1), BigInt::from(3)));
1151        let (n, d) = float_ratio(1e-300).unwrap();
1152        let limited = limit_denominator(&n, &d, &65535.into()).unwrap();
1153        assert_eq!(limited, (BigInt::from(0), BigInt::from(1)));
1154    }
1155
1156    #[test]
1157    fn mixed_numerals_written_as_music21_writes_them() {
1158        assert_eq!(mixed_numeral(-1.333333, 65535).unwrap(), "-1 1/3");
1159        assert_eq!(mixed_numeral(0.0, 65535).unwrap(), "0");
1160        assert_eq!(mixed_numeral(-0.0, 65535).unwrap(), "0");
1161        assert_eq!(
1162            mixed_numeral(2.0000001, 10_000_000).unwrap(),
1163            "2 1/10000000"
1164        );
1165        let fraction = |n: i64, d: i64| mixed_numeral_fraction(&n.into(), &d.into()).unwrap();
1166        assert_eq!(fraction(-31, 7), "-4 3/7");
1167        assert_eq!(fraction(-1, 5), "-1/5");
1168        assert_eq!(fraction(1, 5), "1/5");
1169    }
1170
1171    #[test]
1172    fn floats_written_as_python_writes_them() {
1173        assert_eq!(float_repr(-0.5), "-0.5");
1174        assert_eq!(float_repr(23404.0), "23404.0");
1175        assert_eq!(float_repr(1e22), "1e+22");
1176        assert_eq!(float_repr(1.5e-7), "1.5e-07");
1177        assert_eq!(float_repr(0.0001), "0.0001");
1178        assert_eq!(float_repr(123456789012345.6), "123456789012345.6");
1179        assert_eq!(round_digits(0.35 - 0.25, 7), 0.1);
1180    }
1181
1182    #[test]
1183    fn halves_round_up_on_the_boundaries() {
1184        let int = |value: i64| IntOrFloat::Int(value.into());
1185        assert_eq!(round_to_half_integer(1.2).unwrap(), int(1));
1186        assert_eq!(round_to_half_integer(0.25).unwrap(), IntOrFloat::Float(0.5));
1187        assert_eq!(round_to_half_integer(0.75).unwrap(), int(1));
1188        assert_eq!(
1189            round_to_half_integer(-0.26).unwrap(),
1190            IntOrFloat::Float(-0.5)
1191        );
1192        assert!(round_to_half_integer(f64::INFINITY).is_err());
1193    }
1194
1195    #[test]
1196    fn nearest_multiples_and_their_errors() {
1197        let found = nearest_multiple(23404.0 - 0.0625, 0.125).unwrap();
1198        assert_eq!(
1199            (found.multiple, found.error, found.signed_error),
1200            (23403.875, 0.0625, 0.0625)
1201        );
1202        let error = nearest_multiple(-0.5, 0.125).unwrap_err();
1203        assert_eq!(
1204            error.to_string(),
1205            "Value error: n (-0.5) is less than zero. Thus, cannot find the nearest multiple \
1206             for a value less than the unit, 0.125"
1207        );
1208    }
1209
1210    /// Python's `math.floor` gives an int, which has no sign, so music21's
1211    /// multiple of nought is a positive nought even for a negative one.
1212    #[test]
1213    fn the_multiple_of_negative_nought_is_unsigned() {
1214        let found = nearest_multiple(-0.0, 0.125).unwrap();
1215        assert!(found.multiple.is_sign_positive());
1216        assert!(found.error.is_sign_negative());
1217    }
1218
1219    #[test]
1220    fn numbers_and_strings_of_music21s_examples() {
1221        assert_eq!(str_trim_float(-5.0, 4).unwrap(), "-5.0");
1222        assert!(str_trim_float(1.0, 0).is_err());
1223        assert_eq!(decimal_to_tuplet(1.5).unwrap(), (3, 2));
1224        assert!(decimal_to_tuplet(-0.02).is_err());
1225        assert_eq!(dot_multiplier(3), 1.875);
1226        assert_eq!(dot_multiplier(10), 2047.0 / 1024.0);
1227        assert_eq!(approximate_gcd(&[2.0, 5.0, 10.0], 1e-4).unwrap(), 1.0);
1228        let third = approximate_gcd(&[5.0 / 3.0, 2.0 / 3.0, 5.0 / 6.0, 3.0 / 6.0], 1e-4).unwrap();
1229        assert_eq!(str_trim_float(third, 4).unwrap(), "0.1667");
1230        assert_eq!(
1231            num_to_int_or_float(1.00003).unwrap(),
1232            IntOrFloat::Float(1.00003)
1233        );
1234        assert!(unit_normalize_proportion(&[0.0, -2.0, -8.0]).is_err());
1235        assert_eq!(weighted_index(&[1.0, 0.0], 0.99).unwrap(), 0);
1236        assert_eq!(contiguous_runs(&[3, 3, 4]), [0..1, 1..3]);
1237        assert_eq!(contiguous_runs::<i64>(&[]), Vec::<Range<usize>>::new());
1238    }
1239
1240    #[test]
1241    fn roman_numerals_both_ways() {
1242        assert_eq!(from_roman("vii", false).unwrap(), 7);
1243        assert_eq!(from_roman("MCCCCLXXXIX", false).unwrap(), 1489);
1244        assert_eq!(
1245            from_roman("vx", false).unwrap_err().to_string(),
1246            "Value error: input contains an invalid subtraction element: vx"
1247        );
1248        assert_eq!(
1249            from_roman("ab", false).unwrap_err().to_string(),
1250            "Value error: value is not a valid roman numeral: AB"
1251        );
1252        assert_eq!(to_roman(7).unwrap(), "VII");
1253        assert!(to_roman(4000).is_err());
1254    }
1255
1256    #[test]
1257    fn ordinals_map_to_their_numbers() {
1258        let entries = ordinals_to_numbers();
1259        let find = |name: &str| entries.iter().find(|(key, _)| key == name).map(|(_, n)| *n);
1260        assert_eq!(find("unison"), Some(1));
1261        assert_eq!(find("1st"), Some(1));
1262        assert_eq!(find("Octave"), Some(8));
1263        assert_eq!(find("8th"), Some(8));
1264        assert_eq!(find("22nd"), Some(22));
1265        assert_eq!(
1266            &entries[..3],
1267            &[
1268                ("Zeroth".to_string(), 0),
1269                ("zeroth".to_string(), 0),
1270                ("0th".to_string(), 0)
1271            ]
1272        );
1273    }
1274
1275    #[test]
1276    fn test_music_ordinal_try_from_integer_valid() {
1277        let cases = [
1278            (0, MusicOrdinals::Zeroth),
1279            (1, MusicOrdinals::Unison),
1280            (2, MusicOrdinals::Second),
1281            (8, MusicOrdinals::Octave),
1282            (15, MusicOrdinals::DoubleOctave),
1283            (22, MusicOrdinals::TripleOctave),
1284        ];
1285        for (input, expected) in cases {
1286            let ordinal = MusicOrdinals::try_from(input).unwrap();
1287            assert_eq!(ordinal, expected);
1288        }
1289    }
1290
1291    #[test]
1292    fn test_music_ordinal_try_from_integer_invalid() {
1293        let result = MusicOrdinals::try_from(23);
1294        assert!(result.is_err());
1295        if let Err(Error::Ordinal(msg)) = result {
1296            assert!(msg.contains("Invalid MusicOrdinals value: 23"));
1297        } else {
1298            panic!("Expected Error::Ordinal error");
1299        }
1300    }
1301
1302    #[test]
1303    fn test_music_ordinal_try_from_str_valid() {
1304        let cases = [
1305            ("zeroth", MusicOrdinals::Zeroth),
1306            ("Unison", MusicOrdinals::Unison),
1307            ("SECOND", MusicOrdinals::Second),
1308            ("octave", MusicOrdinals::Octave),
1309            ("double-octave", MusicOrdinals::DoubleOctave),
1310            ("triple-octave", MusicOrdinals::TripleOctave),
1311        ];
1312        for (input, expected) in cases {
1313            let ordinal = MusicOrdinals::try_from(input).unwrap();
1314            assert_eq!(ordinal, expected);
1315        }
1316    }
1317
1318    #[test]
1319    fn test_music_ordinal_try_from_str_invalid() {
1320        let result = MusicOrdinals::try_from("invalid");
1321        assert!(result.is_err());
1322        if let Err(Error::Ordinal(msg)) = result {
1323            assert!(msg.contains("Invalid MusicOrdinals string: invalid"));
1324        } else {
1325            panic!("Expected Error::Ordinal error");
1326        }
1327    }
1328
1329    #[test]
1330    fn test_music_ordinal_display() {
1331        let ordinal = MusicOrdinals::TwentyFirst;
1332        assert_eq!(format!("{ordinal}"), "Twenty-first");
1333    }
1334
1335    #[test]
1336    fn test_static_arrays() {
1337        let musical_strings: Vec<_> = MUSICAL_ORDINAL_STRINGS.iter().cloned().collect();
1338        assert_eq!(musical_strings[0], "Zeroth");
1339        assert_eq!(musical_strings[1], "Unison");
1340        assert_eq!(musical_strings[8], "Octave");
1341        assert_eq!(musical_strings[15], "Double-octave");
1342        assert_eq!(musical_strings[22], "Triple-octave");
1343    }
1344}