【发布时间】:2021-12-18 17:20:09
【问题描述】:
我的默认 Rust 启用了整数溢出保护,并且会在溢出时停止正在执行的程序。大量算法需要溢出才能正常运行(SHA1、SHA2 等)
【问题讨论】:
我的默认 Rust 启用了整数溢出保护,并且会在溢出时停止正在执行的程序。大量算法需要溢出才能正常运行(SHA1、SHA2 等)
【问题讨论】:
使用Wrapping 类型,或直接使用wrapping functions。这些禁用溢出检查。 Wrapping 类型允许您照常使用普通运算符。
此外,当您在“发布”模式下编译代码时(例如使用cargo build --release),会省略溢出检查以提高性能。不过不要依赖于此,使用上述类型或函数,这样代码即使在调试版本中也能正常工作。
【讨论】:
Francis Gagné's answer 绝对是您的情况的正确答案,但有一个编译器选项可以禁用溢出检查。我看不出有任何使用它的理由,但它确实存在并且可能会为人所知:
#![allow(arithmetic_overflow)]
fn main() {
dbg!(u8::MAX + u8::MAX);
}
在你的profile section中设置这个:
[profile.dev]
overflow-checks = false
% cargo run -q
[src/main.rs:6] u8::MAX + u8::MAX = 254
rustc
使用-C overflow-checks 命令行选项:
% rustc overflow.rs -C overflow-checks=off
% ./overflow
[overflow.rs:6] u8::MAX + u8::MAX = 254
【讨论】:
cargo rustc -- -Z force-overflow-checks=no,即使在稳定版上也是如此。
#![allow(arithmetic_overflow)] 并没有防止我使用它时因乘法溢出而引起的恐慌。我最终使用了x.wrapping_mul(y)。
对于那些来自未来的人,即使你在 release 模式编译 src,rust 会检查算术溢出。
➜ ~ cargo new overflow_test --vcs='none'
Created binary (application) `overflow_test` package
➜ ~ cd overflow_test
➜ overflow_test vim src/main.rs
➜ overflow_test cat src/main.rs
fn main() {
let mut max: i32 = i32::MAX;
max += 1;
}
➜ overflow_test cargo run --release
Compiling overflow_test v0.1.0 (/home/steve/overflow_test)
// two warnings are omitted
error: this arithmetic operation will overflow
--> src/main.rs:3:5
|
3 | max += 1;
| ^^^^^^^^ attempt to compute `i32::MAX + 1_i32`, which would overflow
|
= note: `#[deny(arithmetic_overflow)]` on by default
warning: `overflow_test` (bin "overflow_test") generated 2 warnings
error: could not compile `overflow_test` due to previous error; 2 warnings emitted
【讨论】: