num_enum

Derive Macro UnsafeFromPrimitive

source
#[derive(UnsafeFromPrimitive)]
{
    // Attributes available to this derive:
    #[num_enum]
}
Expand description

Generates a unsafe fn unchecked_transmute_from(number: Primitive) -> Self associated function.

§Allows unsafely turning a primitive into an enum with unchecked_transmute_from

If you’re really certain a conversion will succeed, and want to avoid a small amount of overhead, you can use unsafe code to do this conversion. Unless you have data showing that the match statement generated in the try_from above is a bottleneck for you, you should avoid doing this, as the unsafe code has potential to cause serious memory issues in your program.

Note that this derive ignores any default, catch_all, and alternatives attributes on the enum. If you need support for conversions from these values, you should use TryFromPrimitive or FromPrimitive.

use num_enum::UnsafeFromPrimitive;

#[derive(Debug, Eq, PartialEq, UnsafeFromPrimitive)]
#[repr(u8)]
enum Number {
    Zero,
    One,
}

fn main() {
    assert_eq!(
        Number::Zero,
        unsafe { Number::unchecked_transmute_from(0_u8) },
    );
    assert_eq!(
        Number::One,
        unsafe { Number::unchecked_transmute_from(1_u8) },
    );
}

unsafe fn undefined_behavior() {
    let _ = Number::unchecked_transmute_from(2); // 2 is not a valid discriminant!
}