decimal_wad/
common.rs

1use std::convert::TryFrom;
2
3use crate::error::*;
4
5/// Scale of precision
6pub const SCALE: usize = 18;
7/// Identity
8pub const WAD: u64 = 1_000_000_000_000_000_000;
9/// Half of identity
10pub const HALF_WAD: u64 = 500_000_000_000_000_000;
11/// Scale for percentages
12pub const PERCENT_SCALER: u64 = 10_000_000_000_000_000;
13
14/// Scale for bips (100 bp = 1 percent)
15pub const BPS_SCALER: u64 = PERCENT_SCALER / 100;
16
17// For code generated by the macros
18#[allow(clippy::assign_op_pattern)]
19#[allow(clippy::ptr_offset_with_cast)]
20#[allow(clippy::reversed_empty_ranges)]
21#[allow(clippy::manual_range_contains)]
22pub mod uint {
23    use super::*;
24    use ::uint::construct_uint;
25
26    construct_uint! {
27        /// U192 with 192 bits consisting of 3 x 64-bit words
28        pub struct U192(3);
29    }
30
31    construct_uint! {
32        /// U128 with 128 bits consisting of 2 x 64-bit words
33        pub struct U128(2);
34    }
35
36    impl From<U128> for U192 {
37        fn from(value: U128) -> U192 {
38            let U128(ref arr) = value;
39            let mut ret = [0; 3];
40            ret[0] = arr[0];
41            ret[1] = arr[1];
42            U192(ret)
43        }
44    }
45
46    impl TryFrom<U192> for U128 {
47        type Error = DecimalError;
48
49        fn try_from(value: U192) -> Result<U128, DecimalError> {
50            let U192(ref arr) = value;
51            if arr[2] != 0 {
52                return Err(DecimalError::MathOverflow);
53            }
54            let mut ret = [0; 2];
55            ret[0] = arr[0];
56            ret[1] = arr[1];
57            Ok(U128(ret))
58        }
59    }
60}
61
62/// Try to subtract, return an error on underflow
63pub trait TrySub: Sized {
64    /// Subtract
65    fn try_sub(self, rhs: Self) -> Result<Self, DecimalError>;
66}
67
68/// Try to subtract, return an error on overflow
69pub trait TryAdd: Sized {
70    /// Add
71    fn try_add(self, rhs: Self) -> Result<Self, DecimalError>;
72}
73
74/// Try to divide, return an error on overflow or divide by zero
75pub trait TryDiv<RHS>: Sized {
76    /// Divide
77    fn try_div(self, rhs: RHS) -> Result<Self, DecimalError>;
78}
79
80/// Try to multiply, return an error on overflow
81pub trait TryMul<RHS>: Sized {
82    /// Multiply
83    fn try_mul(self, rhs: RHS) -> Result<Self, DecimalError>;
84}