Skip to main content

lance_core/utils/
assume.rs

1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright The Lance Authors
3
4/// Assert an invariant that should also be visible to the optimizer.
5///
6/// Unlike [`debug_assert!`], this remains checked in release builds. This is
7/// required because the macro can be invoked from safe Rust and an invalid
8/// assumption must not become undefined behavior.
9#[macro_export]
10macro_rules! assume {
11    ($cond:expr) => {
12        assert!($cond)
13    };
14    ($cond:expr, $($arg:tt)+) => {
15        assert!($cond, $($arg)+)
16    };
17}
18
19/// Helper macro for equality assumptions.
20#[macro_export]
21macro_rules! assume_eq {
22    ($left:expr, $right:expr) => {
23        assert_eq!($left, $right)
24    };
25    ($left:expr, $right:expr, $($arg:tt)+) => {
26        assert_eq!($left, $right, $($arg)+)
27    };
28}
29
30#[cfg(test)]
31mod tests {
32    #[test]
33    fn assume_rejects_false_conditions() {
34        assert!(std::panic::catch_unwind(|| assume!(false)).is_err());
35        assert!(std::panic::catch_unwind(|| assume!(false, "invalid condition")).is_err());
36    }
37
38    #[test]
39    fn assume_eq_rejects_unequal_values() {
40        assert!(std::panic::catch_unwind(|| assume_eq!(1, 2)).is_err());
41        assert!(std::panic::catch_unwind(|| assume_eq!(1, 2, "invalid equality")).is_err());
42    }
43}