Skip to main content

heika_wallet/
amount.rs

1//! 人が書いた量(`1.5` など)を、いちばん小さい単位の数にする。
2
3use std::fmt;
4
5/// 量を読めなかった
6#[derive(Clone, Copy, PartialEq, Eq, Debug)]
7pub enum AmountError {
8    /// 数字と小数点だけの形でない
9    Malformed,
10    /// 小数点の下が、可分性の桁より多い
11    TooManyDecimals { divisibility: u8 },
12    /// u64 に収まらない
13    TooLarge,
14}
15
16impl fmt::Display for AmountError {
17    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
18        match self {
19            Self::Malformed => f.write_str("1.5 のように、数字と小数点で書いてください"),
20            Self::TooManyDecimals { divisibility } => {
21                write!(f, "小数点の下は {divisibility} 桁までです")
22            }
23            Self::TooLarge => f.write_str("量が大きすぎます"),
24        }
25    }
26}
27
28impl std::error::Error for AmountError {}
29
30/// 可分性が `divisibility` のモザイクの量 `text` を、いちばん小さい単位の数にする。
31/// 符号、指数、桁の区切り、前後の空白は受け付けない
32pub fn parse(text: &str, divisibility: u8) -> Result<u64, AmountError> {
33    let (whole, fraction) = text.split_once('.').unwrap_or((text, ""));
34    let digits = |part: &str| part.bytes().all(|byte| byte.is_ascii_digit());
35    if whole.is_empty() || !digits(whole) || !digits(fraction) || text.ends_with('.') {
36        return Err(AmountError::Malformed);
37    }
38    let width = usize::from(divisibility);
39    if fraction.len() > width {
40        return Err(AmountError::TooManyDecimals { divisibility });
41    }
42    format!("{whole}{fraction:0<width$}")
43        .parse()
44        .map_err(|_| AmountError::TooLarge)
45}
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    #[test]
52    fn reads_amounts_in_the_smallest_unit() {
53        assert_eq!(parse("1.5", 6), Ok(1_500_000));
54        assert_eq!(parse("0.000001", 6), Ok(1));
55        assert_eq!(parse("12", 6), Ok(12_000_000));
56        assert_eq!(parse("0", 6), Ok(0));
57        assert_eq!(parse("7", 0), Ok(7));
58        for wrong in ["", ".5", "1.", "1.2.3", "-1", "1,000", " 1", "1e3"] {
59            assert_eq!(parse(wrong, 6), Err(AmountError::Malformed), "{wrong}");
60        }
61        assert_eq!(
62            parse("0.0000001", 6),
63            Err(AmountError::TooManyDecimals { divisibility: 6 })
64        );
65        assert_eq!(
66            parse("1.5", 0),
67            Err(AmountError::TooManyDecimals { divisibility: 0 })
68        );
69        assert_eq!(
70            parse("18446744073709.551616", 6),
71            Err(AmountError::TooLarge)
72        );
73    }
74}