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
51
pub trait SafeAdd {
fn safe_add(self, o: Self) -> Self;
fn safe_inc(&mut self, o: Self);
}
macro_rules! safeadd_integer_impl {
($trait_name:ident for $($t:ty)*) => {$(
impl $trait_name for $t {
#[inline]
fn safe_add(self, o: Self) -> Self {
self.saturating_add(o)
}
#[inline]
fn safe_inc(&mut self, o: Self) {
*self = self.saturating_add(o)
}
}
)*}
}
macro_rules! safeadd_float_impl {
($trait_name:ident for $($t:ty)*) => {$(
impl $trait_name for $t {
#[inline]
fn safe_add(self, o: Self) -> Self {
self + o
}
#[inline]
fn safe_inc(&mut self, o: Self) {
*self += o
}
}
)*}
}
safeadd_integer_impl!(SafeAdd for isize usize i8 u8 i16 u16 i32 u32 i64 u64);
#[cfg(has_i128)]
safeadd_integer_impl!(SafeAdd for i128 u128);
safeadd_float_impl!(SafeAdd for f32 f64);