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
/// Checked operations.
pub trait CheckedOps: Sized {
/// Checked integer addition. Computes `self + rhs`, returning `None`
/// if overflow occurred.
fn checked_add(self, rhs: Self) -> Option<Self>;
/// Checked integer subtraction. Computes `self - rhs`, returning `None` if
/// overflow occurred.
fn checked_sub(self, rhs: Self) -> Option<Self>;
/// Checked integer multiplication. Computes `self * rhs`, returning `None` if
/// overflow occurred.
fn checked_mul(self, rhs: Self) -> Option<Self>;
/// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0`
/// or the division results in overflow.
fn checked_div(self, rhs: Self) -> Option<Self>;
/// Checked integer remainder. Computes `self % rhs`, returning `None` if
/// `rhs == 0` or the division results in overflow.
fn checked_rem(self, rhs: Self) -> Option<Self>;
}
/// Implements [`CheckedOps`].
macro_rules! impl_checked {
($($t:ty),*) => {
$(impl CheckedOps for $t {
#[inline] fn checked_add(self, rhs: Self) -> Option<Self> { self.checked_add(rhs) }
#[inline] fn checked_sub(self, rhs: Self) -> Option<Self> { self.checked_sub(rhs) }
#[inline] fn checked_mul(self, rhs: Self) -> Option<Self> { self.checked_mul(rhs) }
#[inline] fn checked_div(self, rhs: Self) -> Option<Self> { self.checked_div(rhs) }
#[inline] fn checked_rem(self, rhs: Self) -> Option<Self> { self.checked_rem(rhs) }
})*
};
}
impl_checked!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);