Skip to content

Commit

Permalink
Rollup merge of #50185 - dmizuk:mod_euc-fix-overflow, r=kennytm
Browse files Browse the repository at this point in the history
core: Fix overflow in `int::mod_euc` when `self < 0 && rhs == MIN`

This commit removes usage of `abs`, which overflows when `self == MIN`.
  • Loading branch information
kennytm committed Apr 24, 2018
2 parents 8d0c5da + 104c64d commit 893774e
Show file tree
Hide file tree
Showing 3 changed files with 11 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/libcore/num/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1765,7 +1765,11 @@ assert_eq!((-a).mod_euc(-b), 1);
pub fn mod_euc(self, rhs: Self) -> Self {
let r = self % rhs;
if r < 0 {
r + rhs.abs()
if rhs < 0 {
r - rhs
} else {
r + rhs
}
} else {
r
}
Expand Down
1 change: 1 addition & 0 deletions src/libcore/tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#![feature(core_private_diy_float)]
#![feature(dec2flt)]
#![feature(decode_utf8)]
#![feature(euclidean_division)]
#![feature(exact_size_is_empty)]
#![feature(fixed_size_array)]
#![feature(float_internals)]
Expand Down
5 changes: 5 additions & 0 deletions src/libcore/tests/num/int_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ mod tests {
num::test_num(10 as $T, 2 as $T);
}

#[test]
fn test_mod_euc() {
assert!((-1 as $T).mod_euc(MIN) == MAX);
}

#[test]
pub fn test_abs() {
assert!((1 as $T).abs() == 1 as $T);
Expand Down

0 comments on commit 893774e

Please sign in to comment.