derive_utils 0.3.0

A procedural macro helper for trait implemention for enums.
Documentation

derive_utils

Build Status version documentation license Rustc Version

A procedural macro helper for trait implemention for enums.

Usage

Add this to your Cargo.toml:

[dependencies]
derive_utils = "0.3"

and this to your crate root:

extern crate derive_utils;

Examples

extern crate derive_utils;
extern crate proc_macro;
extern crate syn;

use derive_utils::{derive_trait, EnumData};
use proc_macro::TokenStream;
use syn::DeriveInput;

#[proc_macro_derive(Iterator)]
pub fn derive(input: TokenStream) -> TokenStream {
    let ast: DeriveInput = syn::parse(input).unwrap();
    let data = EnumData::from_derive(&ast).unwrap();

    derive_trait!(
        data,
        // path
        (Iterator),
        // trait
        trait Iterator {
            type Item;
            fn next(&mut self) -> Option<Self::Item>;
            fn size_hint(&self) -> (usize, Option<usize>);
        }
    )
    .unwrap()
    .into()
}

Generated code

When deriving for enum like the following:

#[derive(Iterator)]
enum Iter<A, B> {
    A(A),
    B(B),
}

Code like this will be generated:

enum Iter<A, B> {
    A(A),
    B(B),
}

impl<A, B> Iterator for Iter<A, B>
where
    A: Iterator,
    B: Iterator<Item = <A as Iterator>::Item>,
{
    type Item = <A as Iterator>::Item;
    fn next(&mut self) -> Option<Self::Item> {
        match self {
            Iter::A(x) => x.next(),
            Iter::B(x) => x.next(),
        }
    }
    fn size_hint(&self) -> (usize, Option<usize>) {
        match self {
            Iter::A(x) => x.size_hint(),
            Iter::B(x) => x.size_hint(),
        }
    }
}

See auto_enums crate for more examples.

Crate Features

  • std
    • Enabled by default.
    • Generate code for std library.
    • Disable to generate code for no_std.

Rust Version

The current minimum required Rust version is 1.30.

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, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.