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
#![feature(proc_macro, proc_macro_lib)]
#![cfg(not(test))]
extern crate proc_macro;
extern crate syn;
extern crate synstructure;
#[macro_use]
extern crate quote;
use proc_macro::TokenStream;
use synstructure::{each_field, BindStyle};
#[proc_macro_derive(Abomonation)]
pub fn derive_abomonation(input: TokenStream) -> TokenStream {
let source = input.to_string();
let mut ast = syn::parse_macro_input(&source).unwrap();
let entomb = each_field(&mut ast, &BindStyle::Ref.into(), |bi| {
quote! {
::abomonation::Abomonation::entomb(#bi, _writer);
}
});
let embalm = each_field(&mut ast, &BindStyle::RefMut.into(), |bi| {
quote! {
::abomonation::Abomonation::embalm(#bi);
}
});
let exhume = each_field(&mut ast, &BindStyle::RefMut.into(), |bi| {
quote! {
let temp = bytes;
let exhume_result = ::abomonation::Abomonation::exhume(#bi, temp);
bytes = if let Some(bytes) = exhume_result {
bytes
} else {
return None
};
}
});
let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let result = quote! {
#ast
impl #impl_generics ::abomonation::Abomonation for #name #ty_generics #where_clause {
#[inline] unsafe fn entomb(&self, _writer: &mut Vec<u8>) {
match *self { #entomb }
}
#[inline] unsafe fn embalm(&mut self) {
match *self { #embalm }
}
#[inline] unsafe fn exhume<'a,'b>(&'a mut self, mut bytes: &'b mut [u8])
-> Option<&'b mut [u8]> {
match *self { #exhume }
Some(bytes)
}
}
};
result.to_string().parse().unwrap()
}