|
| 1 | +// Adapted from Yann Villessuzanne's roman.rs under the |
| 2 | +// Unlicense, at https://github.com/linfir/roman.rs/ |
| 3 | + |
| 4 | +use crate::integer::IntegerImpl; |
| 5 | +use crate::UnsignedInteger; |
| 6 | +use core::fmt; |
| 7 | + |
| 8 | +/// Formats unsigned integers as Roman numerals. |
| 9 | +/// |
| 10 | +/// By default, the dedicated unicode symbols for Roman numerals are used. |
| 11 | +/// You can use [`Roman::ascii`] to use ASCII symbols instead. |
| 12 | +/// |
| 13 | +/// ``` |
| 14 | +/// # use fmtastic::Roman; |
| 15 | +/// assert_eq!("ⅾⅽⅽⅼⅹⅹⅹⅰⅹ", format!("{:#}", Roman::new(789_u16).unwrap())); // lowercase |
| 16 | +/// assert_eq!("ⅯⅯⅩⅩⅠⅤ", format!("{}", Roman::new(2024_u16).unwrap())); |
| 17 | +/// assert_eq!("MMXXIV", format!("{}", Roman::new(2024_u16).unwrap().ascii())); // ascii |
| 18 | +/// assert_eq!("ⅠⅠⅠ", format!("{}", Roman::from(3_u8))); // u8's can always be formatted as Roman numeral |
| 19 | +/// ``` |
| 20 | +/// |
| 21 | +/// ## Formatting Flags |
| 22 | +/// ### Alternate `#` |
| 23 | +/// By default uppercase numerals are used. |
| 24 | +/// The alternate flag `#` can be used to switch to lowercase numerals. |
| 25 | +#[derive(Debug, Clone, Copy, Eq, PartialEq)] |
| 26 | +pub struct Roman<T>(T, SymbolRepertoire); |
| 27 | + |
| 28 | +impl<T> Roman<T> { |
| 29 | + /// Uses ASCII symbols instead of the dedicated unciode |
| 30 | + /// symbols for Roman numerals. |
| 31 | + pub fn ascii(mut self) -> Self { |
| 32 | + self.1 = SymbolRepertoire::Ascii; |
| 33 | + self |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +#[derive(Debug, Clone, Copy, Eq, PartialEq)] |
| 38 | +#[non_exhaustive] |
| 39 | +enum SymbolRepertoire { |
| 40 | + Unicode, |
| 41 | + Ascii, |
| 42 | +} |
| 43 | + |
| 44 | +impl From<u8> for Roman<u8> { |
| 45 | + fn from(value: u8) -> Self { |
| 46 | + Roman(value, SymbolRepertoire::Unicode) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +impl<T> Roman<T> |
| 51 | +where |
| 52 | + T: UnsignedInteger, |
| 53 | +{ |
| 54 | + /// Creates a new [`Roman`] numeral. |
| 55 | + /// Returns `None` if the value is not between 1 and 3999. |
| 56 | + pub fn new(value: T) -> Option<Roman<T>> { |
| 57 | + if T::Impl::ZERO < value.into_impl() && value.into_impl() <= T::UnsignedImpl::ROMAN_MAX { |
| 58 | + Some(Roman(value, SymbolRepertoire::Unicode)) |
| 59 | + } else { |
| 60 | + None |
| 61 | + } |
| 62 | + } |
| 63 | +} |
| 64 | + |
| 65 | +impl<T> fmt::Display for Roman<T> |
| 66 | +where |
| 67 | + T: UnsignedInteger, |
| 68 | +{ |
| 69 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 70 | + let mut n = self.0.into_impl(); |
| 71 | + for (symbol, value) in roman_pairs::<T>(self.1, f.alternate()) { |
| 72 | + let value = value.into_impl(); |
| 73 | + while n >= value { |
| 74 | + n -= value; |
| 75 | + write!(f, "{symbol}")?; |
| 76 | + } |
| 77 | + } |
| 78 | + debug_assert!(n == T::Impl::ZERO); |
| 79 | + Ok(()) |
| 80 | + } |
| 81 | +} |
| 82 | + |
| 83 | +fn roman_pairs<T>( |
| 84 | + repertoire: SymbolRepertoire, |
| 85 | + lowercase: bool, |
| 86 | +) -> impl Iterator<Item = (&'static str, T)> |
| 87 | +where |
| 88 | + T: UnsignedInteger, |
| 89 | +{ |
| 90 | + ROMAN_PAIRS.iter().copied().filter_map( |
| 91 | + move |(upper_unicode, lower_unicode, upper_ascii, lower_ascii, value)| { |
| 92 | + let symbol = match (repertoire, lowercase) { |
| 93 | + (SymbolRepertoire::Unicode, false) => upper_unicode, |
| 94 | + (SymbolRepertoire::Unicode, true) => lower_unicode, |
| 95 | + (SymbolRepertoire::Ascii, false) => upper_ascii, |
| 96 | + (SymbolRepertoire::Ascii, true) => lower_ascii, |
| 97 | + }; |
| 98 | + Some((symbol, T::Impl::try_from(value).ok()?.into_public())) |
| 99 | + }, |
| 100 | + ) |
| 101 | +} |
| 102 | + |
| 103 | +static ROMAN_PAIRS: &[(&str, &str, &str, &str, u16)] = &[ |
| 104 | + ("Ⅿ", "ⅿ", "M", "m", 1000), |
| 105 | + ("ⅭⅯ", "ⅽⅿ", "CM", "cm", 900), |
| 106 | + ("Ⅾ", "ⅾ", "D", "d", 500), |
| 107 | + ("ⅭⅮ", "ⅽⅾ", "CD", "cd", 400), |
| 108 | + ("Ⅽ", "ⅽ", "C", "c", 100), |
| 109 | + ("ⅩⅭ", "ⅹⅽ", "XC", "xc", 90), |
| 110 | + ("Ⅼ", "ⅼ", "L", "l", 50), |
| 111 | + ("ⅩⅬ", "ⅹⅼ", "XL", "xl", 40), |
| 112 | + ("Ⅹ", "ⅹ", "X", "x", 10), |
| 113 | + ("ⅠⅩ", "ⅰⅹ", "IX", "ix", 9), |
| 114 | + ("Ⅴ", "ⅴ", "V", "v", 5), |
| 115 | + ("ⅠⅤ", "ⅰⅴ", "IV", "iv", 4), |
| 116 | + ("Ⅰ", "ⅰ", "I", "i", 1), |
| 117 | +]; |
| 118 | + |
| 119 | +pub(crate) trait RomanInteger { |
| 120 | + const ROMAN_MAX: Self; |
| 121 | +} |
| 122 | + |
| 123 | +impl RomanInteger for u8 { |
| 124 | + const ROMAN_MAX: Self = u8::MAX; |
| 125 | +} |
| 126 | + |
| 127 | +macro_rules! impl_roman_integer { |
| 128 | + ($($ty:ty),*) => { |
| 129 | + $( |
| 130 | + impl RomanInteger for $ty { |
| 131 | + /// The largest number representable as a roman numeral. |
| 132 | + const ROMAN_MAX: Self = 3999; |
| 133 | + } |
| 134 | + )* |
| 135 | + } |
| 136 | +} |
| 137 | + |
| 138 | +impl_roman_integer!(u16, u32, u64, u128, usize); |
| 139 | + |
| 140 | +#[cfg(test)] |
| 141 | +mod tests { |
| 142 | + use super::*; |
| 143 | + |
| 144 | + #[test] |
| 145 | + fn test_to_roman() { |
| 146 | + let roman = |
| 147 | + "I II III IV V VI VII VIII IX X XI XII XIII XIV XV XVI XVII XVIII XIX XX XXI XXII" |
| 148 | + .split(' '); |
| 149 | + for (i, x) in roman.enumerate() { |
| 150 | + let n = i + 1; |
| 151 | + assert_eq!(format!("{}", Roman::new(n).unwrap().ascii()), x); |
| 152 | + } |
| 153 | + assert_eq!( |
| 154 | + format!("{}", Roman::new(1984u32).unwrap().ascii()), |
| 155 | + "MCMLXXXIV" |
| 156 | + ); |
| 157 | + assert_eq!( |
| 158 | + format!("{}", Roman::new(448u32).unwrap().ascii()), |
| 159 | + "CDXLVIII" |
| 160 | + ); |
| 161 | + } |
| 162 | +} |
0 commit comments