rustc_serialize/
int_overflow.rs

1// This would belong to `rustc_data_structures`, but `rustc_serialize` needs it too.
2
3/// Addition, but only overflow checked when `cfg(debug_assertions)` is set
4/// instead of respecting `-Coverflow-checks`.
5///
6/// This exists for performance reasons, as we ship rustc with overflow checks.
7/// While overflow checks are perf neutral in almost all of the compiler, there
8/// are a few particularly hot areas where we don't want overflow checks in our
9/// dist builds. Overflow is still a bug there, so we want overflow check for
10/// builds with debug assertions.
11///
12/// That's a long way to say that this should be used in areas where overflow
13/// is a bug but overflow checking is too slow.
14pub trait DebugStrictAdd {
15    /// See [`DebugStrictAdd`].
16    fn debug_strict_add(self, other: Self) -> Self;
17}
18
19macro_rules! impl_debug_strict_add {
20    ($( $ty:ty )*) => {
21        $(
22            impl DebugStrictAdd for $ty {
23                #[inline]
24                fn debug_strict_add(self, other: Self) -> Self {
25                    if cfg!(debug_assertions) {
26                        self + other
27                    } else {
28                        self.wrapping_add(other)
29                    }
30                }
31            }
32        )*
33    };
34}
35
36/// See [`DebugStrictAdd`].
37pub trait DebugStrictSub {
38    /// See [`DebugStrictAdd`].
39    fn debug_strict_sub(self, other: Self) -> Self;
40}
41
42macro_rules! impl_debug_strict_sub {
43    ($( $ty:ty )*) => {
44        $(
45            impl DebugStrictSub for $ty {
46                #[inline]
47                fn debug_strict_sub(self, other: Self) -> Self {
48                    if cfg!(debug_assertions) {
49                        self - other
50                    } else {
51                        self.wrapping_sub(other)
52                    }
53                }
54            }
55        )*
56    };
57}
58
59impl_debug_strict_add! {
60    u8 u16 u32 u64 u128 usize
61    i8 i16 i32 i64 i128 isize
62}
63
64impl_debug_strict_sub! {
65    u8 u16 u32 u64 u128 usize
66    i8 i16 i32 i64 i128 isize
67}