assert_unchecked

Macro assert_unchecked

Source
macro_rules! assert_unchecked {
    ($cond:expr) => { ... };
    ($expr:expr, $($arg:tt)*) => { ... };
}
Expand description

Asserts that a boolean expression is true at runtime.

In builds with debug-assertions enabled, this will function equivalent to assert. However, in an optimized build without debug_assertions enabled, this assertion serves as an optimization hint; the boolean expression itself will likely not appear in the generated code, but instead will be assumed in a way that allows for optimizing the surrounding code.

§Safety

In release mode, the assertion failing is completely undefined behavior (UB). Since the compiler assumes that all UB must never happen, it may use the assumption that this assertion is true to optimize other sections of the code.

If this assumption turns out to be wrong, i.e. the assertion can fail in practice, the compiler will apply the wrong optimization strategy, and may sometimes even corrupt seemingly unrelated code, causing difficult-to-debug problems.

Use this function only when you can prove that the assertion will never be false. Otherwise, consider just using assert, or if assertions are undesired in optimized code, use debug_assert.

§Example

use assert_unchecked::assert_unchecked;
fn copy(from_arr: &[u8], to_arr: &mut [u8]) {
    assert_eq!(from_arr.len(), to_arr.len());
    for i in 0..to_arr.len() {
        // SAFETY: bounds of to_arr is checked outside of loop
        // Without this line, the compiler isn't smart enough to remove the bounds check
        unsafe { assert_unchecked!(i <= to_arr.len()) };
        to_arr[i] = from_arr[i];
    }
}