Stream: ideas

Topic: bitflags


view this post on Zulip Richard Feldman (May 19 2022 at 00:58):

idea: what if we optimized structs like { foo : Bool, bar : Bool, baz : Bool } into bitflags automatically?

view this post on Zulip Richard Feldman (May 19 2022 at 00:58):

in other words, at runtime that record would be a single u8, and { foo: True, bar: False, baz: True } would be represented as 0b0000_0101

view this post on Zulip Richard Feldman (May 19 2022 at 00:59):

getting and setting those fields from a boolean can be done in 2-3 bitwise instructions each: https://godbolt.org/z/1nTjx3fYb

view this post on Zulip Richard Feldman (May 19 2022 at 00:59):

and it would automatically work (without any extra implementation effort) for any tag union with exactly 2 tags in it, not just Bool

view this post on Zulip Richard Feldman (May 19 2022 at 01:02):

for a 4-field record of bools, it would be 1 byte in memory instead of 4, so savings could be pretty big!

view this post on Zulip Brendan Hansknecht (May 19 2022 at 23:56):

Any reason this is limited to 1 bit enums and not also 2 or 4 bit enums?

view this post on Zulip Richard Feldman (May 20 2022 at 00:30):

I thought about that - seems like for those to be efficient we would need to change our algorithm for assigning numbers to tags

view this post on Zulip Richard Feldman (May 20 2022 at 00:32):

e.g. instead of 0, 1, 2, 3, 4, ... we'd want to start off 0, 1, 2, 4, 8, ... and then once we ran out of bits, wrap around and start filling in the non-powers-of-two

view this post on Zulip Richard Feldman (May 20 2022 at 00:33):

that way a tag union of up to 8 tags would have every tag represented as a number with a single 1 in it

view this post on Zulip Richard Feldman (May 20 2022 at 00:34):

although, now that I think about it more, I wonder whether that's necessary :thinking:

view this post on Zulip Brendan Hansknecht (May 20 2022 at 00:48):

That doesn't sound necessary to me. I don't think one hot encoding would be a real gain for this.

view this post on Zulip Brendan Hansknecht (May 20 2022 at 00:49):

Given it is probably used in a switch statement which will likely be a jump table


Last updated: Jun 16 2026 at 16:19 UTC