Re: [PATCH v8] rust: add new macro for common bitflag operations
From: Andreas Hindborg
Date: Thu Jan 15 2026 - 08:32:09 EST
"Gary Guo" <gary@xxxxxxxxxxx> writes:
> On Thu Jan 15, 2026 at 12:14 PM GMT, Andreas Hindborg wrote:
>> Andreas Hindborg <a.hindborg@xxxxxxxxxx> writes:
>>
>>> "Filipe Xavier" <felipeaggger@xxxxxxxxx> writes:
>>>
>>>> We have seen a proliferation of mod_whatever::foo::Flags
>>>> being defined with essentially the same implementation
>>>> for BitAnd, BitOr, contains and etc.
>>>>
>>>> This macro aims to bring a solution for this,
>>>> allowing to generate these methods for user-defined structs.
>>>> With some use cases in KMS and upcoming GPU drivers.
>>>>
>>>> Link: https://rust-for-linux.zulipchat.com/#narrow/channel/288089-General/topic/We.20really.20need.20a.20common.20.60Flags.60.20type
>>>> Suggested-by: Daniel Almeida <daniel.almeida@xxxxxxxxxxxxx>
>>>> Suggested-by: Lyude Paul <lyude@xxxxxxxxxx>
>>>> Reviewed-by: Daniel Almeida <daniel.almeida@xxxxxxxxxxxxx>
>>>> Reviewed-by: Lyude Paul <lyude@xxxxxxxxxx>
>>>> Signed-off-by: Filipe Xavier <felipeaggger@xxxxxxxxx>
>>>
>>> Tested-by: Andreas Hindborg <a.hindborg@xxxxxxxxxx>
>>> Reviewed-by: Andreas Hindborg <a.hindborg@xxxxxxxxxx>
>>>
>>>
>>> I think it would be useful to add:
>>>
>>> impl Flags {
>>> unsafe from_raw(value: Repr) -> {
>>> ...
>>> }
>>> }
>>>
>>> impl TryFrom<Repr> for Flag {
>>> // Succeed if `value` is a valid `Flag` enum bit pattern.
>>> }
>>>
>>> impl TryFrom<Repr> for Flags {
>>> // Succeed if `value` is the logical OR of valid enum bit patterns.
>>> }
>>
>> Also bitwise operations on the underlying type such as
>>
>> impl BitOrAssign<Flag> for u32 {
>> ...
>> }
>>
>> Not sure if that is possible with the orphan rule, but it would be nice.
>> I was trying to
>>
>> lim.features |= request::Feature::Rotational;
>
> This is allowed by orphan rules, in a similar way that you can implement
> `From<Local> for Foreign`.
>
> However I don't think this is desirable feature? Why can't a conversion be used
> if you're using raw reprs?
>
> I think we should discourage the use of raw integers when bitflags can be used,
> adding that (or even `TryFrom`) can be a negative incentive.
In this case I have a C struct with a flag field. It would not be
ergonomic to read out the field, convert to `Flag` type, do the
operation, and store back again.
This assignment is in abstraction code. I could use the raw bindings
constant for the operation, but I would rather use the Rust type.
I do not think there is any risk by allowing operators between flags and
integers. What situation do you imagine where there would be a problem?
Best regards
Andreas Hindborg