From 6e2745d2183fb55417b7d5c6378bac97ba73009e Mon Sep 17 00:00:00 2001 From: David Palm Date: Sun, 15 Dec 2019 20:59:54 +0100 Subject: [PATCH] More tests for MallocSizeOf impl for SmallVec --- parity-util-mem/src/impls.rs | 46 +++++++++++++++++++++++++++++------- 1 file changed, 38 insertions(+), 8 deletions(-) diff --git a/parity-util-mem/src/impls.rs b/parity-util-mem/src/impls.rs index 6e9f19404..867e10cda 100644 --- a/parity-util-mem/src/impls.rs +++ b/parity-util-mem/src/impls.rs @@ -40,18 +40,17 @@ macro_rules! impl_smallvec { where T: MallocSizeOf, { - fn size_of(&self, _: &mut MallocSizeOfOps) -> usize { - if self.spilled() { - self.capacity() * core::mem::size_of::() - } else { - 0 + fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { + let mut n = 0; + for elem in self.iter() { + n += elem.size_of(ops); } + n } } }; } -// todo[dvdplm]: check if we really need all these impls. impl_smallvec!(32); // kvdb uses this impl_smallvec!(36); // trie-db uses this @@ -74,7 +73,7 @@ mod tests { impl_smallvec!(3); #[test] - fn test_smallvec() { + fn test_smallvec_stack_allocated_type() { let mut v: SmallVec<[u8; 3]> = SmallVec::new(); let mut ops = new_malloc_size_ops(); assert_eq!(v.size_of(&mut ops), 0); @@ -85,7 +84,38 @@ mod tests { assert!(!v.spilled()); v.push(4); assert!(v.spilled(), "SmallVec spills when going beyond the capacity of the inner backing array"); - assert_eq!(v.len(), 4); + assert_eq!(v.size_of(&mut ops), 0); // <–– WHY NOT 4? + } + + #[test] + fn test_smallvec_boxed_stack_allocated_type() { + let mut v: SmallVec<[Box; 3]> = SmallVec::new(); + let mut ops = new_malloc_size_ops(); + assert_eq!(v.size_of(&mut ops), 0); + v.push(Box::new(1u8)); + v.push(Box::new(2u8)); + v.push(Box::new(3u8)); + assert_eq!(v.size_of(&mut ops), 3); // <– shouldn't this be 3 * pointer_size = 24? + assert!(!v.spilled()); + v.push(Box::new(4u8)); + assert!(v.spilled(), "SmallVec spills when going beyond the capacity of the inner backing array"); + let mut ops = new_malloc_size_ops(); assert_eq!(v.size_of(&mut ops), 4); } + + #[test] + fn test_smallvec_heap_allocated_type() { + let mut v: SmallVec<[String; 3]> = SmallVec::new(); + let mut ops = new_malloc_size_ops(); + assert_eq!(v.size_of(&mut ops), 0); + v.push("COW".into()); + v.push("PIG".into()); + v.push("DUCK".into()); + assert!(!v.spilled()); + assert_eq!(v.size_of(&mut ops), 10); + v.push("ÖWL".into()); + assert!(v.spilled()); + let mut ops = new_malloc_size_ops(); + assert_eq!(v.size_of(&mut ops), 14); + } }