Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mark a type as allowing any value #263

Closed
Morganamilo opened this issue Nov 1, 2021 · 3 comments · Fixed by #282
Closed

Mark a type as allowing any value #263

Morganamilo opened this issue Nov 1, 2021 · 3 comments · Fixed by #282

Comments

@Morganamilo
Copy link

Would it be possible to mark a bitflag as allowing any value?

This is useful to me when wrapping C apis that use bitflags where we as the user of the API may not be aware of all the possible flags. I would like to take the cint and turn it into a bitflags type, perserving the original value, while only defining the flag bits that I am aware of/are public/care about.

@Morganamilo
Copy link
Author

Thinking about it I could just bypass the unsafe unchecked function by wrapping it in a safe one.

However the saftey sections says:

The caller of from_bits_unchecked() has to ensure that all bits correspond to a defined flag or that extra bits are valid for this bitflags type.

Is there actually any reason this invariant has to be held? If I violate it is there any UB issues?

@KodrAus
Copy link
Member

KodrAus commented Nov 2, 2021

Hey @Morganamilo 👋

This method has been a source of confusion since it was introduced and isn't actually possible to make any safety guarantees on. We're going to be deprecating it in favor of a from_bits_preserve function.

In the meantime you can add an inherent method to your flags type:

bitflags! {
    /// baz
    pub struct Flags: u32 {
        const A = 0b00000001;
        #[doc = "bar"]
        const B = 0b00000010;
        const C = 0b00000100;
        #[doc = "foo"]
        const ABC = Flags::A.bits() | Flags::B.bits() | Flags::C.bits();
    }
}

impl Flags {
    pub fn from_bits_preserve(bits: u32) -> Self {
        Flags { bits }
    }
}

@Morganamilo
Copy link
Author

Glad it's being worked on. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants