[PATCH 2/3] rust: num: add the `last_set_bit` operation
Alexandre Courbot
acourbot at nvidia.com
Fri Jun 20 13:14:52 UTC 2025
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 at nvidia.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
More information about the Nouveau
mailing list