Skip to main content

newtype_enum

Macro newtype_enum 

Source
macro_rules! newtype_enum {
    (
        $(#[$type_attrs:meta])*
        $visibility:vis enum $type:ident : $base_vis:vis $base_integer:ty => $(#[$impl_attrs:meta])* {
            $(
                $(#[$variant_attrs:meta])*
                $variant:ident = $value:expr,
            )*
        }
    ) => { ... };
}
Expand description

Creates a struct newtype from an enum definition.

The enum is represented as a tuple struct with a single field of type base_integer. Each variant is converted to an associated constant of the same name, with value equal to $type($value).

This allows for representing enums that do not have a fixed set of variants, as creating an enum in Rust with an out of range discriminant is undefined behaviour.

ยงExamples

use kernel_api::newtype_enum;

newtype_enum! {
    /// The type of food requested.
    pub enum FoodType: pub u8 => {
        /// Red and round.
        TOMATO = 0,
        /// Green and cylindrical.
        CUCUMBER = 1,
    }
}

assert_eq!(FoodType::TOMATO, FoodType(0));
assert_eq!(FoodType::CUCUMBER, FoodType(1));
let carrot = FoodType(2);