From: "Christian S. Lima" <christiansantoslima21@gmail.com>
To: "Miguel Ojeda" <ojeda@kernel.org>,
"Alex Gaynor" <alex.gaynor@gmail.com>,
"Boqun Feng" <boqun.feng@gmail.com>,
"Gary Guo" <gary@garyguo.net>,
"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
"Benno Lossin" <benno.lossin@proton.me>,
"Andreas Hindborg" <a.hindborg@kernel.org>,
"Alice Ryhl" <aliceryhl@google.com>,
"Trevor Gross" <tmgross@umich.edu>,
"Danilo Krummrich" <dakr@kernel.org>,
rust-for-linux@vger.kernel.org, linux-kernel@vger.kernel.org,
~lkcamp/patches@lists.sr.ht, richard120310@gmail.com
Subject: [PATCH v10] rust: transmute: Add methods for FromBytes trait
Date: Sun, 24 Aug 2025 18:31:33 -0300 [thread overview]
Message-ID: <20250824213134.27079-1-christiansantoslima21@gmail.com> (raw)
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
next reply other threads:[~2025-08-24 21:31 UTC|newest]
Thread overview: 10+ messages / expand[flat|nested] mbox.gz Atom feed top
2025-08-24 21:31 Christian S. Lima [this message]
2025-08-25 10:24 ` [PATCH v10] rust: transmute: Add methods for FromBytes trait 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
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20250824213134.27079-1-christiansantoslima21@gmail.com \
--to=christiansantoslima21@gmail.com \
--cc=a.hindborg@kernel.org \
--cc=alex.gaynor@gmail.com \
--cc=aliceryhl@google.com \
--cc=benno.lossin@proton.me \
--cc=bjorn3_gh@protonmail.com \
--cc=boqun.feng@gmail.com \
--cc=dakr@kernel.org \
--cc=gary@garyguo.net \
--cc=linux-kernel@vger.kernel.org \
--cc=ojeda@kernel.org \
--cc=richard120310@gmail.com \
--cc=rust-for-linux@vger.kernel.org \
--cc=tmgross@umich.edu \
--cc=~lkcamp/patches@lists.sr.ht \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
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).