Skip to content

Commit 893774e

Browse files
authored
Rollup merge of rust-lang#50185 - dmizuk:mod_euc-fix-overflow, r=kennytm
core: Fix overflow in `int::mod_euc` when `self < 0 && rhs == MIN` This commit removes usage of `abs`, which overflows when `self == MIN`.
2 parents 8d0c5da + 104c64d commit 893774e

File tree

3 files changed

+11
-1
lines changed

3 files changed

+11
-1
lines changed

src/libcore/num/mod.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -1765,7 +1765,11 @@ assert_eq!((-a).mod_euc(-b), 1);
17651765
pub fn mod_euc(self, rhs: Self) -> Self {
17661766
let r = self % rhs;
17671767
if r < 0 {
1768-
r + rhs.abs()
1768+
if rhs < 0 {
1769+
r - rhs
1770+
} else {
1771+
r + rhs
1772+
}
17691773
} else {
17701774
r
17711775
}

src/libcore/tests/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
#![feature(core_private_diy_float)]
1717
#![feature(dec2flt)]
1818
#![feature(decode_utf8)]
19+
#![feature(euclidean_division)]
1920
#![feature(exact_size_is_empty)]
2021
#![feature(fixed_size_array)]
2122
#![feature(float_internals)]

src/libcore/tests/num/int_macros.rs

+5
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,11 @@ mod tests {
3030
num::test_num(10 as $T, 2 as $T);
3131
}
3232

33+
#[test]
34+
fn test_mod_euc() {
35+
assert!((-1 as $T).mod_euc(MIN) == MAX);
36+
}
37+
3338
#[test]
3439
pub fn test_abs() {
3540
assert!((1 as $T).abs() == 1 as $T);

0 commit comments

Comments
 (0)