[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-Id: <20250620-num-v1-2-7ec3d3fb06c9@nvidia.com>
Date: Fri, 20 Jun 2025 22:14:52 +0900
From: Alexandre Courbot <acourbot@...dia.com>
To: Miguel Ojeda <ojeda@...nel.org>, Alex Gaynor <alex.gaynor@...il.com>,
Boqun Feng <boqun.feng@...il.com>, Gary Guo <gary@...yguo.net>,
Björn Roy Baron <bjorn3_gh@...tonmail.com>,
Benno Lossin <lossin@...nel.org>, Andreas Hindborg <a.hindborg@...nel.org>,
Alice Ryhl <aliceryhl@...gle.com>, Trevor Gross <tmgross@...ch.edu>,
Danilo Krummrich <dakr@...nel.org>
Cc: linux-kernel@...r.kernel.org, rust-for-linux@...r.kernel.org,
nouveau@...ts.freedesktop.org, Alexandre Courbot <acourbot@...dia.com>
Subject: [PATCH 2/3] rust: num: add the `last_set_bit` operation
Add an equivalent to the `fls` (Find Last Set bit) C function to Rust
unsigned types.
It is to be first used by the nova-core driver.
Signed-off-by: Alexandre Courbot <acourbot@...dia.com>
---
rust/kernel/num.rs | 38 ++++++++++++++++++++++++++++++++++++++
1 file changed, 38 insertions(+)
diff --git a/rust/kernel/num.rs b/rust/kernel/num.rs
index 6ecff037893dd25420a6369ea0cd6adbe3460b29..95766201a7cf208989f37ecbc6d54d264385a754 100644
--- a/rust/kernel/num.rs
+++ b/rust/kernel/num.rs
@@ -161,3 +161,41 @@ pub const fn align_up(self, value: $t) -> $t {
}
power_of_two_impl!(usize, u8, u16, u32, u64, u128);
+
+macro_rules! impl_last_set_bit {
+ ($($t:ty),+) => {
+ $(
+ ::kernel::macros::paste! {
+ /// Last Set Bit: return the 1-based index of the last (i.e. most significant) set bit
+ /// in `v`.
+ ///
+ /// Equivalent to the C `fls` function.
+ ///
+ /// # Examples
+ ///
+ /// ```
+ #[doc = concat!("use kernel::num::last_set_bit_", stringify!($t), ";")]
+ ///
+ #[doc = concat!("assert_eq!(last_set_bit_", stringify!($t), "(0x0), 0);")]
+ #[doc = concat!("assert_eq!(last_set_bit_", stringify!($t), "(0x1), 1);")]
+ #[doc = concat!("assert_eq!(last_set_bit_", stringify!($t), "(0x10), 5);")]
+ #[doc = concat!("assert_eq!(last_set_bit_", stringify!($t), "(0x1f), 5);")]
+ #[doc = concat!(
+ "assert_eq!(last_set_bit_",
+ stringify!($t),
+ "(",
+ stringify!($t),
+ "::MAX), ",
+ stringify!($t), "::BITS);"
+ )]
+ /// ```
+ #[inline(always)]
+ pub const fn [<last_set_bit_ $t>](v: $t) -> u32 {
+ $t::BITS - v.leading_zeros()
+ }
+ }
+ )+
+ };
+}
+
+impl_last_set_bit!(usize, u8, u16, u32, u64, u128);
--
2.49.0
Powered by blists - more mailing lists