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));§Optional Features
There are also modules that provide additional functionality. They are only built when a feature with a matching name is enabled.
inherent: ProvidingAsReprInherentbuilt onAsReprbut chooses a specific representation to interpret as for const operationscmp: Providing const fns generic for comparable typesfloat: Providing const fns generic for floating point typesint: Providing const fns generic for integer typesnum: Providing const fns generic for numeric types (floats and ints)ops: Providing const fns generic for mathematical types (numeric types andDurations)
Modules§
- cmp
cmpConstant partial order on inherent representations- float
floatConstant float operations on inherent representations- inherent
inherentDefine an inherent representation- int
intConstant integer operations on inherent representations- num
numConstant numeric operations on inherent representations- ops
opsConstant arithmetic operations on inherent representations
Traits§
Functions§
- as_repr
- Convert a type implementing
AsReprtoT. - as_
repr_ ref - Convert a reference to type implementing
AsReprto&T. - as_
repr_ slice - Convert a slice of a type implementing
AsReprto&[T].