rust-for-linux.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* [PATCH v7] rust: transmute: Add methods for FromBytes trait
@ 2025-06-15  7:20 Every2
  2025-06-15  9:34 ` Miguel Ojeda
                   ` (2 more replies)
  0 siblings, 3 replies; 14+ messages in thread
From: Every2 @ 2025-06-15  7:20 UTC (permalink / raw)
  To: Miguel Ojeda, Alex Gaynor, Boqun Feng, Gary Guo,
	Björn Roy Baron, Benno Lossin, Andreas Hindborg, Alice Ryhl,
	Trevor Gross, Danilo Krummrich, rust-for-linux, linux-kernel,
	~lkcamp/patches, richard120310

Methods receive a slice and perform size check to add a valid way to make
conversion safe. An Option is used, in error case just return `None`.

Link: https://github.com/Rust-for-Linux/linux/issues/1119
Signed-off-by: Every2 <christiansantoslima21@gmail.com>
---
Changes in v2:
- Rollback the implementation for the macro in the repository and implement
  methods in trait
- Link to v2: https://lore.kernel.org/rust-for-linux/20241012070121.110481-1-christiansantoslima21@gmail.com/

Changes in v3:
- Fix grammar errors
- Remove repeated tests
- Fix alignment errors
- Fix tests not building
- Link to v3: https://lore.kernel.org/rust-for-linux/20241109055442.85190-1-christiansantoslima21@gmail.com/

Changes in v4:
- Removed core::simd::ToBytes
- Changed trait and methods to safe Add
- Result<&Self, Error> in order to make safe methods
- Link to v4: https://lore.kernel.org/rust-for-linux/20250314034910.134463-1-christiansantoslima21@gmail.com/

Changes in v5:
- Changed from Result to Option
- Removed commentaries
- Returned trait impl to unsafe
- Link to v5: https://lore.kernel.org/rust-for-linux/20250320014041.101470-1-christiansantoslima21@gmail.com/

Changes in v6:
- Add endianess check to doc test and use match to check
success case
- Reformulated safety comments
- Link to v6: https://lore.kernel.org/rust-for-linux/20250330234039.29814-1-christiansantoslima21@gmail.com/

Changes in v7:
- Add alignment check
---
 rust/kernel/transmute.rs | 95 +++++++++++++++++++++++++++++++++++++---
 1 file changed, 89 insertions(+), 6 deletions(-)

diff --git a/rust/kernel/transmute.rs b/rust/kernel/transmute.rs
index 1c7d43771a37..5443355de17d 100644
--- a/rust/kernel/transmute.rs
+++ b/rust/kernel/transmute.rs
@@ -9,29 +9,112 @@
 ///
 /// It's okay for the type to have padding, as initializing those bytes has no effect.
 ///
+/// # Example
+/// ```
+/// let arr = [1, 2, 3, 4];
+///
+/// let result = u32::from_bytes(&arr);
+///
+/// #[cfg(target_endian = "little")]
+/// match result {
+///     Some(x) => assert_eq!(*x, 0x4030201),
+///     None => unreachable!()
+/// }
+///
+/// #[cfg(target_endian = "big")]
+/// match result {
+///     Some(x) => assert_eq!(*x, 0x1020304),
+///     None => unreachable!()
+/// }
+/// ```
+///
 /// # Safety
 ///
 /// All bit-patterns must be valid for this type. This type must not have interior mutability.
-pub unsafe trait FromBytes {}
+pub unsafe trait FromBytes {
+    /// Converts a slice of bytes to a reference to `Self` when possible.
+    fn from_bytes(bytes: &[u8]) -> Option<&Self>;
+
+    /// Converts a mutable slice of bytes to a reference to `Self` when possible.
+    fn from_mut_bytes(bytes: &mut [u8]) -> Option<&mut Self>
+    where
+        Self: AsBytes;
+}
 
 macro_rules! impl_frombytes {
     ($($({$($generics:tt)*})? $t:ty, )*) => {
         // SAFETY: Safety comments written in the macro invocation.
-        $(unsafe impl$($($generics)*)? FromBytes for $t {})*
+        $(unsafe impl$($($generics)*)? FromBytes for $t {
+            fn from_bytes(bytes: &[u8]) -> Option<&$t> {
+                if bytes.len() == core::mem::size_of::<$t>()
+                    && (bytes.as_ptr() as usize) % core::mem::align_of::<$t>() == 0
+                {
+                    let slice_ptr = bytes.as_ptr().cast::<$t>();
+                    unsafe { Some(&*slice_ptr) }
+                } else {
+                    None
+                }
+            }
+
+            fn from_mut_bytes(bytes: &mut [u8]) -> Option<&mut $t>
+            where
+            Self: AsBytes,
+            {
+                if bytes.len() == core::mem::size_of::<$t>()
+                    && (bytes.as_mut_ptr() as usize) % core::mem::align_of::<$t>() == 0
+                {
+                    let slice_ptr = bytes.as_mut_ptr().cast::<$t>();
+                    unsafe { Some(&mut *slice_ptr) }
+                } else {
+                    None
+                }
+            }
+        })*
     };
 }
 
 impl_frombytes! {
     // SAFETY: All bit patterns are acceptable values of the types below.
+    // Checking the pointer size and alignment makes this operation safe and it's necessary
+    // to dereference to get the value and return it as a reference to `Self`.
     u8, u16, u32, u64, usize,
     i8, i16, i32, i64, isize,
-
-    // SAFETY: If all bit patterns are acceptable for individual values in an array, then all bit
-    // patterns are also acceptable for arrays of that type.
-    {<T: FromBytes>} [T],
     {<T: FromBytes, const N: usize>} [T; N],
 }
 
+// SAFETY: If all bit patterns are acceptable for individual values in an array, then all bit
+// patterns are also acceptable for arrays of that type.
+unsafe impl<T: FromBytes> FromBytes for [T] {
+    fn from_bytes(bytes: &[u8]) -> Option<&Self> {
+        if bytes.len() % core::mem::size_of::<T>() == 0
+            && (bytes.as_ptr() as usize) % core::mem::align_of::<T>() == 0
+        {
+            let slice_ptr = bytes.as_ptr().cast::<T>();
+            let slice_len = bytes.len() / core::mem::size_of::<T>();
+            // SAFETY: Since the code checks the size and alignment, the slice is valid.
+            unsafe { Some(core::slice::from_raw_parts(slice_ptr, slice_len)) }
+        } else {
+            None
+        }
+    }
+
+    fn from_mut_bytes(bytes: &mut [u8]) -> Option<&mut Self>
+    where
+        Self: AsBytes,
+    {
+        if bytes.len() % core::mem::size_of::<T>() == 0
+            && (bytes.as_mut_ptr() as usize) % core::mem::align_of::<T>() == 0
+        {
+            let slice_ptr = bytes.as_mut_ptr().cast::<T>();
+            let slice_len = bytes.len() / core::mem::size_of::<T>();
+            // SAFETY: Since the code checks the size and alignment, the slice is valid.
+            unsafe { Some(core::slice::from_raw_parts_mut(slice_ptr, slice_len)) }
+        } else {
+            None
+        }
+    }
+}
+
 /// Types that can be viewed as an immutable slice of initialized bytes.
 ///
 /// If a struct implements this trait, then it is okay to copy it byte-for-byte to userspace. This
-- 
2.49.0


^ permalink raw reply related	[flat|nested] 14+ messages in thread

end of thread, other threads:[~2025-06-19 19:31 UTC | newest]

Thread overview: 14+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-06-15  7:20 [PATCH v7] rust: transmute: Add methods for FromBytes trait Every2
2025-06-15  9:34 ` Miguel Ojeda
2025-06-16 20:07   ` Christian
2025-06-16 20:42     ` Miguel Ojeda
2025-06-16 21:11       ` Christian
2025-06-16 21:23         ` Miguel Ojeda
2025-06-18 19:29           ` Benno Lossin
2025-06-19 19:31             ` Miguel Ojeda
2025-06-15 17:12 ` kernel test robot
2025-06-16  8:09 ` Alexandre Courbot
2025-06-16 19:57   ` Christian
2025-06-17  1:15     ` Alexandre Courbot
2025-06-17  1:55       ` Christian
2025-06-17  7:39         ` Alexandre Courbot

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).