The bitfield macro's setter currently uses the From trait for type
conversion, which is overly restrictive and prevents use cases such as
narrowing conversions (e.g., u32 storage size to u8 field size) which
aren't supported by From.

Replace 'from' with 'as' in the setter implementation to support this.

Suggested-by: Yury Norov <[email protected]>
Signed-off-by: Joel Fernandes <[email protected]>
---
 rust/kernel/bits/bitfield.rs | 46 +++++++++++++++++++++++++++++++++++-
 1 file changed, 45 insertions(+), 1 deletion(-)

diff --git a/rust/kernel/bits/bitfield.rs b/rust/kernel/bits/bitfield.rs
index 99e443580b36..6342352891fa 100644
--- a/rust/kernel/bits/bitfield.rs
+++ b/rust/kernel/bits/bitfield.rs
@@ -300,7 +300,7 @@ impl $name {
         $vis fn [<set_ $field>](mut self, value: $to_type) -> Self {
             const MASK: $storage = $name::[<$field:upper _MASK>];
             const SHIFT: u32 = $name::[<$field:upper _SHIFT>];
-            let value = (<$storage>::from(value) << SHIFT) & MASK;
+            let value = ((value as $storage) << SHIFT) & MASK;
             self.0 = (self.0 & !MASK) | value;
 
             self
@@ -452,6 +452,15 @@ struct TestPartialBits: u8 {
         }
     }
 
+    // For testing wide field types on narrow storage
+    bitfield! {
+        struct TestWideFields: u8 {
+            3:0       nibble      as u32;
+            7:4       high_nibble as u32;
+            7:0       full        as u64;
+        }
+    }
+
     #[test]
     fn test_single_bits() {
         let mut pte = TestPageTableEntry::default();
@@ -689,4 +698,39 @@ fn test_partial_bitfield() {
         bf2 = bf2.set_state(0x55);
         assert_eq!(bf2.state(), 0x1);
     }
+
+    #[test]
+    fn test_wide_field_types() {
+        let mut wf = TestWideFields::default();
+
+        wf = wf.set_nibble(0x0000000F_u32);
+        assert_eq!(wf.nibble(), 0x0000000F_u32);
+
+        wf = wf.set_high_nibble(0x00000007_u32);
+        assert_eq!(wf.high_nibble(), 0x00000007_u32);
+
+        wf = wf.set_nibble(0xDEADBEEF_u32);
+        assert_eq!(wf.nibble(), 0x0000000F_u32);
+
+        wf = wf.set_high_nibble(0xCAFEBABE_u32);
+        assert_eq!(wf.high_nibble(), 0x0000000E_u32);
+
+        wf = wf.set_full(0xDEADBEEFCAFEBABE_u64);
+        assert_eq!(wf.full(), 0xBE_u64);
+
+        assert_eq!(wf.raw(), 0xBE_u8);
+
+        wf = TestWideFields::default()
+            .set_nibble(0x5_u32)
+            .set_high_nibble(0xA_u32);
+        assert_eq!(wf.raw(), 0xA5_u8);
+        assert_eq!(wf.nibble(), 0x5_u32);
+        assert_eq!(wf.high_nibble(), 0xA_u32);
+
+        // Test builder pattern
+        let wf2 = TestWideFields::default()
+            .set_nibble(0x12345678_u32)    // truncated to 0x8
+            .set_high_nibble(0x9ABCDEF0_u32); // truncated to 0x0
+        assert_eq!(wf2.raw(), 0x08_u8);
+    }
 }
-- 
2.34.1

Reply via email to