1use 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
78define_ordinals! {
80 pub(crate) enum MusicOrdinals {
81 Zeroth => ("Zeroth", "zeroth"),
82 Unison => ("Unison", "unison"), 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"), 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"), 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"), }
105}
106
107pub(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
120pub(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
125pub const DENOM_LIMIT: u64 = 65535;
128
129pub 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
157pub 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#[derive(Clone, Copy, Debug, PartialEq)]
188#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
189pub enum OffsetQL {
190 Float(FloatType),
192 Fraction {
194 numerator: i64,
196 denominator: i64,
198 },
199}
200
201impl OffsetQL {
202 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#[derive(Clone, Debug, PartialEq)]
217pub enum IntOrFloat {
218 Int(BigInt),
220 Float(FloatType),
222}
223
224pub 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
244pub 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
299pub(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
308pub(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
331pub 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
358pub 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 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
422pub 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 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
469pub fn is_binary_denominator(denominator: &BigInt) -> bool {
472 is_power_of_two(denominator)
473}
474
475pub 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
498fn 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
509fn 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
531pub 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
563pub 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("ient, &remainder))
589}
590
591pub 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
620pub 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
640pub 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#[derive(Clone, Copy, Debug, PartialEq)]
675pub struct NearestMultiple {
676 pub multiple: FloatType,
678 pub error: FloatType,
680 pub signed_error: FloatType,
682}
683
684pub 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 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
735const 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
740pub 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
758pub 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
793fn 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
810pub 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
834pub 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
866pub 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
889pub 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
935pub 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
952pub 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
976pub 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
1032pub 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
1076pub 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
1108pub 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 #[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}