September 13th, 2024

Packed structs in Zig make bit/flag sets trivial

Zig's packed structs efficiently manage flag sets using single bits for booleans, ensuring compile-time validation and reducing errors. The upcoming Zig 0.10 will further simplify their usage with explicit backing integers.

Read original articleLink Icon
Packed structs in Zig make bit/flag sets trivial

Zig's packed structs offer a more efficient way to handle flag sets compared to traditional languages like C. In the context of the Mach engine's development, the article discusses how Zig allows for the creation of flag sets using packed structs, which can store boolean values as single bits. This contrasts with other languages where a boolean typically occupies a full byte. The example provided illustrates how to define a color write mask using a packed struct, enabling simpler and more readable code for checking the status of flags. The author emphasizes the advantages of Zig's approach, including compile-time validation to ensure the struct's size matches expected values, thus preventing potential errors. Additionally, the upcoming Zig 0.10 release will introduce explicit backing integers for packed structs, further simplifying their use. The author also addresses misconceptions about C's bitfields, noting their implementation-defined nature and the tendency for modern APIs to favor integer types for compatibility. Overall, the article highlights the benefits of Zig's packed structs in game development, particularly for managing flag sets.

- Zig's packed structs allow for efficient flag set management using single bits for booleans.

- Compile-time validation ensures that packed structs match expected sizes, reducing errors.

- The upcoming Zig 0.10 will simplify packed struct usage with explicit backing integers.

- The author contrasts Zig's approach with C's implementation-defined bitfields, which are less commonly used in modern APIs.

- The article advocates for the readability and simplicity of Zig's syntax for flag management.

Link Icon 3 comments
By @mahkoh - 7 months
>The in-memory representation of bit fields is implementation-defined. Therefore, if you’re calling into an external API that takes a uint32_t like in the example without an explicit remapping, you may or may not like the results.

>In practice, everything you’re likely to come across will be little endian nowadays, and the ABI you’re using will most likely order your struct from top to bottom in memory, so they will look the same most of the time.

Unfortunately it is not that simple:

https://github.com/mahkoh/repr-c/blob/0c218ac5a6f82034e649fe...

By @orlp - 7 months
> Secondly, I’d like to question: if C has bitfields, then why do seemingly all modern C APIs not use?

Because an unsigned integer containing many flags is convenient for setting/toggling/clearing multiple options at once. At least in C doing that with bit fields is a pain.