1
//! Display and wire renderings of an exact amount.
2

            
3
use num_rational::Rational64;
4

            
5
use crate::parse_amount;
6

            
7
const MIN_SCALE: u32 = 2;
8

            
9
/// Reduced `(num, denom)` with a positive denominator; `None` for a zero one.
10
164727
fn reduced(num: i64, denom: i64) -> Option<(i128, i128)> {
11
164727
    if denom == 0 {
12
2
        return None;
13
164725
    }
14
164725
    let sign = if denom < 0 { -1 } else { 1 };
15
164725
    let (num, denom) = (i128::from(num) * sign, i128::from(denom).abs());
16
164725
    let divisor = crate::gcd(num.abs(), denom).max(1);
17
164725
    Some((num / divisor, denom / divisor))
18
164727
}
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.
22
164727
pub fn wire_token(num: i64, denom: i64) -> Option<String> {
23
164727
    let (num, denom) = reduced(num, denom)?;
24
164725
    Some(match denom {
25
132708
        1 => num.to_string(),
26
32017
        _ => format!("{num}/{denom}"),
27
    })
28
164727
}
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.
32
152292
pub fn wire_rational(value: Rational64) -> String {
33
152292
    let (num, denom) = (*value.numer(), *value.denom());
34
152292
    wire_token(num, denom).unwrap_or_else(|| format!("{num}/{denom}"))
35
152292
}
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).
39
223880
pub fn display(num: i64, denom: i64) -> String {
40
223880
    format_amount(i128::from(num), denom)
41
2
        .or_else(|| wire_token(num, denom))
42
1
        .unwrap_or_else(|| format!("{num}/{denom}"))
43
223880
}
44

            
45
514144
fn strip_factor(mut value: i128, factor: i128) -> (i128, u32) {
46
514144
    let mut count = 0;
47
569614
    while value % factor == 0 {
48
55470
        value /= factor;
49
55470
        count += 1;
50
    }
51
514144
    (value, count)
52
514144
}
53

            
54
257072
fn terminating_scale(denom: i128) -> Option<u32> {
55
257072
    let (rest, twos) = strip_factor(denom, 2);
56
257072
    let (rest, fives) = strip_factor(rest, 5);
57
257072
    (rest == 1).then_some(twos.max(fives))
58
257072
}
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`.
62
257072
fn exact_decimal(num: i128, denom: i128) -> Option<String> {
63
257072
    let scale = terminating_scale(denom)?.max(MIN_SCALE);
64
208612
    let unit = 10_i128.checked_pow(scale)?;
65
208443
    let scaled = num.checked_mul(unit)? / denom;
66
208395
    Some(format!(
67
208395
        "{}.{:0width$}",
68
208395
        scaled / unit,
69
208395
        scaled % unit,
70
208395
        width = scale as usize
71
208395
    ))
72
257072
}
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.
78
257074
pub fn format_amount(num: i128, denom: i64) -> Option<String> {
79
257074
    if denom == 0 {
80
2
        return None;
81
257072
    }
82
257072
    let negative = (num < 0) != (denom < 0);
83
257072
    let (num, denom) = (num.abs(), i128::from(denom).abs());
84
257072
    let divisor = crate::gcd(num, denom).max(1);
85
257072
    let (num, denom) = (num / divisor, denom / divisor);
86
257072
    let sign = if negative && num != 0 { "-" } else { "" };
87
257072
    let decimal = exact_decimal(num, denom).map(|d| format!("{sign}{d}"));
88
257072
    let fraction = format!("{sign}{num}/{denom}");
89
257072
    let signed = if sign.is_empty() { num } else { -num };
90
257072
    let expected = (i64::try_from(signed).ok()?, i64::try_from(denom).ok()?);
91
257072
    let reads_back = |text: &str| parse_amount(text) == Ok(expected);
92
257070
    decimal
93
208394
        .filter(|d| reads_back(d))
94
48678
        .or_else(|| Some(fraction).filter(|f| reads_back(f)))
95
257074
}