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"?
If I understand you, I think in the toml file you do
[profile.release]
overflow-checks = true
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).
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 (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
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 build.rs
script, and see if it panics. Emit a cfg based on that:
//! build.rs
fn main ()
{
if ::std::panic::catch_unwind(|| {
#[allow(arithmetic_overflow)]
let _ = 255_u8 + 1;
}).is_err()
{
// `cfg(overflow_checks)`
println!("cargo:rustc-cfg=overflow_checks");
} // else `not(cfg(overflow_checks))`
}
Thank you Yandros, that's neat
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.