assert-unchecked
Unsafe assertions that allow for optimizations in release mode.
These macros use core::hint::unreachable_unchecked
, which make it possible to write assertions that simultaneously clarify code as well as hint at optimizations to LLVM.
Usage
Add this to your Cargo.toml
[dependencies]
assert_unchecked = "0.1.2"
Examples
use assert_unchecked::{
assert_eq_unchecked, assert_ne_unchecked, assert_unchecked, unreachable_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() {
unsafe { assert_unchecked!(i <= to_arr.len()) };
to_arr[i] = from_arr[i];
}
}
fn get_last(len: usize) -> usize {
if len == 0 {
return 0;
}
let mut v = vec![0];
for i in 1..len {
v.push(i)
}
unsafe { assert_eq_unchecked!(len, v.len()) };
v[len - 1]
}
unsafe fn modify_start_and_delta(a: &mut [u8], delta: usize) -> u8 {
assert_unchecked!(delta < a.len());
assert_ne_unchecked!(delta, 0);
a[0] = 0;
a[delta] = 1;
a[0]
}
fn div_1(a: u32, b: u32) -> u32 {
a.checked_div(b.saturating_add(1))
.unwrap_or_else(|| unsafe { unreachable_unchecked!("division by zero isn't possible") })
}