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