-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
Closed
Labels
proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.This issue suggests modifications. If it also has the "accepted" label then it is planned.
Milestone
Description
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 mandatory
const WidgetAnchor = 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 2
ERR_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,
}
const my_anchor : WidgetAnchor = .LEFT | .RIGHT;
const isAnchoredLeft = (my_anchor & .LEFT) != 0;
const isNotAnchoredLeft = (my_anchor & .LEFT) == 0;
// compile error: only bitwise operators (or, and, not) are allowed for enumflags
const my_anchor2 : WidgetAnchor = my_anchor + .LEFT;
// compile error: Both operands of bitwise-or must be WidgetAnchor members.
const my_anchor3 : WidgetAnchor = my_anchor | 4;Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
proposalThis issue suggests modifications. If it also has the "accepted" label then it is planned.This issue suggests modifications. If it also has the "accepted" label then it is planned.