Skip to main content

amount/
display.rs

1//! Display and wire renderings of an exact amount.
2
3use num_rational::Rational64;
4
5use crate::parse_amount;
6
7const MIN_SCALE: u32 = 2;
8
9/// Reduced `(num, denom)` with a positive denominator; `None` for a zero one.
10fn reduced(num: i64, denom: i64) -> Option<(i128, i128)> {
11    if denom == 0 {
12        return None;
13    }
14    let sign = if denom < 0 { -1 } else { 1 };
15    let (num, denom) = (i128::from(num) * sign, i128::from(denom).abs());
16    let divisor = crate::gcd(num.abs(), denom).max(1);
17    Some((num / divisor, denom / divisor))
18}
19
20/// Wire token for the nomiscript reader: the reduced `n` for a whole value,
21/// else `n/d` with the sign on `n`. `None` for a zero denominator.
22pub fn wire_token(num: i64, denom: i64) -> Option<String> {
23    let (num, denom) = reduced(num, denom)?;
24    Some(match denom {
25        1 => num.to_string(),
26        _ => format!("{num}/{denom}"),
27    })
28}
29
30/// Wire token of a `Rational64`; a zero-denominator ratio (constructible only
31/// unchecked) renders as `n/0`, which the reader rejects instead of misreading.
32pub fn wire_rational(value: Rational64) -> String {
33    let (num, denom) = (*value.numer(), *value.denom());
34    wire_token(num, denom).unwrap_or_else(|| format!("{num}/{denom}"))
35}
36
37/// Display text of `num/denom`: the exact decimal or fraction, falling back
38/// to the wire token (`n/0` for a zero denominator).
39pub fn display(num: i64, denom: i64) -> String {
40    format_amount(i128::from(num), denom)
41        .or_else(|| wire_token(num, denom))
42        .unwrap_or_else(|| format!("{num}/{denom}"))
43}
44
45fn strip_factor(mut value: i128, factor: i128) -> (i128, u32) {
46    let mut count = 0;
47    while value % factor == 0 {
48        value /= factor;
49        count += 1;
50    }
51    (value, count)
52}
53
54fn terminating_scale(denom: i128) -> Option<u32> {
55    let (rest, twos) = strip_factor(denom, 2);
56    let (rest, fives) = strip_factor(rest, 5);
57    (rest == 1).then_some(twos.max(fives))
58}
59
60/// Exact decimal of the reduced `num/denom` (`num >= 0`), with at least two
61/// places; `None` when the expansion does not terminate or overflows `i128`.
62fn exact_decimal(num: i128, denom: i128) -> Option<String> {
63    let scale = terminating_scale(denom)?.max(MIN_SCALE);
64    let unit = 10_i128.checked_pow(scale)?;
65    let scaled = num.checked_mul(unit)? / denom;
66    Some(format!(
67        "{}.{:0width$}",
68        scaled / unit,
69        scaled % unit,
70        width = scale as usize
71    ))
72}
73
74/// Renders `num/denom` so the amount parser reads back the same reduced
75/// value: the exact decimal when it terminates and the parser accepts it,
76/// otherwise the reduced fraction `a/b`. Never rounds. `None` for a zero
77/// denominator or a value the parser cannot hold.
78pub fn format_amount(num: i128, denom: i64) -> Option<String> {
79    if denom == 0 {
80        return None;
81    }
82    let negative = (num < 0) != (denom < 0);
83    let (num, denom) = (num.abs(), i128::from(denom).abs());
84    let divisor = crate::gcd(num, denom).max(1);
85    let (num, denom) = (num / divisor, denom / divisor);
86    let sign = if negative && num != 0 { "-" } else { "" };
87    let decimal = exact_decimal(num, denom).map(|d| format!("{sign}{d}"));
88    let fraction = format!("{sign}{num}/{denom}");
89    let signed = if sign.is_empty() { num } else { -num };
90    let expected = (i64::try_from(signed).ok()?, i64::try_from(denom).ok()?);
91    let reads_back = |text: &str| parse_amount(text) == Ok(expected);
92    decimal
93        .filter(|d| reads_back(d))
94        .or_else(|| Some(fraction).filter(|f| reads_back(f)))
95}