buffered_derive/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
use convert_case::{Case, Casing};
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{Data, DeriveInput, Fields};

#[proc_macro_attribute]
pub fn buffered(args: TokenStream, mut input: TokenStream) -> TokenStream {
    let item = syn::parse::<DeriveInput>(input.clone()).expect("Failed to parse");
    let ty = match item.data {
        Data::Struct(x) => x,
        _ => panic!("Buffed only works for structs"),
    };

    let (fields, types): (Vec<_>, Vec<_>) = match ty.fields {
        Fields::Named(x) => x.named,
        _ => panic!("Buffed only supports named field structs"),
    }
    .into_iter()
    .map(|f| (format_ident!("{}", f.ident.unwrap()), f.ty))
    .unzip();

    let buffered_name = format_ident!("{}Buffered", item.ident);
    let buffered_fields_name = format_ident!("{}Fields", item.ident);
    let buffered_fields_selector_name = format_ident!("{}FieldSelectors", item.ident);
    let uppercase_fields: Vec<_> = fields
        .iter()
        .map(|f| format!("{}", f).to_case(Case::UpperCamel))
        .map(|f| format_ident!("{}", f))
        .collect();

    let output: TokenStream = quote! {
        #[derive(Debug)]
        struct #buffered_name {
            #(#fields : Vec<#types>),*
        }

        #[derive(Debug)]
        enum #buffered_fields_name {
            #(#uppercase_fields(#types)),*
        }

        #[derive(Debug)]
        enum #buffered_fields_selector_name {
            #(#uppercase_fields),*
        }

        impl Buffered for #buffered_name {
            type Fields = #buffered_fields_name;

            fn push_field(&mut self, field: Self::Fields) -> Result<(), Self::Fields> {
                match field {
                    #(Self::Fields::#uppercase_fields(x) => self.#fields.push(x)),*
                }

                Ok(())
            }
        }

        impl #buffered_name {
            fn new() -> Self {
                Self {
                    #(#fields : Vec::new()),*
                }
            }
        }

    }
    .into();

    input.extend(output);
    input
}