[PATCH v5 2/2] rust: transmute: add `as_bytes_mut` method to `AsBytes` trait

Alexandre Courbot posted 2 patches 2 months ago
[PATCH v5 2/2] rust: transmute: add `as_bytes_mut` method to `AsBytes` trait
Posted by Alexandre Courbot 2 months ago
Types that implement both `AsBytes` and `FromBytes` can be safely
modified as a slice of bytes. Add a `as_bytes_mut` method for that
purpose.

Reviewed-by: Alice Ryhl <aliceryhl@google.com>
Reviewed-by: Danilo Krummrich <dakr@kernel.org>
Reviewed-by: Gary Guo <gary@garyguo.net>
Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>
---
 rust/kernel/transmute.rs | 15 +++++++++++++++
 1 file changed, 15 insertions(+)

diff --git a/rust/kernel/transmute.rs b/rust/kernel/transmute.rs
index 08e6f0ff92a563e90895efa31f31f887aa05a0ae..5b2a53aa5df041e56be0c23993f684aa803551ae 100644
--- a/rust/kernel/transmute.rs
+++ b/rust/kernel/transmute.rs
@@ -57,6 +57,21 @@ fn as_bytes(&self) -> &[u8] {
         // SAFETY: `data` is non-null and valid for reads of `len * sizeof::<u8>()` bytes.
         unsafe { core::slice::from_raw_parts(data, len) }
     }
+
+    /// Returns `self` as a mutable slice of bytes.
+    fn as_bytes_mut(&mut self) -> &mut [u8]
+    where
+        Self: FromBytes,
+    {
+        // CAST: `Self` implements both `AsBytes` and `FromBytes` thus making `Self`
+        // bi-directionally transmutable to `[u8; size_of_val(self)]`.
+        let data = core::ptr::from_mut(self).cast::<u8>();
+        let len = size_of_val(self);
+
+        // SAFETY: `data` is non-null and valid for read and writes of `len * sizeof::<u8>()`
+        // bytes.
+        unsafe { core::slice::from_raw_parts_mut(data, len) }
+    }
 }
 
 macro_rules! impl_asbytes {

-- 
2.50.1
Re: [PATCH v5 2/2] rust: transmute: add `as_bytes_mut` method to `AsBytes` trait
Posted by Benno Lossin 2 months ago
On Fri Aug 1, 2025 at 3:24 PM CEST, Alexandre Courbot wrote:
> Types that implement both `AsBytes` and `FromBytes` can be safely
> modified as a slice of bytes. Add a `as_bytes_mut` method for that
> purpose.
>
> Reviewed-by: Alice Ryhl <aliceryhl@google.com>
> Reviewed-by: Danilo Krummrich <dakr@kernel.org>
> Reviewed-by: Gary Guo <gary@garyguo.net>
> Signed-off-by: Alexandre Courbot <acourbot@nvidia.com>

Reviewed-by: Benno Lossin <lossin@kernel.org>

---
Cheers,
Benno

> ---
>  rust/kernel/transmute.rs | 15 +++++++++++++++
>  1 file changed, 15 insertions(+)