How can I disable integer overflow protection?

By default, Rust has integer overflow protection turned on and stops program execution when it overflows. A large number of algorithms require overflow for proper operation (SHA1, SHA2, etc.)

+4
source share
2 answers

Use Wrappingor use wrapper functions directly. They disable overflow checking. The type Wrappingallows you to use regular operators as usual.

In addition, when you compile your code in release mode (for example, using cargo build --release), overflow checks are excluded to improve performance. Do not rely on this, but use the above type or functions to make the code work even in debug builds.

+4
source

Answer Francis Gagné is the right answer for your case. However, I will say that there is a compiler option to disable overflow checking. I see no reason to use it, but it exists and may also be known:

use std::u8;

fn main() {
    u8::MAX + u8::MAX;
}

Compiled and launched:

$ rustc overflow.rs
$ ./overflow
thread '<main>' panicked at 'arithmetic operation overflowed', overflow.rs:4

$ rustc -Z force-overflow-checks=no overflow.rs
$ ./overflow
$
+1
source

All Articles