Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wrapping add #9

Merged
merged 11 commits into from
Sep 25, 2023
24 changes: 24 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -792,6 +792,30 @@ macro_rules! impl_ranged {
<Self as $crate::traits::RangeIsValid>::ASSERT;
Self::new_saturating(self.get().saturating_pow(exp))
}

/// Wrapping integer addition. Computes `self + rhs`, wrapping around the numeric
/// bounds.
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
pub fn wrapping_add(self, rhs: $internal) -> Self {
Easyoakland marked this conversation as resolved.
Show resolved Hide resolved
<Self as $crate::traits::RangeIsValid>::ASSERT;
Easyoakland marked this conversation as resolved.
Show resolved Hide resolved
let inner = self.get();
let range_len = Self::MAX.get().abs_diff(Self::MIN.get()) + 1;
Easyoakland marked this conversation as resolved.
Show resolved Hide resolved
let offset = rhs.rem_euclid(range_len.try_into().expect("Length of valid range is greater than the largest value in the type"));
let greater_vals = Self::MAX.get() - inner;
// No wrap
if offset <= greater_vals {
// Safety: offset <= greater_vals. No overflow.
unsafe { Self::new_unchecked(inner + offset) }
}
// Wrap
else {
// Safety:
// - offset < range_len by rem_euclid (MIN + ... safe)
// - offset > greater_values from if statement (offset - (greater_values + 1) safe)
unsafe { Self::new_unchecked(Self::MIN.get() + (offset - (greater_vals + 1))) }
}
}
}

impl<const MIN: $internal, const MAX: $internal> $optional_type<MIN, MAX> {
Expand Down
12 changes: 12 additions & 0 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,18 @@ macro_rules! tests {
assert_eq!($t::<5, 10>::MAX.saturating_add(1), $t::<5, 10>::MAX);
)*}

#[test]
fn wrapping_add() {$(
Easyoakland marked this conversation as resolved.
Show resolved Hide resolved
assert_eq!($t::<5, 10>::MAX.wrapping_add(0), $t::<5, 10>::MAX);
assert_eq!($t::<5, 10>::MAX.wrapping_add(1), $t::<5, 10>::MIN);
)*
$(if_signed! { $signed
assert_eq!($t::<-5, 10>::MAX.wrapping_add(0), $t::<-5, 10>::MAX);
assert_eq!($t::<-5, 10>::MAX.wrapping_add(1), $t::<-5, 10>::MIN);
assert_eq!($t::<-5, 10>::MIN.wrapping_add(-1), $t::<-5, 10>::MAX);
})*
}

#[test]
fn saturating_sub() {$(
assert_eq!($t::<5, 10>::MIN.saturating_sub(0), $t::<5, 10>::MIN);
Expand Down