Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is left-shifting a negative value undefined behavior in Rust?

Several operations on integers that yield undefined behavior in C are defined in Rust. A common theme is that they panic in debug mode and have a defined non-panic outcome in release mode. For example, signed integer overflow panics in debug mode, but wraps in release mode. There are also operator variants defined like wrapping_add(), saturating_add(), etc.

But what about shifting a negative value? This is undefined behavior in C.

The following test case succeeds in Rust 1.17.0:

#[test]
fn negative_shift() {
    let i = -128i8;
    let j = i << 1;
    assert_eq!(j, 0);
}

Although it succeeds it could still be undefined behavior...

like image 487
maxschlepzig Avatar asked Oct 30 '22 08:10

maxschlepzig


1 Answers

The Rust Reference has a list of all undefined behavior. Left shifting a signed number beyond the size of the type is not in the list.

like image 86
Shepmaster Avatar answered Dec 31 '22 01:12

Shepmaster