1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use std::ops;

use num_traits::ops::checked::{CheckedAdd, CheckedSub};
use serde::{Deserialize, Serialize};

#[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Deserialize, Serialize)]
pub struct Amount(u128);

impl From<u128> for Amount {
    fn from(value: u128) -> Self {
        Self(value)
    }
}

impl TryFrom<&str> for Amount {
    type Error = eyre::ErrReport;

    fn try_from(value: &str) -> Result<Self, Self::Error> {
        let amount = value.parse::<u128>()?;
        Ok(Amount(amount))
    }
}

impl ops::Add<Amount> for Amount {
    type Output = Amount;

    fn add(self, rhs: Amount) -> Self::Output {
        Self(self.0 + rhs.0)
    }
}

impl CheckedAdd for Amount {
    fn checked_add(&self, rhs: &Self) -> Option<Self> {
        self.0.checked_add(rhs.0).map(Self)
    }
}

impl ops::Sub<Amount> for Amount {
    type Output = Amount;

    fn sub(self, rhs: Amount) -> Self::Output {
        Self(self.0 - rhs.0)
    }
}

impl CheckedSub for Amount {
    fn checked_sub(&self, rhs: &Self) -> Option<Self> {
        self.0.checked_sub(rhs.0).map(Self)
    }
}

#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;

    use super::*;

    #[test]
    fn amount_try_from() {
        assert!(Amount::try_from("not-a-number").is_err());
        assert_eq!(Amount::try_from("1000").unwrap(), Amount(1000));
    }
}