Expand description
Rust trait for constant #[repr(T)] conversions.
Uses a const trait workaround for stable Rust exposing a safe transmute to
the repr type with a trait.
The type implementing AsRepr may have some additional invariants from
the repr type, but should still be usable as the underlying representation.
§Getting Started
#[derive(Eq, PartialEq, Debug)]
#[repr(transparent)]
pub struct Id(u32);
// safety: `Id` is `#[repr(transparent)]` referring to `u32`
unsafe impl AsRepr<u32> for Id { }
assert_eq!(const { as_repr::as_repr::<u32>(Id(4)) }, 4);
// this is provided!
assert_eq!(const { as_repr::as_repr::<Id>(Id(4)) }, Id(4));
#[repr(u32)]
enum IdName {
Ferris = 0,
Corro = 1,
}
// safety: `IdName` is `#[repr(u32)]` referring to `u32`
unsafe impl AsRepr<u32> for IdName { }
// safety: `IdName` is `#[repr(u32)]`; `Id` has equivalent representation
unsafe impl AsRepr<Id> for IdName { }
assert_eq!(const { as_repr::as_repr::<u32>(IdName::Ferris) }, 0);
assert_eq!(const { as_repr::as_repr::<u32>(IdName::Corro) }, 1);
assert_eq!(const { as_repr::as_repr::<Id>(IdName::Ferris) }, Id(0));
assert_eq!(const { as_repr::as_repr::<Id>(IdName::Corro) }, Id(1));