[PATCH v7 03/10] rust: num: add nz! macro for compile time NonZero values

From
Eliot Courtney <hidden>
Date
2026-08-17 07:04:40
Also in
dri-devel, lkml, nova-gpu
Reply to
Eliot Courtney, 2026-08-17
Currently, using NonZero constants is quite verbose. It's unfortunate
because it disincentivizes using it in interface boundaries. Introduce a
macro to make it nicer to use.

Link: https://lore.kernel.org/DKO414SNC0B2.248FUBGJGSPLU@kernel.org (local)
Signed-off-by: Eliot Courtney <redacted>
---
 rust/kernel/num.rs | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)
diff --git a/rust/kernel/num.rs b/rust/kernel/num.rs
index 8532b511384c..055d23ca7fd1 100644
--- a/rust/kernel/num.rs
+++ b/rust/kernel/num.rs
@@ -7,6 +7,29 @@
 pub mod bounded;
 pub use bounded::*;
 
+/// Infallibly creates a [`NonZero`] value from a constant expression.
+///
+/// [`NonZero`]: core::num::NonZero
+///
+/// # Examples
+///
+/// ```
+/// use core::num::NonZero;
+/// use kernel::nz;
+///
+/// let v: NonZero<usize> = nz!(8);
+/// assert_eq!(v.get(), 8);
+///
+/// const N: NonZero<u32> = nz!(0x10);
+/// assert_eq!(N.get(), 0x10);
+/// ```
+#[macro_export]
+macro_rules! nz {
+    ($v:expr) => {
+        const { ::core::num::NonZero::new($v).unwrap() }
+    };
+}
+
 /// Designates unsigned primitive types.
 pub enum Unsigned {}
 
-- 
2.55.0
Thread (37 messages) 37 messages, 6 authors, last reply 2026-08-25
Keyboard shortcuts
hback out one level
jnext message in thread / next series-diff position
kprevious message in thread / previous series-diff position
ldrill in
Escclose help / fold thread tree
?toggle this help