defuse_num_utils/
add_sub.rs

1pub trait CheckedAdd<RHS = Self>: Sized {
2    fn checked_add(self, rhs: RHS) -> Option<Self>;
3}
4
5pub trait CheckedSub<RHS = Self>: Sized {
6    fn checked_sub(self, rhs: RHS) -> Option<Self>;
7}
8
9macro_rules! impl_checked_add {
10    ($unsigned:ty, $signed:ty) => {
11        impl CheckedAdd for $unsigned {
12            #[inline]
13            fn checked_add(self, rhs: Self) -> Option<Self> {
14                self.checked_add(rhs)
15            }
16        }
17
18        impl CheckedAdd<$signed> for $unsigned {
19            #[inline]
20            fn checked_add(self, rhs: $signed) -> Option<Self> {
21                self.checked_add_signed(rhs)
22            }
23        }
24
25        impl CheckedAdd for $signed {
26            #[inline]
27            fn checked_add(self, rhs: Self) -> Option<Self> {
28                self.checked_add(rhs)
29            }
30        }
31
32        impl CheckedAdd<$unsigned> for $signed {
33            #[inline]
34            fn checked_add(self, rhs: $unsigned) -> Option<Self> {
35                self.checked_add_unsigned(rhs)
36            }
37        }
38    };
39}
40
41macro_rules! impl_checked_sub {
42    ($unsigned:ty, $signed:ty) => {
43        impl CheckedSub for $unsigned {
44            #[inline]
45            fn checked_sub(self, rhs: Self) -> Option<Self> {
46                self.checked_sub(rhs)
47            }
48        }
49
50        impl CheckedSub for $signed {
51            #[inline]
52            fn checked_sub(self, rhs: Self) -> Option<Self> {
53                self.checked_sub(rhs)
54            }
55        }
56
57        impl CheckedSub<$unsigned> for $signed {
58            #[inline]
59            fn checked_sub(self, rhs: $unsigned) -> Option<Self> {
60                self.checked_sub_unsigned(rhs)
61            }
62        }
63    };
64}
65
66macro_rules! impl_checked {
67    ($unsigned:ty, $signed:ty) => {
68        impl_checked_add!($unsigned, $signed);
69        impl_checked_sub!($unsigned, $signed);
70    };
71}
72impl_checked!(u8, i8);
73impl_checked!(u16, i16);
74impl_checked!(u32, i32);
75impl_checked!(u64, i64);
76impl_checked!(u128, i128);