How to truncate if const _ = !0; was used #443

Closed
opened 2025-04-24 12:22:47 -05:00 by rusty-snake · 1 comment
rusty-snake commented 2025-04-24 12:22:47 -05:00 (Migrated from github.com)

I'm in the situation where a bitflags type from a third-party crate uses const _ = !0; (i.e. I can not modify the bitflags! definition and add/remove flags). I need the complement of all known/defined flags. However I do not see a way to truncate/... theses flags in this case or do a complement_defined or access FooFlags::_ or whatever. I can not even tell if there are extra bits set.

I'm in the situation where a bitflags type from a third-party crate uses `const _ = !0;` (i.e. I can not modify the `bitflags!` definition and add/remove flags). I need the `complement` of all known/defined flags. However I do not see a way to `truncate`/... theses flags in this case or do a `complement_defined` or access `FooFlags::_` or whatever. I can not even tell if there are extra bits set.
KodrAus commented 2025-04-28 17:07:41 -05:00 (Migrated from github.com)

If the library is using an unnamed _ = !0 flag then there aren't really any unknown flags or bits so to speak. The underlying definition could introduce new flags before the library adds them, so any set bits should be considered valid.

Something you can do though is get a flags value that only includes named flags by iterating over them, like in this example:

let defined = <MyFlags as bitflags::Flags>::FLAGS
    .iter()
    .filter(|f| !f.name().is_empty())
    .fold(MyFlags::empty(), |acc, f| acc | *f.value());

We could maybe define a Flags::all_named constructor that produced this value, and optimize it for the bitflags! macro.

If the library is using an unnamed `_ = !0` flag then there aren't really any unknown flags or bits so to speak. The underlying definition could introduce new flags before the library adds them, so any set bits should be considered valid. Something you can do though is get a flags value that only includes named flags by iterating over them, like [in this example](https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=e8155b2a5a9d36a1ade3d5b1468e1573): ```rust let defined = <MyFlags as bitflags::Flags>::FLAGS .iter() .filter(|f| !f.name().is_empty()) .fold(MyFlags::empty(), |acc, f| acc | *f.value()); ``` We could maybe define a `Flags::all_named` constructor that produced this value, and optimize it for the `bitflags!` macro.
Sign in to join this conversation.
No labels
bug
good first issue
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
gh-bitflags/bitflags#443
No description provided.