How can integer overflow protection be turned off?

时光怂恿深爱的人放手 提交于 2019-12-10 16:06:23

问题


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.)


回答1:


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.




回答2:


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
$


来源:https://stackoverflow.com/questions/31215139/how-can-integer-overflow-protection-be-turned-off

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!