How can integer overflow protection be turned off?

2019-06-27 13:12发布

My default Rust has integer overflow protect enabled, and will halt a program in execution on overflow. A large number of algorithms require overflow to function correctly (SHA1, SHA2, etc.)

2条回答
霸刀☆藐视天下
2楼-- · 2019-06-27 13:32

Use the Wrapping type, or use the wrapping functions directly. These disable the overflow checks. The Wrapping type allows you to use the normal operators as usual.

Also, when you compile your code in "release" mode (such as with cargo build --release), the overflow checks are omitted to improve performance. Do not rely on this though, use the above type or functions so that the code works even in debug builds.

查看更多
虎瘦雄心在
3楼-- · 2019-06-27 13:37

Francis Gagné's answer is absolutely the correct answer for your case. However, I will say that there is a compiler option to disable overflow checks. I don't see any reason to use it, but it exists and might as well be known about:

use std::u8;

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

Compiled and run:

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

$ rustc -Z force-overflow-checks=no overflow.rs
$ ./overflow
$
查看更多
登录 后发表回答