Re: [PATCH v2 2/3] rust: Add support for deriving `AsBytes` and `FromBytes`

From: Alice Ryhl

Date: Thu Dec 18 2025 - 03:26:47 EST


On Thu, Dec 18, 2025 at 04:23:43PM +0900, Alexandre Courbot wrote:
> On Thu Dec 18, 2025 at 3:01 AM JST, Matthew Maurer wrote:
> > On Tue, Dec 16, 2025 at 7:12 PM Alexandre Courbot <acourbot@xxxxxxxxxx> wrote:
> >> > +/// Implements `FromBytes` for a struct.
> >> > +///
> >> > +/// It will fail compilation if the struct you are deriving on cannot be determined to implement
> >> > +/// `FromBytes` safely. It may still fail for some types which would be safe to implement
> >> > +/// `FromBytes` for, in which case you will need to write the implementation and justification
> >> > +/// yourself.
> >> > +///
> >> > +/// Main reasons your type may be rejected:
> >> > +/// * Not a `struct`
> >> > +/// * One of the fields is not `FromBytes`
> >> > +///
> >> > +/// # Examples
> >> > +///
> >> > +/// ```
> >> > +/// #[derive(FromBytes)]
> >> > +/// #[repr(C)]
> >> > +/// struct Foo {
> >> > +/// x: u32,
> >> > +/// y: u16,
> >> > +/// z: u16,
> >> > +/// }
> >> > +/// ```
> >>
> >> One thing I have noticed is that I could sucessfully derive `FromBytes`
> >> on a struct that is not `repr(C)`... Is that something we want to
> >> disallow?
> >>
> >
> > Why should we disallow this? I can enforce it very easily if we want
> > it, but the only difference between `#[repr(C)]` and `#[repr(Rust)]`
> > is whether we can statically predict their layout. In theory you can
> > use this to elide the padding check for `#[repr(C)]` structs (and
> > `zerocopy` does this), but it's significantly more complicated.
> >
> > The only argument I see in favor of disallowing `#[repr(Rust)]` here
> > is that if it's not a struct that also supports `AsBytes`, there's a
> > question about where you're getting the bytes to load from.
> >
> > I will point out that we probably don't *just* want to restrict to
> > `#[repr(C)]` because `#[repr(transparent)]` and `#[repr(packed)]` are
> > also great use cases.
>
> Yeah it's probably correct as it is. I am not sure why we would want to
> use it on types without a predictable layout, but also cannot say this
> is fundamentally broken.

At the very least such types can roundtrip to/from byte arrays. Or you
could pass them to the randomness pool:

https://lore.kernel.org/all/20251216-add-entropy-v2-1-4d866f251474@xxxxxxxxxx/

Alice