dharitri_sc/types/managed/wrapped/managed_decimal/
managed_decimal_op_add.rs

1use crate::{
2    api::ManagedTypeApi,
3    typenum::Unsigned,
4    types::{ConstDecimals, Decimals, ManagedDecimal, NumDecimals},
5};
6
7use core::ops::{Add, AddAssign};
8
9impl<M: ManagedTypeApi, D1: Decimals, D2: Decimals> AddAssign<&ManagedDecimal<M, D2>>
10    for ManagedDecimal<M, D1>
11{
12    fn add_assign(&mut self, rhs: &ManagedDecimal<M, D2>) {
13        let scaled_data = rhs.rescale_data(self.scale().num_decimals());
14        self.data += scaled_data;
15    }
16}
17
18impl<M: ManagedTypeApi, D1: Decimals, D2: Decimals> AddAssign<ManagedDecimal<M, D2>>
19    for ManagedDecimal<M, D1>
20{
21    #[inline]
22    fn add_assign(&mut self, rhs: ManagedDecimal<M, D2>) {
23        self.add_assign(&rhs);
24    }
25}
26
27// const + const
28impl<M: ManagedTypeApi, DECIMALS: Unsigned> Add<ManagedDecimal<M, ConstDecimals<DECIMALS>>>
29    for ManagedDecimal<M, ConstDecimals<DECIMALS>>
30{
31    type Output = Self;
32
33    fn add(mut self, rhs: ManagedDecimal<M, ConstDecimals<DECIMALS>>) -> Self::Output {
34        self.data += rhs.data;
35        self
36    }
37}
38
39// var + var
40impl<M: ManagedTypeApi> Add<ManagedDecimal<M, NumDecimals>> for ManagedDecimal<M, NumDecimals> {
41    type Output = Self;
42
43    fn add(mut self, rhs: ManagedDecimal<M, NumDecimals>) -> Self::Output {
44        match self.decimals.cmp(&rhs.decimals) {
45            core::cmp::Ordering::Less => {
46                self = self.rescale(rhs.decimals);
47                self.data += rhs.data;
48            },
49            core::cmp::Ordering::Equal => self.data += rhs.data,
50            core::cmp::Ordering::Greater => {
51                let rhs_data = rhs.rescale_data(self.decimals);
52                self.data += rhs_data;
53            },
54        }
55        self
56    }
57}
58
59// var + const
60impl<DECIMALS: Unsigned, M: ManagedTypeApi> Add<ManagedDecimal<M, ConstDecimals<DECIMALS>>>
61    for ManagedDecimal<M, NumDecimals>
62{
63    type Output = ManagedDecimal<M, NumDecimals>;
64
65    fn add(self, rhs: ManagedDecimal<M, ConstDecimals<DECIMALS>>) -> Self::Output {
66        self + rhs.into_var_decimals()
67    }
68}
69
70// const + var
71impl<DECIMALS: Unsigned, M: ManagedTypeApi> Add<ManagedDecimal<M, NumDecimals>>
72    for ManagedDecimal<M, ConstDecimals<DECIMALS>>
73{
74    type Output = ManagedDecimal<M, NumDecimals>;
75
76    fn add(self, rhs: ManagedDecimal<M, NumDecimals>) -> Self::Output {
77        self.into_var_decimals() + rhs
78    }
79}