Skip to content

Commit e2b0b85

Browse files
authored
Merge pull request #101 from Rust-for-Linux/rust-static_assert
libkernel: add `static_assert!` macro
2 parents 9f45abb + a28bd00 commit e2b0b85

File tree

3 files changed

+40
-1
lines changed

3 files changed

+40
-1
lines changed

rust/kernel/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ pub mod module_param;
4040
pub mod prelude;
4141
pub mod printk;
4242
pub mod random;
43+
mod static_assert;
4344

4445
#[cfg(CONFIG_SYSCTL)]
4546
pub mod sysctl;

rust/kernel/prelude.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,4 +15,4 @@ pub use alloc::{borrow::ToOwned, string::String};
1515

1616
pub use module::module;
1717

18-
pub use super::{println, KernelModule, KernelResult};
18+
pub use super::{println, static_assert, KernelModule, KernelResult};

rust/kernel/static_assert.rs

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
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] == 'a' as u8);
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+
// Based on the latest one in `rustc`'s one before it was [removed].
33+
//
34+
// [removed]: https://github.com/rust-lang/rust/commit/c2dad1c6b9f9636198d7c561b47a2974f5103f6d
35+
#[allow(dead_code)]
36+
const _: () = [()][!($condition) as usize];
37+
};
38+
}

0 commit comments

Comments
 (0)