parity_util_mem/
sizeof.rs

1// Copyright 2020 Parity Technologies
2//
3// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6// option. This file may not be copied, modified, or distributed
7// except according to those terms.
8
9//! Estimation for heapsize calculation. Usable to replace call to allocator method (for some
10//! allocators or simply because we just need a deterministic cunsumption measurement).
11
12use crate::malloc_size::{MallocShallowSizeOf, MallocSizeOf, MallocSizeOfOps, MallocUnconditionalShallowSizeOf};
13#[cfg(not(feature = "std"))]
14use alloc::boxed::Box;
15#[cfg(not(feature = "std"))]
16use alloc::string::String;
17#[cfg(not(feature = "std"))]
18use alloc::sync::Arc;
19#[cfg(not(feature = "std"))]
20use alloc::vec::Vec;
21#[cfg(not(feature = "std"))]
22use core::mem::{size_of, size_of_val};
23
24#[cfg(feature = "std")]
25use std::mem::{size_of, size_of_val};
26#[cfg(feature = "std")]
27use std::sync::Arc;
28
29impl<T: ?Sized> MallocShallowSizeOf for Box<T> {
30	fn shallow_size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
31		size_of_val(&**self)
32	}
33}
34
35impl MallocSizeOf for String {
36	fn size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
37		self.capacity() * size_of::<u8>()
38	}
39}
40
41impl<T> MallocShallowSizeOf for Vec<T> {
42	fn shallow_size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
43		self.capacity() * size_of::<T>()
44	}
45}
46
47impl<T> MallocUnconditionalShallowSizeOf for Arc<T> {
48	fn unconditional_shallow_size_of(&self, _ops: &mut MallocSizeOfOps) -> usize {
49		size_of::<T>()
50	}
51}