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
// suppress `use_self` recommendation; unavoidable in macro context
#![allow(clippy::use_self)]

#[cfg(test)]
mod unit_tests;

pub trait Overflow<T = Self> {
    type Output;

    fn overflowing_abs(self) -> Self::Output;
    fn overflowing_add(self, rhs: T) -> Self::Output;
    fn overflowing_div(self, rhs: T) -> Self::Output;
    fn overflowing_div_euclid(self, rhs: T) -> Self::Output;
    fn overflowing_mul(self, rhs: T) -> Self::Output;
    fn overflowing_neg(self) -> Self::Output;
    fn overflowing_pow(self, rhs: u32) -> Self::Output;
    fn overflowing_rem(self, rhs: T) -> Self::Output;
    fn overflowing_rem_euclid(self, rhs: T) -> Self::Output;
    fn overflowing_shl(self, rhs: u32) -> Self::Output;
    fn overflowing_shr(self, rhs: u32) -> Self::Output;
    fn overflowing_sub(self, rhs: T) -> Self::Output;
}

macro_rules! overflowing_impl {
    ($($t:ty)*) => ($(
        impl Overflow for $t {
            type Output = (Self, bool);

            binary_op_impl! {
                $t,
                overflowing_add,
                overflowing_div,
                overflowing_div_euclid,
                overflowing_mul,
                overflowing_rem,
                overflowing_rem_euclid,
                overflowing_sub
            }

            binary_op_impl! {
                u32,
                overflowing_pow,
                overflowing_shl,
                overflowing_shr
            }

            unary_op_impl! {
                overflowing_abs,
                overflowing_neg
            }
        }
    )*)
}

overflowing_impl! { i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize }