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
extern crate proc_macro;
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, Data, DeriveInput, Fields};
#[proc_macro_derive(MemoryTraceHelper, attributes(name))]
pub fn memory_trace_reset_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = input.ident;
let reset_imp;
let sum_imp;
match input.data {
Data::Struct(ref s) => match s.fields {
Fields::Named(ref fields) => {
let reset_total = fields.named.iter().map(|f| {
let name = &f.ident;
quote! {
lhs_sum += self.#name;
rhs_sum += rhs.#name;
self.#name = rhs.#name;
}
});
reset_imp = quote! {
use tikv_alloc::trace::TraceEvent;
use std::cmp::Ordering;
let mut lhs_sum: usize = 0;
let mut rhs_sum: usize = 0;
#(#reset_total)*
match lhs_sum.cmp(&rhs_sum) {
Ordering::Greater => Some(TraceEvent::Sub(lhs_sum-rhs_sum)),
Ordering::Less => Some(TraceEvent::Add(rhs_sum-lhs_sum)),
Ordering::Equal => None,
}
};
let sum_total = fields.named.iter().map(|f| {
let name = &f.ident;
quote! {
sum += self.#name;
}
});
sum_imp = quote! {
let mut sum: usize = 0;
#(#sum_total)*
sum
};
}
_ => unimplemented!(),
},
_ => unimplemented!(),
};
let expanded = quote! {
impl #name {
#[inline]
pub fn reset(&mut self, rhs: Self) -> Option<tikv_alloc::trace::TraceEvent> {
#reset_imp
}
#[inline]
pub fn sum(&self) -> usize {
#sum_imp
}
}
};
TokenStream::from(expanded)
}