]> git.ipfire.org Git - thirdparty/kernel/stable.git/commitdiff
rust: static_assert: add optional message
authorAltan Ozlu <altan@ozlu.eu>
Wed, 26 Mar 2025 20:25:36 +0000 (20:25 +0000)
committerMiguel Ojeda <ojeda@kernel.org>
Sun, 11 May 2025 22:20:25 +0000 (00:20 +0200)
Add an optional panic message to the `static_assert!` macro.

The panic message doesn't support argument formatting, because the
`assert!` macro only supports formatting in non-const contexts.

Suggested-by: Miguel Ojeda <ojeda@kernel.org>
Link: https://github.com/Rust-for-Linux/linux/issues/1149
Signed-off-by: Altan Ozlu <altan@ozlu.eu>
Reviewed-by: Benno Lossin <benno.lossin@proton.me>
Reviewed-by: Trevor Gross <tmgross@umich.edu>
Link: https://lore.kernel.org/r/20250326202520.1176162-2-altan@ozlu.eu
Signed-off-by: Miguel Ojeda <ojeda@kernel.org>
rust/kernel/static_assert.rs

index 3115ee0ba8e9d7a412b2a0734a5c52ef21c1cfa8..d8120f838260f87db067c691223c2983836bdbf7 100644 (file)
@@ -6,6 +6,10 @@
 ///
 /// Similar to C11 [`_Static_assert`] and C++11 [`static_assert`].
 ///
+/// An optional panic message can be supplied after the expression.
+/// Currently only a string literal without formatting is supported
+/// due to constness limitations of the [`assert!`] macro.
+///
 /// The feature may be added to Rust in the future: see [RFC 2790].
 ///
 /// [`_Static_assert`]: https://en.cppreference.com/w/c/language/_Static_assert
 ///     x + 2
 /// }
 /// static_assert!(f(40) == 42);
+/// static_assert!(f(40) == 42, "f(x) must add 2 to the given input.");
 /// ```
 #[macro_export]
 macro_rules! static_assert {
-    ($condition:expr) => {
-        const _: () = core::assert!($condition);
+    ($condition:expr $(,$arg:literal)?) => {
+        const _: () = core::assert!($condition $(,$arg)?);
     };
 }