3 ms·
I get that this was just an example, but a boolean 5 would actually be language-level UB that could have very real correctness implications! The Rust compiler
by Nullabillity 5y ago
I get that this was just an example, but a boolean 5 would actually be language-level UB that could have very real correctness implications!
The Rust compiler is allowed to (and sometimes required to) use the invalid values of a child value to represent other cases of an enum. For example, this is how it optimizes `Option<&T>` into "pointer where null is None and any other value is Some".
This would technically also allow it (I don't know whether it currently does this..) to optimize the following enum:
enum Foo {
A(bool),
B(bool),
C(bool),
}
into the following single-byte representation:
A(false) => 0,
A(true) => 1,
B(false) => 2,
B(true) => 3,
C(false) => 4,
C(true) => 5,
With this representation, `A(5 as bool)` would be impossible to distinguish from `C(true)`, which would be complete and utter nonsense.
- Dylan16807 5y ago> I get that this was just an example, but a boolean 5 would actually be language-level UB that could have very real correctness implications! Yes, that's why I used it as the example. And you don't need anything that complicated, either. A simple if or switch statement might be optimized by the compiler for 0 and 1 and jump into random code for 5.