Macro neli::impl_trait

source ·
macro_rules! impl_trait {
    (
        $(#[$outer:meta])*
        $vis_trait:vis $trait_name:ident,
        $to_from_ty:ty,
        $(
            #[$wrapper_outer:meta]
        )*
        $vis_enum:vis $wrapper_type:ident,
        $( $const_enum:ident ),+
        $(,)?
    ) => { ... };
}
Expand description

For generating a marker trait that flags a new enum as usable in a field that accepts a generic type. This way, the type parameter can be constrained by a trait bound to only accept enums that implement the marker trait.

Usage

use neli::neli_enum;

/// Define an enum
#[neli_enum(serialized_type = "u16")]
pub enum MyFamilyEnum {
    One = 1,
    Two = 2,
    Three = 3
}

/// Define another enum
#[neli_enum(serialized_type = "u16")]
pub enum MyOtherFamilyEnum {
    Four = 4,
    Five = 5,
    Six = 6,
}

/// Define a marker trait and implement it for MyFamilyEnum and
/// MyOtherFamilyEnum.
neli::impl_trait!(
    MyMarkerTrait,
    u16,
    MyFamilyWrapperType,
    MyFamilyEnum,
    MyOtherFamilyEnum
);

The result of the example above will be:

  • One enum called MyFamilyEnum.
  • Another called MyOtherFamilyEnum.
  • A marker trait called MyMarkerTrait. This can be used to constain type parameter so that only MyFamilyEnum and MyOtherFamilyEnum variants can be passed in as a value.
  • A wrapper enum called MyFamilyWrapperType. The definition is as follows:
enum MyFamilyEnum {
    One,
    Two,
    Three,
}

enum MyOtherFamilyEnum {
    Four,
    Five,
    Six,
}

enum MyFamilyWrapperType {
    MyFamilyEnum(MyFamilyEnum),
    MyOtherFamilyEnum(MyOtherFamilyEnum),
}

If you are unsure of which type will be passed back, the wrapper type can be used to automatically determine this for you when deserializing and accept all values defined across both enums.