Derive Macro num_enum::UnsafeFromPrimitive
source · #[derive(UnsafeFromPrimitive)]
{
// Attributes available to this derive:
#[num_enum]
}
Expand description
Generates a unsafe fn from_unchecked (number: Primitive) -> Self
associated function.
§Allows unsafely turning a primitive into an enum with from_unchecked.
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.
use num_enum::UnsafeFromPrimitive;
#[derive(Debug, Eq, PartialEq, UnsafeFromPrimitive)]
#[repr(u8)]
enum Number {
Zero,
One,
}
fn main() {
assert_eq!(
Number::Zero,
unsafe { Number::from_unchecked(0_u8) },
);
assert_eq!(
Number::One,
unsafe { Number::from_unchecked(1_u8) },
);
}
unsafe fn undefined_behavior() {
let _ = Number::from_unchecked(2); // 2 is not a valid discriminant!
}