Skip to content

Commit 2a05f77

Browse files
committed
std: Make abs() panic on overflow in debug mode
Debug overflow checks for arithmetic negation landed in #24500, at which time the `abs` method on signed integers was changed to using `wrapping_neg` to ensure that the function never panicked. This implied that `abs` of `INT_MIN` would return `INT_MIN`, another negative value. When this change was back-ported to beta, however, in #24708, the `wrapping_neg` function had not yet been backported, so the implementation was changed in #24785 to `!self + 1`. This change had the unintended side effect of enabling debug overflow checks for the `abs` function. Consequently, the current state of affairs is that the beta branch checks for overflow in debug mode for `abs` and the nightly branch does not. This commit alters the behavior of nightly to have `abs` always check for overflow in debug mode. This change is more consistent with the way the standard library treats overflow as well, and it is also not a breaking change as it's what the beta branch currently does (albeit if by accident). cc #25378
1 parent af52207 commit 2a05f77

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

src/libcore/num/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -569,7 +569,7 @@ macro_rules! int_impl {
569569
#[inline]
570570
pub fn abs(self) -> $T {
571571
if self.is_negative() {
572-
self.wrapping_neg()
572+
-self
573573
} else {
574574
self
575575
}

src/test/run-pass/int-abs-overflow.rs

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// compile-flags: -Z force-overflow-checks=on
12+
13+
use std::thread;
14+
15+
fn main() {
16+
assert!(thread::spawn(|| i8::min_value().abs()).join().is_err());
17+
assert!(thread::spawn(|| i16::min_value().abs()).join().is_err());
18+
assert!(thread::spawn(|| i32::min_value().abs()).join().is_err());
19+
assert!(thread::spawn(|| i64::min_value().abs()).join().is_err());
20+
assert!(thread::spawn(|| isize::min_value().abs()).join().is_err());
21+
}

0 commit comments

Comments
 (0)