oasis_types/
balance.rs

1#[derive(
2    Clone,
3    Copy,
4    Debug,
5    Default,
6    Eq,
7    Hash,
8    Ord,
9    PartialEq,
10    PartialOrd,
11    Display,
12    LowerHex,
13    UpperHex,
14    FromStr,
15    From,
16    Into,
17    Add,
18    Div,
19    Mul,
20    Rem,
21    Sub,
22    AddAssign,
23    DivAssign,
24    MulAssign,
25    RemAssign,
26    SubAssign,
27    oasis_borsh::BorshSerialize,
28    oasis_borsh::BorshDeserialize,
29)]
30#[repr(C)]
31pub struct Balance(pub u128);
32
33impl Balance {
34    // Alias for `mem::size_of::<Balance>()`.
35    pub const fn size() -> usize {
36        std::mem::size_of::<Self>()
37    }
38}
39
40macro_rules! impl_interop_with_prims {
41    ($($prim:ty),+) => {
42        $(
43            impl PartialEq<$prim> for Balance {
44                fn eq(&self, prim: &$prim) -> bool {
45                    use std::convert::TryFrom;
46                    u128::try_from(*prim).map(|p| p == self.0).unwrap_or_default()
47                }
48            }
49
50            impl PartialOrd<$prim> for Balance {
51                fn partial_cmp(&self, prim: &$prim) -> Option<std::cmp::Ordering> {
52                    use std::convert::TryFrom;
53                    u128::try_from(*prim).ok().map(|p| self.0.cmp(&p))
54                }
55            }
56        )+
57    }
58}
59
60impl_interop_with_prims!(u8, i8, u16, i16, u32, i32, u64, i64, u128, i128);
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    #[test]
67    fn test_add() {
68        let mut bal = Balance::from(3);
69        assert_eq!(bal - Balance::from(2), Balance::from(1));
70        bal += 1u128.into();
71        assert_eq!(bal, 4)
72    }
73
74    #[test]
75    fn test_mul() {
76        let mut bal = Balance::from(3);
77        bal *= 2;
78        assert_eq!(u128::from(bal), 6u128);
79        assert_eq!(bal % 4, Balance(2));
80        assert_eq!(bal / 4, 1);
81    }
82
83    #[test]
84    fn test_from_str() {
85        use std::str::FromStr;
86        assert!(Balance::from_str(&u128::max_value().to_string()).unwrap() == u128::max_value());
87    }
88
89    #[test]
90    fn test_cmp() {
91        assert!(Balance(1) < 2);
92        assert!(Balance(1) == 1);
93    }
94}