Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion parity-util-mem/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -73,10 +73,17 @@ pub use malloc_size::{MallocSizeOf, MallocSizeOfOps};

pub use parity_util_mem_derive::*;

/// Heap size of structure.
///
/// Structure can be anything that implements MallocSizeOf.
pub fn malloc_size<T: MallocSizeOf + ?Sized>(t: &T) -> usize {
MallocSizeOf::size_of(t, &mut allocators::new_malloc_size_ops())
}

#[cfg(feature = "std")]
#[cfg(test)]
mod test {
use super::MallocSizeOfExt;
use super::{malloc_size, MallocSizeOf, MallocSizeOfExt};
use std::sync::Arc;

#[test]
Expand All @@ -85,4 +92,12 @@ mod test {
let s = val.malloc_size_of();
assert!(s > 0);
}

#[test]
fn test_dyn() {
trait Augmented: MallocSizeOf {}
impl Augmented for Vec<u8> {}
let val: Arc<dyn Augmented> = Arc::new(vec![0u8; 1024]);
assert!(malloc_size(&*val) > 1000);
Copy link
Copy Markdown
Contributor

@ordian ordian Jan 1, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does it actually use Arc in calculation? Dereference implies that it doesn't?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, it does not, it uses those of the dereferenced trait.

This is for cases when you know that Arc is the primary reference

MallocSizeOf is not defined for Arc<T: ?Sized>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, measuring MallocSizeOf for an Arc is tricky, but I wonder why a type is required to be Sized for Arc (in MallocUnconditionalShallowSizeOf), but not for Box.

Anyway, my point was that using Arc in tests causes a bit of confusion, we can use a trait object here directly, something like

let val = vec![0u8; 1024];
let val_ref: &dyn Augmented = &val as _; 
assert!(malloc_size(val_ref) > 1000);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am also wondering about those constraints.

About the test, I only wanted to show how to measure Arc in the test, also to ensure the exactly Arc<dyn Trait> can be measured -- it is a higher-level requirement, so hope we can have it as it is.

}
}