[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-Id: <20250728-as_bytes-v4-2-b9156af37e33@nvidia.com>
Date: Mon, 28 Jul 2025 21:47:52 +0900
From: Alexandre Courbot <acourbot@...dia.com>
To: Abdiel Janulgue <abdiel.janulgue@...il.com>,
Danilo Krummrich <dakr@...nel.org>,
Daniel Almeida <daniel.almeida@...labora.com>,
Robin Murphy <robin.murphy@....com>,
Andreas Hindborg <a.hindborg@...nel.org>, Miguel Ojeda <ojeda@...nel.org>,
Alex Gaynor <alex.gaynor@...il.com>, Boqun Feng <boqun.feng@...il.com>,
Gary Guo <gary@...yguo.net>,
Björn Roy Baron <bjorn3_gh@...tonmail.com>,
Benno Lossin <lossin@...nel.org>, Alice Ryhl <aliceryhl@...gle.com>,
Trevor Gross <tmgross@...ch.edu>
Cc: "Christian S. Lima" <christiansantoslima21@...il.com>,
rust-for-linux@...r.kernel.org, linux-kernel@...r.kernel.org,
Alexandre Courbot <acourbot@...dia.com>
Subject: [PATCH v4 2/2] rust: transmute: add `as_bytes_mut` method to
`AsBytes` trait
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.
Signed-off-by: Alexandre Courbot <acourbot@...dia.com>
---
rust/kernel/transmute.rs | 13 +++++++++++++
1 file changed, 13 insertions(+)
diff --git a/rust/kernel/transmute.rs b/rust/kernel/transmute.rs
index d541c9960904d8c7f755351f22d06e4e8dbd546a..000fda2a78f8e6e8378bbe93cddd8a5008db20cc 100644
--- a/rust/kernel/transmute.rs
+++ b/rust/kernel/transmute.rs
@@ -56,6 +56,19 @@ fn as_bytes(&self) -> &[u8] {
// SAFETY: `data` is non-null and valid for reads over `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,
+ {
+ 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 over `len * sizeof::<u8>()`
+ // bytes. Since `Self` implements `FromBytes` it can be represented by any value.
+ unsafe { core::slice::from_raw_parts_mut(data, len) }
+ }
}
macro_rules! impl_asbytes {
--
2.50.1
Powered by blists - more mailing lists