Skip to content

Commit ef9e379

Browse files
committed
rust: static_assert: add static_assert! macro
Add the `static_assert!` macro, which is a compile-time assert, similar to the C11 `_Static_assert` and C++11 `static_assert` declarations [1,2]. Do so in a new module, called `static_assert`. For instance: static_assert!(42 > 24); static_assert!(core::mem::size_of::<u8>() == 1); const X: &[u8] = b"bar"; static_assert!(X[1] == b'a'); const fn f(x: i32) -> i32 { x + 2 } static_assert!(f(40) == 42); Link: https://en.cppreference.com/w/c/language/_Static_assert [1] Link: https://en.cppreference.com/w/cpp/language/static_assert [2] Co-developed-by: Alex Gaynor <[email protected]> Signed-off-by: Alex Gaynor <[email protected]> Signed-off-by: Miguel Ojeda <[email protected]>
1 parent bee1688 commit ef9e379

File tree

3 files changed

+37
-0
lines changed

3 files changed

+37
-0
lines changed

Diff for: rust/kernel/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ mod allocator;
2626
pub mod error;
2727
pub mod prelude;
2828
pub mod print;
29+
mod static_assert;
2930
#[doc(hidden)]
3031
pub mod std_vendor;
3132
pub mod str;

Diff for: rust/kernel/prelude.rs

+2
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ pub use macros::{module, vtable};
1919

2020
pub use super::{dbg, pr_alert, pr_crit, pr_debug, pr_emerg, pr_err, pr_info, pr_notice, pr_warn};
2121

22+
pub use super::static_assert;
23+
2224
pub use super::error::{code::*, Error, Result};
2325

2426
pub use super::{str::CStr, ThisModule};

Diff for: rust/kernel/static_assert.rs

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
// SPDX-License-Identifier: GPL-2.0
2+
3+
//! Static assert.
4+
5+
/// Static assert (i.e. compile-time assert).
6+
///
7+
/// Similar to C11 [`_Static_assert`] and C++11 [`static_assert`].
8+
///
9+
/// The feature may be added to Rust in the future: see [RFC 2790].
10+
///
11+
/// [`_Static_assert`]: https://en.cppreference.com/w/c/language/_Static_assert
12+
/// [`static_assert`]: https://en.cppreference.com/w/cpp/language/static_assert
13+
/// [RFC 2790]: https://github.com/rust-lang/rfcs/issues/2790
14+
///
15+
/// # Examples
16+
///
17+
/// ```
18+
/// static_assert!(42 > 24);
19+
/// static_assert!(core::mem::size_of::<u8>() == 1);
20+
///
21+
/// const X: &[u8] = b"bar";
22+
/// static_assert!(X[1] == b'a');
23+
///
24+
/// const fn f(x: i32) -> i32 {
25+
/// x + 2
26+
/// }
27+
/// static_assert!(f(40) == 42);
28+
/// ```
29+
#[macro_export]
30+
macro_rules! static_assert {
31+
($condition:expr) => {
32+
const _: () = core::assert!($condition);
33+
};
34+
}

0 commit comments

Comments
 (0)