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

Eliot Courtney <[email protected]>
Newsgroups dev.linux.lists.nova-gpu,org.freedesktop.lists.dri-devel,org.kernel.vger.linux-kernel,org.kernel.vger.rust-for-linux
Message-ID <[email protected]>
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/[email protected]
Signed-off-by: Eliot Courtney <[email protected]>
---
 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
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.