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

From: Alexandre Courbot
Date: Fri Jul 25 2025 - 08:13:25 EST


On Fri Jul 25, 2025 at 4:52 PM JST, Alice Ryhl wrote:
> 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) }
> }
> }

Wow, I was completely oblivious of the fact that `size_of_val` also
worked with non-Sized types! Yes, this works perfectly well and is much
less intrusive and overall way better. Thanks a lot.

... now it also makes me anxious about why we didn't include this
method when the trait was introduced, since it is so simple. ^_^;