Skip to content

Commit

Permalink
Merge #45
Browse files Browse the repository at this point in the history
45: Fix prev/next_multiple_of(&MIN, &-1) r=cuviper a=cuviper

Closes #43.

Co-authored-by: Josh Stone <cuviper@gmail.com>
  • Loading branch information
bors[bot] and cuviper committed Mar 21, 2022
2 parents d839ba5 + cde58ee commit a7d40a1
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions src/lib.rs
Expand Up @@ -560,6 +560,29 @@ macro_rules! impl_integer_for_isize {
fn div_rem(&self, other: &Self) -> (Self, Self) {
(*self / *other, *self % *other)
}

/// Rounds up to nearest multiple of argument.
#[inline]
fn next_multiple_of(&self, other: &Self) -> Self {
// Avoid the overflow of `MIN % -1`
if *other == -1 {
return *self;
}

let m = Integer::mod_floor(self, other);
*self + if m == 0 { 0 } else { other - m }
}

/// Rounds down to nearest multiple of argument.
#[inline]
fn prev_multiple_of(&self, other: &Self) -> Self {
// Avoid the overflow of `MIN % -1`
if *other == -1 {
return *self;
}

*self - Integer::mod_floor(self, other)
}
}

#[cfg(test)]
Expand Down Expand Up @@ -782,6 +805,16 @@ macro_rules! impl_integer_for_isize {
assert_eq!((3 as $T).is_odd(), true);
assert_eq!((4 as $T).is_odd(), false);
}

#[test]
fn test_multiple_of_one_limits() {
for x in &[<$T>::min_value(), <$T>::max_value()] {
for one in &[1, -1] {
assert_eq!(Integer::next_multiple_of(x, one), *x);
assert_eq!(Integer::prev_multiple_of(x, one), *x);
}
}
}
}
};
}
Expand Down

0 comments on commit a7d40a1

Please sign in to comment.