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
52
53
54
55
/// Overflowing operations.
pub trait OverflowingOps: Sized {
/// Calculates `self` + `rhs`
///
/// Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would
/// occur. If an overflow would have occurred then the wrapped value is returned.
fn overflowing_add(self, rhs: Self) -> (Self, bool);
/// Calculates `self` - `rhs`
///
/// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow
/// would occur. If an overflow would have occurred then the wrapped value is returned.
fn overflowing_sub(self, rhs: Self) -> (Self, bool);
/// Calculates the multiplication of `self` and `rhs`.
///
/// Returns a tuple of the multiplication along with a boolean indicating whether an arithmetic overflow
/// would occur. If an overflow would have occurred then the wrapped value is returned.
fn overflowing_mul(self, rhs: Self) -> (Self, bool);
/// Calculates the divisor when `self` is divided by `rhs`.
///
/// Returns a tuple of the divisor along with a boolean indicating whether an arithmetic overflow would
/// occur. If an overflow would occur then self is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is 0.
fn overflowing_div(self, rhs: Self) -> (Self, bool);
/// Calculates the remainder when `self` is divided by `rhs`.
///
/// Returns a tuple of the remainder after dividing along with a boolean indicating whether an
/// arithmetic overflow would occur. If an overflow would occur then 0 is returned.
///
/// # Panics
///
/// This function will panic if `rhs` is 0.
fn overflowing_rem(self, rhs: Self) -> (Self, bool);
}
/// Implements [`OverflowingOps`].
macro_rules! impl_overflowing {
($($t:ty),*) => {
$(impl OverflowingOps for $t {
#[inline] fn overflowing_add(self, rhs: Self) -> (Self, bool) { self.overflowing_add(rhs) }
#[inline] fn overflowing_sub(self, rhs: Self) -> (Self, bool) { self.overflowing_sub(rhs) }
#[inline] fn overflowing_mul(self, rhs: Self) -> (Self, bool) { self.overflowing_mul(rhs) }
#[inline] fn overflowing_div(self, rhs: Self) -> (Self, bool) { self.overflowing_div(rhs) }
#[inline] fn overflowing_rem(self, rhs: Self) -> (Self, bool) { self.overflowing_rem(rhs) }
})*
};
}
impl_overflowing!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);