1
//! The one amount grammar of the transaction forms.
2
//!
3
//! An amount is a decimal (`10.5`, `-3`, `+.25`) or an exact fraction
4
//! `a/b` (optional sign on `a`, positive integer `b`). It parses into a
5
//! reduced `(numerator, denominator)` pair of `i64`, with no floating point.
6

            
7
use std::fmt;
8

            
9
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
10
pub enum AmountError {
11
    Empty,
12
    Syntax,
13
    ZeroDenominator,
14
    Overflow,
15
}
16

            
17
impl fmt::Display for AmountError {
18
1360
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19
1360
        f.write_str(match self {
20
1
            Self::Empty => "empty amount",
21
1359
            Self::Syntax => "expected a decimal like 10.5 or a fraction like 1/3",
22
            Self::ZeroDenominator => "zero denominator",
23
            Self::Overflow => "amount is too large or too precise",
24
        })
25
1360
    }
26
}
27

            
28
impl std::error::Error for AmountError {}
29

            
30
673003
fn digits_value(digits: &str) -> Result<i128, AmountError> {
31
2602125
    digits.bytes().try_fold(0_i128, |acc, byte| {
32
2602125
        acc.checked_mul(10)
33
2602123
            .and_then(|v| v.checked_add(i128::from(byte - b'0')))
34
2602125
            .ok_or(AmountError::Overflow)
35
2602125
    })
36
673003
}
37

            
38
1155391
fn all_digits(text: &str) -> bool {
39
3145551
    text.bytes().all(|b| b.is_ascii_digit())
40
1155391
}
41

            
42
578188
fn split_sign(text: &str) -> (bool, &str) {
43
578188
    match text.as_bytes().first() {
44
47241
        Some(b'-') => (true, &text[1..]),
45
3
        Some(b'+') => (false, &text[1..]),
46
530944
        _ => (false, text),
47
    }
48
578188
}
49

            
50
96588
fn parse_fraction(num: &str, den: &str) -> Result<(i128, i128), AmountError> {
51
96588
    let (negative, digits) = split_sign(num);
52
96588
    if digits.is_empty() || !all_digits(digits) || den.is_empty() || !all_digits(den) {
53
7
        return Err(AmountError::Syntax);
54
96581
    }
55
96581
    let denom = digits_value(den)?;
56
96580
    if denom == 0 {
57
1
        return Err(AmountError::ZeroDenominator);
58
96579
    }
59
96579
    let magnitude = digits_value(digits)?;
60
96579
    Ok((if negative { -magnitude } else { magnitude }, denom))
61
96588
}
62

            
63
481600
fn parse_decimal(text: &str) -> Result<(i128, i128), AmountError> {
64
481600
    let (negative, unsigned) = split_sign(text);
65
481600
    let (int_part, frac_part) = unsigned.split_once('.').unwrap_or((unsigned, ""));
66
481600
    let has_digit = !int_part.is_empty() || !frac_part.is_empty();
67
481600
    if !has_digit || !all_digits(int_part) || !all_digits(frac_part) {
68
1756
        return Err(AmountError::Syntax);
69
479844
    }
70
479844
    let frac_part = frac_part.trim_end_matches('0');
71
479844
    let scale = u32::try_from(frac_part.len()).map_err(|_| AmountError::Overflow)?;
72
479844
    let denom = 10_i128.checked_pow(scale).ok_or(AmountError::Overflow)?;
73
479843
    let magnitude = digits_value(&format!("{int_part}{frac_part}"))?;
74
479842
    Ok((if negative { -magnitude } else { magnitude }, denom))
75
481600
}
76

            
77
3860803
fn gcd(a: i128, b: i128) -> i128 {
78
3860803
    if b == 0 { a.abs() } else { gcd(b, a % b) }
79
3860803
}
80

            
81
/// Reduces `num/denom` by their gcd and narrows it to `i64`; `denom` must be
82
/// positive. Fails with `Overflow` when either part does not fit, or the
83
/// numerator is `i64::MIN`.
84
576426
pub fn reduce_to_i64(num: i128, denom: i128) -> Result<(i64, i64), AmountError> {
85
576426
    let divisor = gcd(num, denom).max(1);
86
576426
    let num = i64::try_from(num / divisor).map_err(|_| AmountError::Overflow)?;
87
576424
    let denom = i64::try_from(denom / divisor).map_err(|_| AmountError::Overflow)?;
88
576423
    if num == i64::MIN {
89
6
        return Err(AmountError::Overflow);
90
576417
    }
91
576417
    Ok((num, denom))
92
576426
}
93

            
94
/// Parses an amount into a reduced `(numerator, denominator)`; the
95
/// denominator is positive and the numerator is never `i64::MIN`.
96
578190
pub fn parse_amount(text: &str) -> Result<(i64, i64), AmountError> {
97
578190
    let text = text.trim();
98
578190
    if text.is_empty() {
99
2
        return Err(AmountError::Empty);
100
578188
    }
101
578188
    let (num, denom) = match text.split_once('/') {
102
96588
        Some((num, den)) => parse_fraction(num.trim_end(), den.trim_start())?,
103
481600
        None => parse_decimal(text)?,
104
    };
105
576421
    reduce_to_i64(num, denom)
106
578190
}
107

            
108
mod display;
109
pub use display::{display, format_amount, wire_rational, wire_token};
110

            
111
#[cfg(test)]
112
mod display_tests;
113
#[cfg(test)]
114
mod tests;