[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-Id: <20250801-as_bytes-v5-2-975f87d5dc85@nvidia.com>
Date: Fri, 01 Aug 2025 22:24:10 +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 v5 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.
Reviewed-by: Alice Ryhl <aliceryhl@...gle.com>
Reviewed-by: Danilo Krummrich <dakr@...nel.org>
Reviewed-by: Gary Guo <gary@...yguo.net>
Signed-off-by: Alexandre Courbot <acourbot@...dia.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
Powered by blists - more mailing lists