Commit 331c24e6 authored by Alexandre Courbot's avatar Alexandre Courbot
Browse files

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.

[acourbot@nvidia.com: use fully qualified `core::mem::size_of_val` to
build with Rust 1.78.]

Reviewed-by: default avatarAlice Ryhl <aliceryhl@google.com>
Reviewed-by: default avatarDanilo Krummrich <dakr@kernel.org>
Reviewed-by: default avatarGary Guo <gary@garyguo.net>
Reviewed-by: default avatarBenno Lossin <lossin@kernel.org>
Acked-by: default avatarMiguel Ojeda <ojeda@kernel.org>
Link: https://lore.kernel.org/r/20250801-as_bytes-v5-2-975f87d5dc85@nvidia.com


Signed-off-by: default avatarAlexandre Courbot <acourbot@nvidia.com>
parent 1db476d2
Loading
Loading
Loading
Loading
+15 −0
Original line number Diff line number Diff line
@@ -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 = core::mem::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 {