#enum #derive #macro #custom_derive

enum_derive

This crate provides macros for deriving additional functionality for enums

4 releases

0.1.7 Aug 3, 2016
0.1.3 Dec 1, 2015
0.1.2 Sep 16, 2015
0.1.1 Aug 16, 2015

#83 in Rust patterns

Download history 227/week @ 2020-02-06 251/week @ 2020-02-13 281/week @ 2020-02-20 249/week @ 2020-02-27 291/week @ 2020-03-05 236/week @ 2020-03-12 327/week @ 2020-03-19 322/week @ 2020-03-26 292/week @ 2020-04-02 270/week @ 2020-04-09 424/week @ 2020-04-16 442/week @ 2020-04-23 260/week @ 2020-04-30 278/week @ 2020-05-07 435/week @ 2020-05-14 372/week @ 2020-05-21

1,127 downloads per month
Used in 21 crates (13 directly)

MIT/Apache

30KB
678 lines

macro-attr

This crate provides the macro_attr! macro that enables the use of custom, macro-based attributes and derivations. Supercedes the custom_derive crate.

Links

Compatibility

macro-attr is compatible with Rust 1.2 and higher.

Example

#[macro_use] extern crate macro_attr;

// Define some traits to be derived.

trait TypeName {
    fn type_name() -> &'static str;
}

trait ReprType {
    type Repr;
}

// Define macros which derive implementations of these macros.

macro_rules! TypeName {
    // We can support any kind of item we want.
    (() $(pub)* enum $name:ident $($tail:tt)*) => { TypeName! { @impl $name } };
    (() $(pub)* struct $name:ident $($tail:tt)*) => { TypeName! { @impl $name } };

    // Inner rule to cut down on repetition.
    (@impl $name:ident) => {
        impl TypeName for $name {
            fn type_name() -> &'static str { stringify!($name) }
        }
    };
}

macro_rules! ReprType {
    // Note that we use a "derivation argument" here for the `$repr` type.
    (($repr:ty) $(pub)* enum $name:ident $($tail:tt)*) => {
        impl ReprType for $name {
            type Repr = $repr;
        }
    };
}

// Here is a macro that *modifies* the item.

macro_rules! rename_to {
    (
        ($new_name:ident),
        then $cb:tt,
        $(#[$($attrs:tt)*])*
        enum $_old_name:ident $($tail:tt)*
    ) => {
        macro_attr_callback! {
            $cb,
            $(#[$($attrs)*])*
            enum $new_name $($tail)*
        }
    };
}

macro_attr! {
    #[allow(dead_code)]
    #[derive(Clone, Copy, Debug, ReprType!(u8), TypeName!)]
    #[rename_to!(Bar)]
    #[repr(u8)]
    enum Foo { A, B }
}

fn main() {
    let bar = Bar::B;
    let v = bar as <Bar as ReprType>::Repr;
    let msg = format!("{}: {:?} ({:?})", Bar::type_name(), bar, v);
    assert_eq!(msg, "Bar: B (1)");
}

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you shall be dual licensed as above, without any additional terms or conditions.

No runtime deps