assert_unchecked

Macro assert_ne_unchecked

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

Asserts that two expressions are not equal to each other (using PartialEq).

In builds with debug-assertions enabled, this will function equivalent to assert_ne. However, in an optimized build without debug_assertions enabled, this assertion serves as an optimization hint; the inequality check 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_ne, or if assertions are undesired in optimized code, use debug_assert_ne.

§Example

use assert_unchecked::{assert_unchecked, assert_ne_unchecked};
// Modifies `a[0]` and `a[delta]`, and then returns `a[0]`.
// delta must be non-zero and delta < a.len().
// This also means that all bounds checks can be removed.
unsafe fn modify_start_and_delta(a: &mut [u8], delta: usize) -> u8 {
    // SAFETY: requirements are invariants of the unsafe function.
    assert_unchecked!(delta < a.len());
    // With this assertion, we know that a[delta] does not modify a[0],
    // which means the function can optimize the return value to always be 0.
    assert_ne_unchecked!(delta, 0);
    a[0] = 0;
    a[delta] = 1;
    a[0]
}