Skip to content

Allow external impls of Bits and BitFlags #348

@KodrAus

Description

@KodrAus

The BitFlags trait is currently sealed, and is only supported through the bitflags! macro. I think we should make this trait publicly implementable, and default most of its members. I spent some time hacking on this, and came up with this minimal implementation.

Given a flags type like:

bitflags! {
    pub struct MyFlags: u32 {
        const A = 0b0000_0001;
        const B = 0b0000_0010;
        const C = 0b0000_0100;
    }
};

You can implement it manually with:

pub struct MyFlags {
    bits: u32,
}

impl BitFlags for MyFlags {
    const FLAGS: &'static [(&'static str, Self::Bits)] = &[
        ("A", 0b0000_0001),
        ("B", 0b0000_0010),
        ("C", 0b0000_0100),
    ];

    type Bits = u32;
    type Iter = bitflags::iter::Iter<Self>;
    type IterNames = bitflags::iter::IterNames<Self>;

    fn bits(&self) -> Self::Bits {
        self.bits
    }

    fn from_bits_retain(bits: Self::Bits) -> Self {
        Self {
            bits
        }
    }

    fn iter(&self) -> Self::Iter {
        bitflags::iter::Iter::new(self)
    }

    fn iter_names(&self) -> Self::IterNames {
        bitflags::iter::IterNames::new(self)
    }
}

I'm proposing we don't do #293, so that the implementation of BitFlags doesn't call for a host of supertraits.

The FLAGS constant there is new, and drives the iteration-based methods like from_bits_truncate, from_name, and the implementations of Iter and IterNames. If you squint, it looks a lot like the body of the bitflags macro.

I think doing this has a few benefits:

  1. It makes the trait "real", so you can implement it and work with it yourself.
  2. It moves most of the generated code out of macros where they don't need to use fully-qualified paths like $crate::__private::core::option::Option::Some<T>.
  3. It gives us a starting point for Allow opting-out of InternalBitFlags fmt/FromStr impls? #347 and can't use private derive macros #339, where you might not be able to use the bitflags! macro, but with a small amount of effort, can cook up your own flags type with whatever shape you want, and still get the benefits of generated code.

For trait impls like serde and arbitrary, we can then expose utilities like that proposed bitflags::iter module that make manual impls of those traits with awareness that the type is a flags enum easy:

impl Serialize for MyFlags {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        bitflags::serde::serialize(self, serializer)
    }
}

I'm keen to hear what people think of this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions