ostd/util/macros.rs
1// SPDX-License-Identifier: MPL-2.0
2/// Asserts that a boolean expression is `true` at compile-time.
3///
4/// Rust provides [`const` blocks], which can be used flexibly within methods, but cannot be used
5/// directly at the top level. This macro serves as a helper to perform compile-time assertions
6/// outside of methods.
7///
8/// [`const` blocks]: https://doc.rust-lang.org/reference/expressions/block-expr.html#const-blocks
9//
10// TODO: Introduce `const_assert_eq!()` once `assert_eq!()` can be used in the `const` context.
11#[macro_export]
12macro_rules! const_assert {
13 ($cond:expr $(,)?) => { const _: () = assert!($cond); };
14 ($cond:expr, $($arg:tt)+) => { const _: () = assert!($cond, $($arg)*); };
15}
16
17/// Creates a pointer whose type matches the expression, but whose value is always NULL.
18///
19/// This is a helper macro, typically used in another macro to help with type inference.
20///
21/// The expression is guaranteed never to be executed, so it can contain arbitrarily unsafe code
22/// without causing any soundness problems.
23#[macro_export]
24macro_rules! ptr_null_of {
25 ($expr:expr $(,)?) => {
26 if true {
27 core::ptr::null()
28 } else {
29 unreachable!();
30
31 // SAFETY: This is dead code and will never be executed.
32 //
33 // One may wonder: is it possible for the dead code to
34 // trigger UBs by simply being compiled, rather than being executed?
35 // More specifically, what if the caller attempts to
36 // trick the macro into defining unsafe language items,
37 // like static variables, functions, implementation blocks, or attributes,
38 // those that are not executed.
39 // Luckily for us, in such cases, the Rust compiler would complain that
40 // "items do not inherit unsafety from separate enclosing items".
41 #[expect(unreachable_code)]
42 unsafe {
43 $expr
44 }
45 }
46 };
47}