[PATCH v2 1/8] rust: transmute: add `from_bytes_copy` method to `FromBytes` trait

Benno Lossin lossin at kernel.org
Tue Aug 26 06:50:44 UTC 2025


On Tue Aug 26, 2025 at 6:07 AM CEST, Alexandre Courbot wrote:
> `FromBytes::from_bytes` comes with a few practical limitations:
>
> - It requires the bytes slice to have the same alignment as the returned
>   type, which might not be guaranteed in the case of a byte stream,
> - It returns a reference, requiring the returned type to implement
>   `Clone` if one wants to keep the value for longer than the lifetime of
>   the slice.

I think that any `Sized` type that can implement `FromBytes` also can
implement `Copy`, so I don't feel like the last point is a strong one.
But the unaligned byte stream is motivation enough :)

> To overcome these when needed, add a `from_bytes_copy` with a default
> implementation in the trait. `from_bytes_copy` returns an owned value
> that is populated using an unaligned read, removing the lifetime
> constraint and making it usable even on non-aligned byte slices.
>
> Reviewed-by: Alice Ryhl <aliceryhl at google.com>
> Signed-off-by: Alexandre Courbot <acourbot at nvidia.com>

Reviewed-by: Benno Lossin <lossin at kernel.org>

---
Cheers,
Benno

> ---
>  rust/kernel/transmute.rs | 17 +++++++++++++++++
>  1 file changed, 17 insertions(+)


More information about the Nouveau mailing list