【问题标题】:How can integer overflow protection be turned off?如何关闭整数溢出保护?
【发布时间】:2021-12-18 17:20:09
【问题描述】:

我的默认 Rust 启用了整数溢出保护,并且会在溢出时停止正在执行的程序。大量算法需要溢出才能正常运行(SHA1、SHA2 等)

【问题讨论】:

    标签: integer overflow rust


    【解决方案1】:

    使用Wrapping 类型,或直接使用wrapping functions。这些禁用溢出检查。 Wrapping 类型允许您照常使用普通运算符。

    此外,当您在“发布”模式下编译代码时(例如使用cargo build --release),会省略溢出检查以提高性能。不过不要依赖于此,使用上述类型或函数,这样代码即使在调试版本中也能正常工作。

    【讨论】:

    • 为了兼容性,请注意一些包装函数直到 1.2.0 才稳定,但是 Wrapping 类型已经可以使用了。
    【解决方案2】:

    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 中使用此标志:cargo rustc -- -Z force-overflow-checks=no,即使在稳定版上也是如此。
    • 使用#![allow(arithmetic_overflow)] 并没有防止我使用它时因乘法溢出而引起的恐慌。我最终使用了x.wrapping_mul(y)
    • 源代码中的属性和编译选项(使用 cargo 或 rustc)都需要禁用溢出保护。
    【解决方案3】:

    对于那些来自未来的人,即使你在 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
    

    【讨论】:

    • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
    • 另外,您提供的链接并没有链接到任何特定的游乐场,您需要点击右上角的“分享”按钮并复制第一个链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 2018-02-19
    • 2013-06-25
    • 2012-07-31
    相关资源
    最近更新 更多