1#![allow(clippy::all)]
18#![cfg_attr(not(feature = "std"), no_std)]
19
20#[cfg(not(feature = "std"))]
21extern crate alloc;
22
23mod memory_stats_noop;
25
26pub mod allocators;
27
28use memory_stats_noop as memory_stats;
29
30#[cfg(any(
31 any(target_os = "macos", target_os = "ios"),
32 feature = "estimate-heapsize"
33))]
34pub mod sizeof;
35
36#[macro_use]
43mod malloc_size;
44
45pub mod external_impls;
46
47pub use allocators::MallocSizeOfExt;
48pub use iota_util_mem_derive::*;
49pub use malloc_size::{MallocShallowSizeOf, MallocSizeOf, MallocSizeOfOps};
50
51pub fn malloc_size<T: MallocSizeOf + ?Sized>(t: &T) -> usize {
55 MallocSizeOf::size_of(t, &mut allocators::new_malloc_size_ops())
56}
57
58#[derive(Clone, Debug)]
60pub struct MemoryStatsError(memory_stats::Error);
61
62#[cfg(feature = "std")]
63impl std::fmt::Display for MemoryStatsError {
64 fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
65 self.0.fmt(fmt)
66 }
67}
68
69#[cfg(feature = "std")]
70impl std::error::Error for MemoryStatsError {}
71
72#[non_exhaustive]
74#[derive(Debug, Clone)]
75pub struct MemoryAllocationSnapshot {
76 pub resident: u64,
78 pub allocated: u64,
80}
81
82#[derive(Clone)]
84pub struct MemoryAllocationTracker(self::memory_stats::MemoryAllocationTracker);
85
86impl MemoryAllocationTracker {
87 pub fn new() -> Result<Self, MemoryStatsError> {
89 self::memory_stats::MemoryAllocationTracker::new()
90 .map(MemoryAllocationTracker)
91 .map_err(MemoryStatsError)
92 }
93
94 pub fn snapshot(&self) -> Result<MemoryAllocationSnapshot, MemoryStatsError> {
96 self.0.snapshot().map_err(MemoryStatsError)
97 }
98}
99
100#[cfg(feature = "std")]
101#[cfg(test)]
102mod test {
103 use std::sync::Arc;
104
105 use super::{MallocSizeOf, MallocSizeOfExt, malloc_size};
106
107 #[test]
108 fn test_arc() {
109 let val = Arc::new("test".to_string());
110 let s = val.malloc_size_of();
111 assert!(s > 0);
112 }
113
114 #[test]
115 fn test_dyn() {
116 trait Augmented: MallocSizeOf {}
117 impl Augmented for Vec<u8> {}
118 let val: Arc<dyn Augmented> = Arc::new(vec![0u8; 1024]);
119 assert!(malloc_size(&*val) > 1000);
120 }
121}