diff options
| author | Gary Guo <gary@garyguo.net> | 2026-03-19 12:16:46 +0000 |
|---|---|---|
| committer | Miguel Ojeda <ojeda@kernel.org> | 2026-03-30 02:03:49 +0200 |
| commit | 560a7a9b9267fbe31a68270ca0ad22b6a4db44a5 (patch) | |
| tree | fc1b22fd60a0e9a64a8e01ea42015a61df6dba64 /rust/kernel/build_assert.rs | |
| parent | abfe5ee9971249b91020b5053afcaad43837336a (diff) | |
| download | lwn-560a7a9b9267fbe31a68270ca0ad22b6a4db44a5.tar.gz lwn-560a7a9b9267fbe31a68270ca0ad22b6a4db44a5.zip | |
rust: add `const_assert!` macro
The macro is a more powerful version of `static_assert!` for use inside
function contexts. This is powered by inline consts, so enable the feature
for old compiler versions that does not have it stably.
While it is possible already to write `const { assert!(...) }`, this
provides a short hand that is more uniform with other assertions. It also
formats nicer with rustfmt where it will not be formatted into multiple
lines.
Two users that would route via the Rust tree are converted.
Reviewed-by: Yury Norov <ynorov@nvidia.com>
Signed-off-by: Gary Guo <gary@garyguo.net>
Reviewed-by: Alexandre Courbot <acourbot@nvidia.com>
Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Danilo Krummrich <dakr@kernel.org>
Link: https://patch.msgid.link/20260319121653.2975748-3-gary@kernel.org
[ Rebased. Fixed period typo. - Miguel ]
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
Diffstat (limited to 'rust/kernel/build_assert.rs')
| -rw-r--r-- | rust/kernel/build_assert.rs | 24 |
1 files changed, 24 insertions, 0 deletions
diff --git a/rust/kernel/build_assert.rs b/rust/kernel/build_assert.rs index d464494d430a..50b0fc0a80fc 100644 --- a/rust/kernel/build_assert.rs +++ b/rust/kernel/build_assert.rs @@ -41,6 +41,30 @@ macro_rules! static_assert { }; } +/// Assertion during constant evaluation. +/// +/// This is a more powerful version of [`static_assert!`] that can refer to generics inside +/// functions or implementation blocks. However, it also has a limitation where it can only appear +/// in places where statements can appear; for example, you cannot use it as an item in the module. +/// +/// # Examples +/// +/// ``` +/// fn foo<const N: usize>() { +/// const_assert!(N > 1); +/// } +/// +/// fn bar<T>() { +/// const_assert!(size_of::<T>() > 0, "T cannot be ZST"); +/// } +/// ``` +#[macro_export] +macro_rules! const_assert { + ($condition:expr $(,$arg:literal)?) => { + const { ::core::assert!($condition $(,$arg)?) }; + }; +} + /// Fails the build if the code path calling `build_error!` can possibly be executed. /// /// If the macro is executed in const context, `build_error!` will panic. |
