macro_rules! assert_eq_unchecked {
($left:expr, $right:expr) => { ... };
($left:expr, $right:expr, $($arg:tt)*) => { ... };
}
Expand description
Asserts that two expressions are equal to each other (using PartialEq
).
In builds with debug-assertions
enabled, this will function equivalent to
assert_eq
. However, in an optimized build without debug_assertions
enabled, this assertion serves as an optimization hint; the equality 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_eq
, or if assertions are
undesired in optimized code, use debug_assert_eq
.
§Example
use assert_unchecked::assert_eq_unchecked;
fn get_last(len: usize) -> usize {
if len == 0 {
return 0;
}
let mut v = vec![0];
for i in 1..len {
v.push(i)
}
// SAFETY: `len` elements have been added to v at this point
// Without this line, the compiler isn't smart enough to remove the bounds check
unsafe { assert_eq_unchecked!(len, v.len()) };
v[len - 1]
}