rust-for-linux.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* [PATCH v10] rust: transmute: Add methods for FromBytes trait
@ 2025-08-24 21:31 Christian S. Lima
  2025-08-25 10:24 ` Alice Ryhl
                   ` (2 more replies)
  0 siblings, 3 replies; 10+ messages in thread
From: Christian S. Lima @ 2025-08-24 21:31 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

The two methods added take a slice of bytes and return those bytes in
a specific type. These methods are useful when we need to transform
the stream of bytes into specific type.

Since the `is_aligned` method for pointer types has been stabilized in
`1.79` version and is being used in this patch. I'm enabling the
feature. In this case, using this method is useful to check the
alignment and avoid a giant boilerplate, such as `(foo.as_ptr() as
usize) % core::mem::align_of::<T>() == 0`.

Even enabling in `rust/kernel/lib.rs` when compiling with `make LLVM=1
CLIPPY=1` a warning is issued, so in order to compile, it was used
locally the `#[allow(clippy::incompatible_msrv)]`.

Link: https://github.com/Rust-for-Linux/linux/issues/1119
Suggested-by: Alexandre Courbot <acourbot@nvidia.com>
Signed-off-by: Christian S. Lima <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
- Link to v7: https://lore.kernel.org/rust-for-linux/20250615072042.133290-1-christiansantoslima21@gmail.com/

Changes in v8:
- Add the new FromBytesSized trait
- Change the implementation of FromBytes trait methods
- Move the cast to pointer earlier and use `is_aligned()` instead manual
alignment check
- Link to v8: https://lore.kernel.org/rust-for-linux/20250624042802.105623-1-christiansantoslima21@gmail.com/

Changes in v9:
- Improve code comments and remove confusing parts.
- Add a build_assert in the conversion of type `[T]` to check for elements
inside the slice.
- Count the elements in the `[T]` conversion instead of using byte
count.
- Link to v9: https://lore.kernel.org/rust-for-linux/20250811213851.65644-1-christiansantoslima21@gmail.com/#t

Changes in v10:
- Remove `FromBytesSized` trait
- Remove implementation for slice types
- Fix doctest not compiling because `?` operator outside a function
that return `Option<()>`
- Make `FromBytes` trait depend on `Sized`
- Add `is_aligned` as feature
---
 rust/kernel/lib.rs       |  1 +
 rust/kernel/transmute.rs | 69 ++++++++++++++++++++++++++++++++++++++--
 2 files changed, 68 insertions(+), 2 deletions(-)

diff --git a/rust/kernel/lib.rs b/rust/kernel/lib.rs
index ed53169e795c..c859a8984bae 100644
--- a/rust/kernel/lib.rs
+++ b/rust/kernel/lib.rs
@@ -18,6 +18,7 @@
 //
 // Stable since Rust 1.79.0.
 #![feature(inline_const)]
+#![feature(pointer_is_aligned)]
 //
 // Stable since Rust 1.81.0.
 #![feature(lint_reasons)]
diff --git a/rust/kernel/transmute.rs b/rust/kernel/transmute.rs
index 1c7d43771a37..7493b84b5474 100644
--- a/rust/kernel/transmute.rs
+++ b/rust/kernel/transmute.rs
@@ -2,6 +2,8 @@
 
 //! Traits for transmuting types.
 
+use core::mem::size_of;
+
 /// Types for which any bit pattern is valid.
 ///
 /// Not all types are valid for all values. For example, a `bool` must be either zero or one, so
@@ -9,10 +11,74 @@
 ///
 /// It's okay for the type to have padding, as initializing those bytes has no effect.
 ///
+/// # Examples
+///
+/// ```
+/// use kernel::transmute::FromBytes;
+///
+/// fn test() -> Option<()> {
+///    let raw = [1, 2, 3, 4];
+///
+///    let result = u32::from_bytes(&raw)?;
+///
+///    #[cfg(target_endian = "little")]
+///    assert_eq!(*result, 0x4030201);
+///
+///    #[cfg(target_endian = "big")]
+///    assert_eq!(*result, 0x1020304);
+///
+///    Some(())
+/// }
+/// ```
+///
 /// # 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 the reference is properly aligned and the size of slice is equal to that of `T`
+    /// and is different from zero.
+    ///
+    /// In another case, it will return `None`.
+    #[allow(clippy::incompatible_msrv)]
+    fn from_bytes(bytes: &[u8]) -> Option<&Self>
+    where
+        Self: Sized,
+    {
+        let slice_ptr = bytes.as_ptr().cast::<Self>();
+        let size = size_of::<Self>();
+        if bytes.len() == size && slice_ptr.is_aligned() {
+            // SAFETY: Checking for size and alignment ensure
+            // that the conversion to a type is valid
+            unsafe { Some(&*slice_ptr) }
+        } else {
+            None
+        }
+    }
+
+    /// Converts a mutable slice of bytes to a reference to `Self`
+    ///
+    /// When the reference is properly aligned and the size of slice
+    /// is equal to that of `T`and is different from zero.
+    ///
+    /// In another case, it will return `None`.
+    #[allow(clippy::incompatible_msrv)]
+    fn from_bytes_mut(bytes: &mut [u8]) -> Option<&mut Self>
+    where
+        Self: AsBytes + Sized,
+    {
+        let slice_ptr = bytes.as_mut_ptr().cast::<Self>();
+        let size = size_of::<Self>();
+        if bytes.len() == size && slice_ptr.is_aligned() {
+            // SAFETY: Checking for size and alignment ensure
+            // that the conversion to a type is valid
+            unsafe { Some(&mut *slice_ptr) }
+        } else {
+            None
+        }
+    }
+}
 
 macro_rules! impl_frombytes {
     ($($({$($generics:tt)*})? $t:ty, )*) => {
@@ -28,7 +94,6 @@ macro_rules! impl_frombytes {
 
     // 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],
 }
 
-- 
2.50.1


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

end of thread, other threads:[~2025-08-29  1:51 UTC | newest]

Thread overview: 10+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-08-24 21:31 [PATCH v10] rust: transmute: Add methods for FromBytes trait Christian S. Lima
2025-08-25 10:24 ` Alice Ryhl
2025-08-25 18:51   ` Christian
2025-08-25 10:39 ` Alexandre Courbot
2025-08-25 14:52   ` Miguel Ojeda
2025-08-25 14:51 ` Miguel Ojeda
2025-08-25 19:51   ` Christian
2025-08-28  0:17     ` Alexandre Courbot
2025-08-28  6:26   ` Alexandre Courbot
2025-08-29  1:50     ` 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).