logoalt Hacker News

How many options fit into a boolean?

48 pointsby luulast Saturday at 5:31 AM22 commentsview on HN

Comments

gimatoday at 7:37 PM

"How many options fit into a boolean?" Five or two, according* to Microsoft.

> MsoTrioState is "a tri-state Boolean value". it has five possible values. only two of them are supported.

*) https://learn.microsoft.com/en-au/dotnet/api/microsoft.offic...

Sourced from here https://fedi.lynnesbian.space/@lynnesbian/115969259564305759

show 1 reply
gizmo686today at 6:03 PM

It's not clear from the article, but "niche optimization" does not mean "optimization that is only useful in a very specific circumstance".

It is a specific optimization based on the idea of storing one type inside of another type by finding a "niche" of unused bit pattern(s) inside the second type.

It has far more useful application than a tower of Option 254 deep.

ralferootoday at 5:37 PM

True | False | FileNotFound was a meme about 2 decades ago, and even that was a reference to MSDOS from another 2 decades earlier. I guess things never change, only the language.

Even now, I still find myself using true/false/null on occasions, but I'm usually smart enough to replace it with an enum at that point. The only time I don't is when it's an optional parameter to a function to override some default/existing value, at which point it then makes sense to keep it as an optional bool.

show 2 replies
pavontoday at 4:28 PM

Neat. Even knowing about niche optimization I would have guessed that you could fit 7 Options - one bit for each. But the developers were smart enough to take advantage of the fact that you can't have a Some nested below a None, so you only need to represent how many Somes there are before you reach None (or the data), allowing 254 possibilities.

show 1 reply
nine_ktoday at 4:29 PM

The scoop: a boolean can't be smaller than a byte. Full 254 level of nested Option<bool> fit into it. (C++ needs much more for even a single level.)

shagietoday at 5:29 PM

For Java developers... you can use Optional<Boolean> to store the elusive four possible booleans.

show 1 reply
priowisetoday at 4:36 PM

This question always reminds me that we often compress far more nuance into binary decisions than reality allows. In practice most systems end up inventing “soft booleans” (flags, states, priorities) to deal with that.

RobotToastertoday at 5:19 PM

>and that it takes up one byte of memory

You can make them smaller using bitfields in C.

show 2 replies
vadelfetoday at 5:56 PM

The deeper you go into memory layout, the more you realize that even "simple" types aren't that simple.

mock-possumtoday at 4:29 PM

> looking at Rust … it turns out that `Option<bool>` takes up exactly one byte of memory, the same as bool! The same is true for `Option<Option<bool>>`, all the way up to 254 nested options.

Ah how many of those options fit into that boolean. Word games!