@@ -24,23 +24,37 @@ cfg_if::cfg_if! {
2424 /// Global allocator
2525 #[ global_allocator]
2626 pub static ALLOC : jemallocator:: Jemalloc = jemallocator:: Jemalloc ;
27+
28+ mod memory_stats_jemalloc;
29+ use memory_stats_jemalloc as memory_stats;
2730 } else if #[ cfg( feature = "dlmalloc-global" ) ] {
2831 /// Global allocator
2932 #[ global_allocator]
3033 pub static ALLOC : dlmalloc:: GlobalDlmalloc = dlmalloc:: GlobalDlmalloc ;
34+
35+ mod memory_stats_noop;
36+ use memory_stats_noop as memory_stats;
3137 } else if #[ cfg( feature = "weealloc-global" ) ] {
3238 /// Global allocator
3339 #[ global_allocator]
3440 pub static ALLOC : wee_alloc:: WeeAlloc = wee_alloc:: WeeAlloc :: INIT ;
41+
42+ mod memory_stats_noop;
43+ use memory_stats_noop as memory_stats;
3544 } else if #[ cfg( all(
3645 feature = "mimalloc-global" ,
3746 not( target_arch = "wasm32" )
3847 ) ) ] {
3948 /// Global allocator
4049 #[ global_allocator]
4150 pub static ALLOC : mimalloc:: MiMalloc = mimalloc:: MiMalloc ;
51+
52+ mod memory_stats_noop;
53+ use memory_stats_noop as memory_stats;
4254 } else {
4355 // default allocator used
56+ mod memory_stats_noop;
57+ use memory_stats_noop as memory_stats;
4458 }
4559}
4660
@@ -78,6 +92,48 @@ pub fn malloc_size<T: MallocSizeOf + ?Sized>(t: &T) -> usize {
7892 MallocSizeOf :: size_of ( t, & mut allocators:: new_malloc_size_ops ( ) )
7993}
8094
95+ /// An error related to the memory stats gathering.
96+ #[ derive( Clone , Debug ) ]
97+ pub struct MemoryStatsError ( memory_stats:: Error ) ;
98+
99+ #[ cfg( feature = "std" ) ]
100+ impl std:: fmt:: Display for MemoryStatsError {
101+ fn fmt ( & self , fmt : & mut std:: fmt:: Formatter ) -> std:: fmt:: Result {
102+ self . 0 . fmt ( fmt)
103+ }
104+ }
105+
106+ #[ cfg( feature = "std" ) ]
107+ impl std:: error:: Error for MemoryStatsError { }
108+
109+ /// Snapshot of collected memory metrics.
110+ #[ non_exhaustive]
111+ #[ derive( Debug , Clone ) ]
112+ pub struct MemoryAllocationSnapshot {
113+ /// Total resident memory, in bytes.
114+ pub resident : u64 ,
115+ /// Total allocated memory, in bytes.
116+ pub allocated : u64 ,
117+ }
118+
119+ /// Accessor to the allocator internals.
120+ #[ derive( Clone ) ]
121+ pub struct MemoryAllocationTracker ( self :: memory_stats:: MemoryAllocationTracker ) ;
122+
123+ impl MemoryAllocationTracker {
124+ /// Create an instance of an allocation tracker.
125+ pub fn new ( ) -> Result < Self , MemoryStatsError > {
126+ self :: memory_stats:: MemoryAllocationTracker :: new ( )
127+ . map ( MemoryAllocationTracker )
128+ . map_err ( MemoryStatsError )
129+ }
130+
131+ /// Create an allocation snapshot.
132+ pub fn snapshot ( & self ) -> Result < MemoryAllocationSnapshot , MemoryStatsError > {
133+ self . 0 . snapshot ( ) . map_err ( MemoryStatsError )
134+ }
135+ }
136+
81137#[ cfg( feature = "std" ) ]
82138#[ cfg( test) ]
83139mod test {
0 commit comments