Write assertions that clarify code to both the readers of the code and to the compiler with assert_unchecked

36 points Sebass13

Hi everyone, I've made a crate, assert_unchecked, that uses the unsafe unreachable_unchecked to hint at optimizations to the compiler. In practice this can mean removing bounds checks and cold paths, which can also mean the hot path can be further optimized. Of course, this means that any use of the macros in this crate must have an associated safety argument, as the assertions failing will cause UB. Here's an example of the usage:

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]

I'd love to build up a bigger list of examples, so if you can find a place where adding in any of these assertions changes the output assembly, please let me know!