tetsy_util_mem_derive/
lib.rs1extern crate proc_macro2;
15#[macro_use]
16extern crate syn;
17#[macro_use]
18extern crate synstructure;
19
20#[cfg(not(test))]
21decl_derive!([MallocSizeOf, attributes(ignore_malloc_size_of)] => malloc_size_of_derive);
22
23fn malloc_size_of_derive(s: synstructure::Structure) -> proc_macro2::TokenStream {
24 let match_body = s.each(|binding| {
25 let ignore = binding.ast().attrs.iter().any(|attr| match attr.parse_meta().unwrap() {
26 syn::Meta::Path(ref path) | syn::Meta::List(syn::MetaList { ref path, .. })
27 if path.is_ident("ignore_malloc_size_of") =>
28 {
29 panic!(
30 "#[ignore_malloc_size_of] should have an explanation, \
31 e.g. #[ignore_malloc_size_of = \"because reasons\"]"
32 );
33 }
34 syn::Meta::NameValue(syn::MetaNameValue { ref path, .. }) if path.is_ident("ignore_malloc_size_of") => true,
35 _ => false,
36 });
37 if ignore {
38 None
39 } else if let syn::Type::Array(..) = binding.ast().ty {
40 Some(quote! {
41 for item in #binding.iter() {
42 sum += tetsy_util_mem::MallocSizeOf::size_of(item, ops);
43 }
44 })
45 } else {
46 Some(quote! {
47 sum += tetsy_util_mem::MallocSizeOf::size_of(#binding, ops);
48 })
49 }
50 });
51
52 let ast = s.ast();
53 let name = &ast.ident;
54 let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
55 let mut where_clause = where_clause.unwrap_or(&parse_quote!(where)).clone();
56 for param in ast.generics.type_params() {
57 let ident = ¶m.ident;
58 where_clause.predicates.push(parse_quote!(#ident: tetsy_util_mem::MallocSizeOf));
59 }
60
61 let tokens = quote! {
62 impl #impl_generics tetsy_util_mem::MallocSizeOf for #name #ty_generics #where_clause {
63 #[inline]
64 #[allow(unused_variables, unused_mut, unreachable_code)]
65 fn size_of(&self, ops: &mut tetsy_util_mem::MallocSizeOfOps) -> usize {
66 let mut sum = 0;
67 match *self {
68 #match_body
69 }
70 sum
71 }
72 }
73 };
74
75 tokens
76}