1 use std::mem; 2 3 pub use heapsize_derive::*; 4 5 pub trait HeapSize { 6 /// Total number of bytes of heap memory owned by `self`. 7 /// 8 /// Does not include the size of `self` itself, which may or may not be on 9 /// the heap. Includes only children of `self`, meaning things pointed to by 10 /// `self`. heap_size_of_children(&self) -> usize11 fn heap_size_of_children(&self) -> usize; 12 } 13 14 // 15 // In a real version of this library there would be lots more impls here, but 16 // here are some interesting ones. 17 // 18 19 impl HeapSize for u8 { 20 /// A `u8` does not own any heap memory. heap_size_of_children(&self) -> usize21 fn heap_size_of_children(&self) -> usize { 22 0 23 } 24 } 25 26 impl HeapSize for String { 27 /// A `String` owns enough heap memory to hold its reserved capacity. heap_size_of_children(&self) -> usize28 fn heap_size_of_children(&self) -> usize { 29 self.capacity() 30 } 31 } 32 33 impl<T> HeapSize for Box<T> 34 where 35 T: ?Sized + HeapSize, 36 { 37 /// A `Box` owns however much heap memory was allocated to hold the value of 38 /// type `T` that we placed on the heap, plus transitively however much `T` 39 /// itself owns. heap_size_of_children(&self) -> usize40 fn heap_size_of_children(&self) -> usize { 41 mem::size_of_val(&**self) + (**self).heap_size_of_children() 42 } 43 } 44 45 impl<T> HeapSize for [T] 46 where 47 T: HeapSize, 48 { 49 /// Sum of heap memory owned by each element of a dynamically sized slice of 50 /// `T`. heap_size_of_children(&self) -> usize51 fn heap_size_of_children(&self) -> usize { 52 self.iter().map(HeapSize::heap_size_of_children).sum() 53 } 54 } 55 56 impl<'a, T> HeapSize for &'a T 57 where 58 T: ?Sized, 59 { 60 /// A shared reference does not own heap memory. heap_size_of_children(&self) -> usize61 fn heap_size_of_children(&self) -> usize { 62 0 63 } 64 } 65