Skip to main content

Crate as_repr

Crate as_repr 

Source
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: Providing AsReprInherent built on AsRepr but chooses a specific representation to interpret as for const operations
  • cmp: Providing const fns generic for comparable types
  • float: Providing const fns generic for floating point types
  • int: Providing const fns generic for integer types
  • num: Providing const fns generic for numeric types (floats and ints)
  • ops: Providing const fns generic for mathematical types (numeric types and Durations)

Modules§

cmp
cmp Constant partial order on inherent representations
float
float Constant float operations on inherent representations
inherent
inherent Define an inherent representation
int
int Constant integer operations on inherent representations
num
num Constant numeric operations on inherent representations
ops
ops Constant arithmetic operations on inherent representations

Traits§

AsRepr
Trait that allows usage with as_repr()

Functions§

as_repr
Convert a type implementing AsRepr to T.
as_repr_ref
Convert a reference to type implementing AsRepr to &T.
as_repr_slice
Convert a slice of a type implementing AsRepr to &[T].