macro_rules! raw_type {
(
$(#[$raw_attr:meta])*
$raw_vis:vis struct $Raw:ident($int:ty);
$(#[$enum_attr:meta])*
$enum_vis:vis enum $Enum:ident {
$(
$(#[$variant_attr:meta])*
$Variant:ident = $value:literal,
)+
}
) => { ... };
}Expand description
Defines a pair of an ABI-compatible raw newtype and a corresponding convenient, high-level open-set enum, along with all conversions between the newtype, the enum, and the underlying integer.
The newtype behaves like the plain integer (Copy, comparisons, and
conversions) but carries the semantics of the enum: Debug prints the
variant name together with the raw value (e.g. Foo(0)) and Display
prints just the variant name (e.g. Foo); values without a specified
semantic print as Custom(x). It is safe to use in #[repr(C)]
structures parsed from raw memory, as every bit pattern is valid for it. The enum assigns each specified value to a
variant; all other values are mapped to the automatically added Custom
variant, which carries the raw integer. By convention, the newtype
carries the name of the enum plus a Raw suffix.
ยงExample
multiboot2_common::raw_type! {
/// ABI compatible representation of a demo type.
pub struct DemoTypeRaw(u32);
/// The type of a demo item.
///
/// This is a higher level abstraction for [`DemoTypeRaw`].
pub enum DemoType {
/// The first defined type.
Foo = 0,
/// The second defined type.
Bar = 1,
}
}
let raw = DemoTypeRaw::new(1);
assert_eq!(raw, DemoType::Bar);
assert_eq!(DemoType::from(DemoTypeRaw::new(42)), DemoType::Custom(42));