4 ms·
> ...does if you overflow normal arithmetic while debug assertions are on (if debug assertions are off, overflows result in wrapping instead). What I am readin
by chewxy 7y ago
> ...does if you overflow normal arithmetic while debug assertions are on (if debug assertions are off, overflows result in wrapping instead).
What I am reading from this is that in Rust, debug assertions cause a different semantics. That does not sound right at all.
- gpm 7y agoThat's... exactly right, it's the entire point. Assertions, check if a condition is true, and if it is false print an error message and exit the program. Assertions in rust are written `assert!(expr, optional_formatting_stuff)`. Debug assertions do the same, but they are only executed when the `debug_assertions` flag is passed to the compiler, typically for performance reasons. In C terms, a debug assert is basically `#ifdef DEBUG_ASSERRTIONS assert(foo) #endif`. Debug assertiosn in rust are written `debug_assert!(expression, optional_formatting_stuff)`. "Formally", arithmetic overflow in rust is defined to either wrap (as per 2s complement arithmetic) or panic. In todays compilers that means they perform 2s complement artihmetic when debug assertions are turned off, and they panic when it is turned on. If performance of checking for overflows improves in the future, it will be considered an acceptable (backwards compatible) change to always panic instead, but that would have too large a performance impact today.
- Yen 7y agoThe debug assertions can panic on code which has defined behavior in production, but behavior that's probably wrong, and probably would be asserted in production if it weren't too expensive. For example, if you do "u32::INTEGER_MAX + 3" in debug, it will panic, but in production code it will not (and will use the underlying CPU's result of "2") In most scenarios, this is not actually what you want. If your program has the possibility of doing arithmetic near or past the bounds, you should define the semantics you need. I.e., you can use one of saturating_add, wrapping_add, checked_add, or overflowing_add, depending on the semantics that are correct for your application. All of these behave the same between dev and prod.