Open Darkfllame opened 1 month ago
For bit operations that are sensible for a particular type, you can already declare methods on the type.
For your second initial point, for common combinations you may consider decl literals,
or again methods (f.e. in the "builder style" of fn setX(Self, x) Self
to get const s = (S{}).setX(.x).setY(2)
[...] ;
).
Or maybe you'd prefer a factory method with a field enum fn of([]const FieldEnum) Self
and use it as const s = S.of(&.{.visible, .fullscreen, .foo
[, ...] });
.
I personally don't think that all packed struct
types (should) represent bit masks,
therefore I think I prefer the explicitness of status-quo.
For repeated semantic operations, write a method so callsites don't repeat themselves.
I think I wouldn't mind a distinct bitmask
construct, but also haven't personally experienced the need for it.
(Tangentially related: https://github.com/ziglang/zig/issues/18882 )
Haven't found other issues for this, but as of today, the only way to substitute flags/bitmask in zig are packed structs. They do work but often introduce some impracticallities, such as:
|
,&
, etc...), do to these, you must first cast your value to a backing integer, do the op, then re-cast the integer to the packed struct using@as
and@bitCast
, and that along knowing which bits is which or just doing even more casting. This also include checking if multiple flags are present..bool
s to do them, but you'll need to type.bitFieldName = true
for each of the bits you wanna set, this is really repetitive considering the fact that bitmask fields are often pretty self-explainatory, i.e field names are often likeuseThing
,hasThing
orisThing
or even just a word likevisible
,fullscreen
orrepeat
.Now a solution I propose is to allow simple enum-like fields when constructing a packed struct value:
Bit operations on packed structs:
Some rules concerning this:
bool
and defaults tofalse
.This is only if we expand on the syntax, we could also add a "bitmask" type or alike, which would natively include those features along of a backing integer, for example:
Which would introduce a clearer separation for new-comers to the language, while requiring more work to implement a whole new type of data in the compiler.