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
73
74
75
76
77
78
79
80
81
use quote::quote;
use syn::*;

// TODO: use correct spans so errors are shown on fields

pub fn derive_encode(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let item = parse_macro_input!(item as DeriveInput);

    let name = &item.ident;

    let field_names: Vec<_> = struct_fields(&item).map(|field| &field.ident).collect();

    let mut field_names_minus_last: Vec<_> =
        struct_fields(&item).map(|field| &field.ident).collect();
    field_names_minus_last.pop();

    let output = quote! {
        impl orga::Encode for #name {
            fn encode_into<W: std::io::Write>(&self, mut dest: &mut W) -> orga::Result<()> {
                fn assert_trait_bounds<T: orga::Encode + orga::Terminated>(_: &T) {}
                #(assert_trait_bounds(&self.#field_names_minus_last);)*

                #(self.#field_names.encode_into(&mut dest)?;)*

                Ok(())
            }

            fn encoding_length(&self) -> orga::Result<usize> {
                Ok(
                    0 #( + self.#field_names.encoding_length()?)*
                )
            }
        }
    };

    output.into()
}

pub fn derive_decode(item: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let item = parse_macro_input!(item as DeriveInput);

    let name = &item.ident;

    let field_names: Vec<_> = struct_fields(&item).map(|field| &field.ident).collect();

    let output = quote! {
        impl orga::Decode for #name {
            fn decode<R: std::io::Read>(mut input: R) -> orga::Result<Self> {
                Ok(Self {
                    #(
                        #field_names: orga::Decode::decode(&mut input)?,
                    )*
                })
            }

            fn decode_into<R: std::io::Read>(&mut self, mut input: R) -> orga::Result<()> {
                #(
                    self.#field_names.decode_into(&mut input)?;
                )*

                Ok(())
            }
        }
    };

    output.into()
}

fn struct_fields<'a>(
    item: &'a DeriveInput
) -> impl Iterator<Item=&'a Field> {
    let data = match item.data {
        Data::Struct(ref data) => data,
        _ => panic!("Currently only structs are supported")
    };
    match data.fields {
        Fields::Named(ref fields) => fields.named.iter(),
        Fields::Unnamed(ref fields) => fields.unnamed.iter(),
        Fields::Unit => panic!("Unit structs are not supported")
    }
}