Detecting overflow-checks

I'm using #[cfg(debug_assertions)] to switch some extra safety asserts in debug builds. But do you know if there's a #[cfg(...)] to enable something (verified numerical casts) even in release builds compiled with "-C overflow-checks"?

1 Like

If I understand you, I think in the toml file you do

overflow-checks = true

per here

1 Like

I've asked if there's something like #[cfg(...)] to put inside the Rust code to enable/disable some code when the compiler is performing the overflow checks (that happen in debug builds or in release builds that are compiled with "-C overflow-checks" added).

1 Like

Ok, you mean locally. Not as far as I know, but you can use things like checked_mul if you just want checking in specific places?

Unfortunately the code I'd like to disable/enable is relative to numerical casts, not about numerical operations. I'd like this #[cfg(...)] because I'd like to test those casts every time the compiler is performing the overflow checks too :slight_smile: (And I don't want to perform those tests when the compiler isn't inserting the overflow checks).
If there isn't such cfg, then I think it should exists. Unless someone tell me why it shouldn't exist :slight_smile:


Hmm not sure I understand, for casts you can just check the value to see if it is in range?

Yes, that's a way to test a cast. There are other ways, even built in ones (like using try_into, etc). The problem I have isn't how to perform such tests, but how to enable such tests when the program is compiled in debug builds or in release builds that also use "-C overflow-checks". And how to disable such code when the code is compiled in release builds that lack the "-C overflow-checks". "disabling" and "enabling" in the sense like "#[cfg(not(debug_assertions))]" that can be used to disable code in release builds.

Heh, a kind of hacky way to do this, but which in practice ought to work quite often, is to try and perform an overflow operation within a script, and see if it panics. Emit a cfg based on that:

fn main ()
    if ::std::panic::catch_unwind(|| {
        let _ = 255_u8 + 1;
        // `cfg(overflow_checks)`
    } // else `not(cfg(overflow_checks))`

Thank you Yandros, that's neat

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.