Re: [PATCH v4 6/6] rust: bitfield: Use 'as' operator for setter type conversion

Joel Fernandes
2025-09-29T20:32:49Z

On Mon, Sep 29, 2025 at 03:47:08PM +0900, Alexandre Courbot wrote:
> On Sun Sep 21, 2025 at 3:22 AM JST, Joel Fernandes wrote:
> > The bitfield macro's setter currently uses the From trait for type
> > conversion, which is overly restrictive and prevents use cases such as
> > narrowing conversions (e.g., u32 storage size to u8 field size) which
> > aren't supported by From.
> >
> > Replace 'from' with 'as' in the setter implementation to support this.
> >
> > Suggested-by: Yury Norov <yury.norov@gmail.com>
>
> Can you add a `Link: ` tag to the discussion for context?
>
> But I am not really convinced this is needed or desirable at all. Where
> would it make sense to define a field that is larger that its containing
> type?

The 'as' keyword is not related to the containing struct IMO.

Example:
you can have a

struct Foo(u8) {
0:3 foo as u8;
4:7 bar as u8;
}

Here if you just go by the 'as u8', the total width would be 16. So we should
not conflate the 'as u8' with the '(u8)', they are already 2 separate things
and incompatible. I think the following would also work:

0:3 foo as u8 => u32;

However, directly using 'as u32' is a better shortcut IMO.

Would it help if I added more documentation comments about this?

> This looks like it can introduce confusion or errors. It's already
> not ideal that we can pass values that would be truncated; but this
> makes it worse.

Actually, in new series we're no longer truncating, I will post that shortly
after we conclude feedback on this series.

>
> Anyway, if we decide to keep this, I think you want to remove the
>
> +//! Note that the compiler will error out if the size of the setter's
> arg exceeds the
> +//! struct's storage size.
>
> bit that was introduced in patch 2.

Ah, good catch! Will remove the comment.

thanks,

- Joel

>