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
use crate::{Currency, CurrencyLocale};
use std::ops::{Add, AddAssign, Sub};

impl<L, T> Add<T> for Currency<L>
where
    T: Into<Currency<L>>,
    L: CurrencyLocale + Default,
{
    type Output = Self;

    fn add(self, rhs: T) -> Self::Output {
        let rhs = rhs.into();
        if rhs.negative {
            self.sub(Self::new(false, rhs.full, rhs.part, rhs.locale))
        } else if self.negative {
            rhs.sub(Self::new(false, self.full, self.part, self.locale))
        } else {
            let new_part = self.part + rhs.part;
            let new_full = self.full + rhs.full + usize::from(new_part >= 100);
            Self::new(false, new_full, new_part % 100, self.locale)
        }
    }
}

impl<L, T> AddAssign<T> for Currency<L>
where
    T: Into<Currency<L>>,
    L: CurrencyLocale + Default + Clone,
{
    fn add_assign(&mut self, rhs: T) {
        let rhs = rhs.into();
        if rhs.negative {
            let new = self
                .clone()
                .sub(Self::new(false, rhs.full, rhs.part, rhs.locale));
            self.negative = new.negative;
            self.full = new.full;
            self.part = new.part;
        } else if self.negative {
            let new = rhs.sub(Self::new(false, self.full, self.part, L::default()));
            self.negative = new.negative;
            self.full = new.full;
            self.part = new.part;
        } else {
            let new_part = self.part + rhs.part;
            self.full += rhs.full + usize::from(new_part >= 100);
            self.part %= 100;
        }
    }
}