fraction/decimal/ops/
sub.rs

1use crate::generic::GenericInteger;
2use crate::GenericDecimal;
3use std::cmp;
4use std::ops::Sub;
5
6impl<O, T, P> Sub<O> for GenericDecimal<T, P>
7where
8    T: Clone + GenericInteger,
9    P: Copy + GenericInteger + Into<usize>,
10    O: Into<GenericDecimal<T, P>>,
11{
12    type Output = Self;
13
14    fn sub(self, other: O) -> Self::Output {
15        let other: GenericDecimal<T, P> = other.into();
16
17        match self {
18            GenericDecimal(sf, sp) => match other {
19                GenericDecimal(of, op) => GenericDecimal(Sub::sub(sf, of), cmp::max(sp, op)),
20            },
21        }
22    }
23}
24
25impl<'a, T, P> Sub for &'a GenericDecimal<T, P>
26where
27    T: Clone + GenericInteger,
28    P: Copy + GenericInteger + Into<usize>,
29    &'a T: Sub<Output = T>,
30{
31    type Output = GenericDecimal<T, P>;
32
33    fn sub(self, other: Self) -> Self::Output {
34        match self {
35            GenericDecimal(sf, sp) => match other {
36                GenericDecimal(of, op) => GenericDecimal(Sub::sub(sf, of), cmp::max(*sp, *op)),
37            },
38        }
39    }
40}
41
42impl<'a, O, T, P> Sub<O> for &'a GenericDecimal<T, P>
43where
44    T: Clone + GenericInteger,
45    P: Copy + GenericInteger + Into<usize>,
46    &'a T: Sub<Output = T>,
47    O: Into<GenericDecimal<T, P>>,
48{
49    type Output = GenericDecimal<T, P>;
50
51    fn sub(self, other: O) -> Self::Output {
52        let other: GenericDecimal<T, P> = other.into();
53
54        match self {
55            GenericDecimal(sf, sp) => match other {
56                GenericDecimal(of, op) => GenericDecimal(Sub::sub(sf, of), cmp::max(*sp, op)),
57            },
58        }
59    }
60}
61
62#[cfg(test)]
63mod tests {
64    use crate::{GenericDecimal, One, Zero};
65
66    type F = GenericDecimal<u8, u8>;
67
68    #[test]
69    fn sub_scalar() {
70        assert_eq!(F::one() - 1, F::zero());
71        assert_eq!(F::one() - 0.5, F::from(0.5));
72
73        assert_eq!(&F::one() - 1, F::zero());
74        assert_eq!(&F::one() - 0.5, F::from(0.5));
75
76        assert_eq!(F::one() - F::from(1), F::zero());
77        assert_eq!(F::one() - F::from(0.5), F::from(0.5));
78
79        assert_eq!(&F::one() - &F::from(1), F::zero());
80        assert_eq!(&F::one() - &F::from(0.5), F::from(0.5));
81    }
82}