illicitonion / num_enum

Apache License 2.0
264 stars 34 forks source link

Add a trait for `IntoPrimitive` #156

Open jgcodes2020 opened 1 week ago

jgcodes2020 commented 1 week ago

FromPrimitive and TryFromPrimitive already have traits, why not IntoPrimitive?

illicitonion commented 1 week ago

We could add one if it's useful. IIRC we added the others so that we could do blanket implementations of other traits. If we wanted to add a blanket implementation using IntoPrimitive it'd probably be a semver break (as it could cause impl conflicts for whatever we added blanket implementations of).

Do you have a concrete use-case you'd like to use IntoPrimitive for, or is this more of an aesthetic question?

jgcodes2020 commented 1 week ago

I'm using this crate with bindgen to generate enums that play nice with Rust. Bindgen generates enums as #[repr(u32)] or #[repr(i32)] on Linux depending on whether the enum has negative values; but on Windows all enums are #[repr(i32)]. I already use TryFromPrimitive to safely cast to enums, but theoretically, having an IntoPrimitive trait allows you to do this, regardless of what the enum's primitive type is. Unlike val as u16, this is checked.

fn mess_with_enum(val: MyEnum) -> u16 {
  let int_val = val.into_primitive();
  u16::try_from(int_val).unwrap();
}