lance_core/utils/assume.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright The Lance Authors
3
4/// A macro that combines debug_assert and std::hint::assert_unchecked for optimized assertions
5///
6/// In debug builds, this will perform a normal assertion check.
7/// In release builds, this will use hint::assert_unchecked which tells the compiler to assume
8/// the condition is true without actually checking it.
9///
10/// # Safety
11///
12/// This macro is unsafe in release builds since it uses hint::assert_unchecked.
13/// The caller must ensure the condition will always be true.
14#[macro_export]
15macro_rules! assume {
16 ($cond:expr) => {
17 debug_assert!($cond);
18 // SAFETY: The debug_assert ensures this is true in debug builds.
19 // In release builds, caller must ensure the condition holds.
20 unsafe { std::hint::assert_unchecked($cond); }
21 };
22 ($cond:expr, $($arg:tt)+) => {
23 debug_assert!($cond, $($arg)+);
24 // SAFETY: The debug_assert ensures this is true in debug builds.
25 // In release builds, caller must ensure the condition holds.
26 unsafe { std::hint::assert_unchecked($cond); }
27 };
28}
29
30/// Helper macro for equality assumptions.
31#[macro_export]
32macro_rules! assume_eq {
33 ($left:expr, $right:expr) => {
34 debug_assert_eq!($left, $right);
35 unsafe { std::hint::assert_unchecked($left == $right); }
36 };
37 ($left:expr, $right:expr, $($arg:tt)+) => {
38 debug_assert_eq!($left, $right, $($arg)+);
39 unsafe { std::hint::assert_unchecked($left == $right); }
40 };
41}