Re: [PATCH] rust: transmute: add `as_bytes` method for `AsBytes` trait

From: Alice Ryhl
Date: Fri Jul 25 2025 - 03:53:10 EST


On Fri, Jul 25, 2025 at 4:11 AM Alexandre Courbot <acourbot@xxxxxxxxxx> wrote:
>
> Every time that implements `AsBytes` should be able to provide its byte
> representation. Introduce the `as_bytes` method that returns the
> implementer as a stream of bytes.
>
> Since types implementing `Sized` can trivially be represented as a
> stream of bytes, introduce the `AsBytesSized` proxy trait that can be
> implemented for any `Sized` type and provides an `AsBytes`
> implementation suitable for such types. Types that are not `Sized` need
> to implement `AsBytes` directly and provide a method implementation.
>
> Signed-off-by: Alexandre Courbot <acourbot@xxxxxxxxxx>

Is the AsBytesSized trait necessary? Can't we just do this?

pub unsafe trait AsBytes {
/// Returns `self` as a slice of bytes.
fn as_bytes(&self) -> &[u8] {
let size = size_of_val(self);
let ptr = self as *const Self as *const u8;
unsafe { slice::from_raw_parts(ptr, size) }
}
}

Alice