num-traits icon indicating copy to clipboard operation
num-traits copied to clipboard

Implementation of Signed::abs is not correct in regard to the doc

Open gui1117 opened this issue 6 years ago • 1 comments

doc is: https://github.com/rust-num/num-traits/blob/d394467906aab26065b5e518f4449aa982c6dcb1/src/sign.rs#L13-L14

but implementation is https://github.com/rust-num/num-traits/blob/d394467906aab26065b5e518f4449aa982c6dcb1/src/sign.rs#L48-L50

the implementation doesn't return MIN but actually panic with overflow, see:

fn abs(t: &i32) -> i32 {
    if t.is_negative() { -*t } else { *t }
}

fn main() {
    println!("{}", abs(&i32::min_value()))
}

gui1117 avatar Sep 27 '19 13:09 gui1117

It's actually more nuanced than that, because in release mode overflow silently wraps. We should probably be forwarding this implementation to std anyway, and the docs there explain:

The absolute value of i32::min_value() cannot be represented as an i32, and attempting to calculate it will cause an overflow. This means that code in debug mode will trigger a panic on this case and optimized code will return i32::min_value() without a panic.

cuviper avatar Sep 27 '19 17:09 cuviper