Function unreachable_unchecked
unsafe const fn unreachable_unchecked() -> never
Informs the compiler that the site which is calling this function is not reachable, possibly enabling further optimizations.
Safety
Reaching this function is Undefined Behavior.
As the compiler assumes that all forms of Undefined Behavior can never
happen, it will eliminate all branches in the surrounding code that it can
determine will invariably lead to a call to unreachable_unchecked().
If the assumptions embedded in using this function turn out to be wrong -
that is, if the site which is calling unreachable_unchecked() is actually
reachable at runtime - the compiler may have generated nonsensical machine
instructions for this situation, including in seemingly unrelated code,
causing difficult-to-debug problems.
Use this function sparingly. Consider using the [unreachable!] macro,
which may prevent some optimizations but will safely panic in case it is
actually reached at runtime. Benchmark your code to find out if using
unreachable_unchecked() comes with a performance benefit.
Examples
unreachable_unchecked() can be used in situations where the compiler
can't prove invariants that were previously established. Such situations
have a higher chance of occurring if those invariants are upheld by
external code that the compiler can't analyze.
/// # Safety
/// All elements of `divisor` must be non-zero.
unsafe
let mut divisors = vec!;
prepare_inputs;
let result = unsafe ;
assert_eq!;
While using unreachable_unchecked() is perfectly sound in the following
example, as the compiler is able to prove that a division by zero is not
possible, benchmarking reveals that unreachable_unchecked() provides
no benefit over using [unreachable!], while the latter does not introduce
the possibility of Undefined Behavior.
assert_eq!;
assert_eq!;
assert_eq!;