enumflags2 icon indicating copy to clipboard operation
enumflags2 copied to clipboard

Add (const) functions on enums

Open axelkar opened this issue 5 months ago • 2 comments

The bitflags crate define most (all?) of its functions on the struct itself, in addition to the Flags trait. Could you define the functions of Bitflag on the implementors of Bitflag, as const?

It's super useful not having to import the trait when using the bitflags crate.

I'm guessing struct BitFlags functions aren't const due to MSRV, but could there be a feature flag to make them const? Or do const functions not work at all in generic impls?

axelkar avatar Jul 15 '25 13:07 axelkar

I periodically try to make things more const, but the features required to do this cleanly were still WIP the last time I checked.

For now, there is a collection of functions with the _c suffix, which expose const APIs that are shaped slightly differently, to be implementable within the limitations of current const fns – see this section of the documentation.

I do admit that this API is somewhat limited – if you have any concrete example use-cases where the API is lacking, let me know and I'll try to extend it in that direction.

meithecatte avatar Jul 15 '25 19:07 meithecatte

if you have any concrete example use-cases where the API is lacking, let me know and I'll try to extend it in that direction.

Could you implement empty, all, from_bits{_truncate,_unchecked} on the enums with bit flags as variants? By implementing them on the enum's impl (without generics), you can make them const. Actually you could probably make empty and all associated constants on the enum. default could also be made const.

Note that this may conflict with functions and associated constants set on the enum by users.

axelkar avatar Jul 16 '25 11:07 axelkar