sa/
lib.rs

1//! Simple `static_assert` macro for compile time  assertions
2//!
3//! Uses `const_panic` within `const` variable to produce compile error hence only usable in `const` context.
4//!
5//! ## Usage
6//!
7//! ```rust
8//! use sa::static_assert;
9//!
10//! static_assert!(1 == 1);
11//! static_assert!(1 == 1, "Must be equal");
12//! ```
13//!
14//! ```compile_fail
15//! use sa::static_assert;
16//!
17//! static_assert!(0 == 1, "Must be equal"); //should fail
18//! ```
19//!
20//! ```compile_fail
21//! use sa::static_assert;
22//!
23//! static_assert!(0 == 1); //should fail
24//! ```
25#![no_std]
26
27#[macro_export]
28///If expression evaluates to `true`, this macro has no effect.
29///
30///Otherwise a compile-time error is issued via panic.
31///
32///## Arguments:
33///
34///- `exp` - expression to evaluate. Result of expression must be `bool`
35///- `msg` - optional string literal to add to the error message.
36macro_rules! static_assert {
37    ($exp:expr) => {
38        #[deny(const_err)]
39        #[allow(unused_must_use)]
40        const _: () = {
41            if !($exp) {
42                core::panic!(core::concat!("Static assertion '", core::stringify!($exp), "' failed"));
43            }
44
45            ()
46        };
47    };
48    ($exp:expr, $msg:literal) => {
49        #[deny(const_err)]
50        #[allow(unused_must_use)]
51        const _: () = {
52            if !($exp) {
53                core::panic!(core::concat!("Static assertion '", core::stringify!($exp), "' failed: ", $msg));
54            }
55
56            ()
57        };
58    };
59}