From e0e9377d3ee39f7ed356c02ab4e0705e803fa4aa Mon Sep 17 00:00:00 2001 From: Troy Hinckley Date: Wed, 20 Sep 2023 08:56:02 -0500 Subject: [PATCH] Fix incorrect heap size value for boxed slice Previously the `GetSize` impl for a boxed slice didn't have a bound on `T`, so `get_size` was being called on `&T` instead of `T`. This meant that the size of each element was always being calculated to the size of a reference. This change fixes that and adds a test. --- src/lib.rs | 12 +++++------- tests/mod.rs | 13 +++++++++++++ 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index a9ff6f0..f3f8ceb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -501,13 +501,11 @@ impl GetSize for std::path::PathBuf { impl GetSize for &std::path::Path {} -impl GetSize for Box<[T]> { +impl GetSize for Box<[T]> +where + T: GetSize, +{ fn get_heap_size(&self) -> usize { - let mut total = 0; - for item in self.iter() { - total += item.get_size() - } - - total + self.iter().map(GetSize::get_size).sum() } } diff --git a/tests/mod.rs b/tests/mod.rs index 5bd5609..c161317 100644 --- a/tests/mod.rs +++ b/tests/mod.rs @@ -246,3 +246,16 @@ fn derive_newtype() { let test = TestNewType(0); assert_eq!(u64::get_stack_size(), test.get_size()); } + +#[test] +fn boxed_slice() { + use std::mem::size_of; + let boxed = vec![1u8; 10].into_boxed_slice(); + assert_eq!(boxed.get_heap_size(), size_of::() * boxed.len()); + + let boxed = vec![1u32; 10].into_boxed_slice(); + assert_eq!(boxed.get_heap_size(), size_of::() * boxed.len()); + + let boxed = vec![&1u8; 10].into_boxed_slice(); + assert_eq!(boxed.get_heap_size(), size_of::<&u8>() * boxed.len()); +}