iota_util_mem/
sizeof.rs

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