meithecatte/enumflags2

How to implement Default 0

Closed this issue · 5 comments

#[derive(BitFlags, Copy, Clone, Debug, PartialEq)]
#[repr(u8)]
enum Test {
    A = 0b01,
    B = 0b10,
}
impl Test {
    pub const NONE: BitFlags<Self> = BitFlags::empty();
}
impl Default for Test {
    fn default() -> Self {
        unsafe { *(&0u8 as &u8 as *const u8 as *const Test) }
    }
}

I kind of figured out how to implement Default but is is extremely ugly.
Am I missing some better way?
Either way it would be good to add it to the doc please.

First off, your code is undefined behavior.

There are two types for an enumflags bitflag - Test always contains exactly one bitflag, such that you can pattern match on it. BitFlags<Test> is a set of flags, and that is the type that can contain 0. BitFlags::empty(), as well as BitFlags::default(), returns that.

The master branch docs contain the following sentence

This means that the type of a single flag is separate from a set of flags.

Would that help with this confusion?

Oh yes this helps a lot, so in the code I should use BitFlags<Test> instead of Test.
But for one of the bit flags enums I am planning to have I will need non zero default, and by understanding the code better now I do not think that is possible, or is it? I can just define constant pub const DEFAULT: BitFlags<Self> = make_bitflags!( Test::{ A | B }); as workaround. I did not check the exact syntax so there might be a typo, is this the only workaround? Or is there a good way to do this?

I will look at it, but no promisses

PR #34 not a working version, but I am not sure if I can take it further :(