Skip to main content

vildrose_core/word/
arithmetic.rs

1use super::{CheckedDiv, Tryte, Word, Word27, Word54};
2use crate::ops::ripple_add;
3use crate::trit::Trit;
4use core::ops;
5
6impl<const N: usize> ops::Add for Word<N> {
7    type Output = Self;
8
9    fn add(self, rhs: Self) -> Self::Output {
10        Self(ripple_add(self.0, rhs.0))
11    }
12}
13
14impl<const N: usize> ops::Sub for Word<N> {
15    type Output = Self;
16
17    fn sub(self, rhs: Self) -> Self::Output {
18        self + -rhs
19    }
20}
21
22impl<const N: usize> ops::Mul for Word<N> {
23    type Output = Self;
24
25    fn mul(self, rhs: Self) -> Self::Output {
26        let mut product = Self::zero();
27
28        for (shift, trit) in rhs.0.iter().copied().enumerate() {
29            let partial = self.tshl(shift);
30
31            product = match trit {
32                Trit::N => product - partial,
33                Trit::Z => product,
34                Trit::P => product + partial,
35            };
36        }
37
38        product
39    }
40}
41
42impl CheckedDiv for Tryte {
43    type Output = Self;
44
45    fn checked_div(self, rhs: Self) -> Option<Self> {
46        if rhs == Self::zero() {
47            return None;
48        }
49
50        Self::from_int(self.to_int() / rhs.to_int()).ok()
51    }
52}
53
54impl CheckedDiv for Word27 {
55    type Output = Self;
56
57    fn checked_div(self, rhs: Self) -> Option<Self> {
58        if rhs == Self::zero() {
59            return None;
60        }
61
62        Self::from_int(self.to_int() / rhs.to_int()).ok()
63    }
64}
65
66impl CheckedDiv for Word54 {
67    type Output = Self;
68
69    fn checked_div(self, rhs: Self) -> Option<Self> {
70        if rhs == Self::zero() {
71            return None;
72        }
73
74        Self::from_int(self.to_int() / rhs.to_int()).ok()
75    }
76}
77
78impl ops::Div for Tryte {
79    type Output = Self;
80
81    fn div(self, rhs: Self) -> Self::Output {
82        self.checked_div(rhs)
83            .unwrap_or_else(|| panic!("Tryte: division by zero"))
84    }
85}
86
87impl ops::Div for Word27 {
88    type Output = Self;
89
90    fn div(self, rhs: Self) -> Self::Output {
91        self.checked_div(rhs)
92            .unwrap_or_else(|| panic!("Word27: division by zero"))
93    }
94}
95
96impl ops::Div for Word54 {
97    type Output = Self;
98
99    fn div(self, rhs: Self) -> Self::Output {
100        self.checked_div(rhs)
101            .unwrap_or_else(|| panic!("Word54: division by zero"))
102    }
103}