A complete working Macros 1.1 implementation of a custom derive. Works on any Rust compiler >=1.15.0.
We are deriving the HeapSize
trait which computes an estimate of the amount of
heap memory owned by a value.
pub trait HeapSize {
/// Total number of bytes of heap memory owned by `self`.
fn heap_size_of_children(&self) -> usize;
}
The custom derive allows users to write #[derive(HeapSize)]
on data structures
in their program.
#[derive(HeapSize)]
struct Demo<'a, T: ?Sized> {
a: Box<T>,
b: u8,
c: &'a str,
d: String,
}
The trait impl generated by the custom derive here would look like:
impl<'a, T: ?Sized + ::heapsize::HeapSize> ::heapsize::HeapSize for Demo<'a, T> {
fn heap_size_of_children(&self) -> usize {
0 + ::heapsize::HeapSize::heap_size_of_children(&self.a)
+ ::heapsize::HeapSize::heap_size_of_children(&self.b)
+ ::heapsize::HeapSize::heap_size_of_children(&self.c)
+ ::heapsize::HeapSize::heap_size_of_children(&self.d)
}
}