Here’s an idea:
unsafe trait CEnum {
type Underlying: Copy;
}
// mod std::intrinsics
fn from_discriminant<E: CEnum>(val: E::Underlying) -> Option<E> { /* filled in by compiler */ }
CEnum
is automatically implemented for #[repr(uN)]
or #[repr(C)]
enums, in “the way one expects”. The intrinsic function does what it says on the tin: eats a number and returns the corresponding variant, if it exists. The actual lookup table for whether an enum is in range is only created when from_discriminant
is monomorphized.