I’m de-serializing an enum from a byte stream. In my use case, I want to be able to handle all possble values found in the byte stream.
Normally I would use a non-exhaustive enum (to force all switch statements on the enum to have an else and to prevent a panic on de-serialization) but in this special case I have an enum that represents all the integers in the backing integer.
Also, if you want, it’s possible to remove enum’s ordinal values in this case since by default they start at zero and increase by one, see langref.
Sidenote: in the case of switching on non-exhaustive enums you can use _ instead of else as a switch prong to ensure that every known value is handled, see langref.
Enum tags can’t have duplicate integer value so you don’t need loop. You can just check that number of fields is equal to 2^(number of bits in backing integer type).
It’s easier, works with signed integers and probably faster to compile.
Yes, that’s a viable option when you don’t specify enum’s ordinal values. But if you do, it’s better to loop through values asserting that there’re no typos. For the same reason it’s better to assert that the backing integer is unsigned (letters ‘u’ and ‘i’ are dangerously close on keyboards). Btw, don’t worry about compilation speed in such trivial cases, incremental is not far off