You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Feature proposal: Enumflagset (zig bit flags type) #4185
Below is what I imagine the entry in the zig docs would look like if this feature was implemented.
Edit: added "tag type" and "_SPARE field" to the example below.
Enumflagset
Zig provides enumflagset as a safer and more ergonomic way to implement bit flags, as opposed to using plain integers.
An enumflagset behaves as an integer that is configured with a set of default (power of 2) values, that can be combined with set operations only: union, intersection, complement and equality. (respectively, bitwise: or, and, not, equals). These set operations are closed for the enumflagset, except the equals operator which can accept a 0 as an operand.
The complement operation (bitwise not) is restricted to the bits in use, so masking is not necessary.
// specificying an uint as the tagtype is mandatoryconstWidgetAnchor=enumflagset(u4){
LEFT=1,
RIGHT=2,
TOP=4,
BOTTOM=8,
// Mandatory field, must be equal to the complement of the bitwise or of all the other members_SPARE=0,
// If tagtype was u6, compiler would force you to write:// _SPARE = 16 + 32,// compile error: must be power of 2ERR_EXAMPLE_1=3,
// compile error: cannot be zero// (only SPARE can be zero if all the bits of the tagtype are used)ERR_EXAMPLE_2=0,
// compile error: duplicate of "LEFT"ERR_EXAMPLE_3=1,
}
constmy_anchor : WidgetAnchor=.LEFT|.RIGHT;
constisAnchoredLeft= (my_anchor & .LEFT) !=0;
constisNotAnchoredLeft= (my_anchor & .LEFT) ==0;
// compile error: only bitwise operators (or, and, not) are allowed for enumflagsconstmy_anchor2 : WidgetAnchor=my_anchor+.LEFT;
// compile error: Both operands of bitwise-or must be WidgetAnchor members. constmy_anchor3 : WidgetAnchor=my_anchor|4;
Activity
Vexu commentedon Jan 15, 2020
This will probably be rejected for the reasons given in #2115 (comment)
Vexu commentedon Jan 15, 2020
More importantly I was referring to this:
A better way to do bit flags is to use a packed struct with bools:
archaistvolts commentedon Jan 15, 2020
Thanks. I didn't realize packed bools only require one bit. Guess so 👍 ⚡
JesseRMeyer commentedon Jan 16, 2020
Does
succeed?
Or was
intended?
archaistvolts commentedon Jan 16, 2020
no, it was intended. try running:
you'll see that @sizeof(u1) == @sizeof(u8) == 1
data-man commentedon Jan 16, 2020
There is also bitset-zig.
Adapting to Zig-master is easy.