1#![cfg(not(target_arch = "wasm32"))]
4
5#[cfg(feature = "stable-memory")]
6pub mod memory;
7
8use std::{
9 alloc::{GlobalAlloc, Layout, System},
10 cell::Cell,
11 time::{Duration, Instant},
12};
13
14#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
21pub struct Measurement {
22 pub allocations: usize,
24 pub reallocations: usize,
26 pub net_bytes: i128,
28 pub peak_bytes: usize,
30 pub elapsed: Duration,
32}
33
34#[derive(Clone, Copy, Default)]
35struct State {
36 active: bool,
37 counts: Measurement,
38}
39thread_local! { static STATE: Cell<State> = const { Cell::new(State {
40 active: false,
41 counts: Measurement { allocations: 0, reallocations: 0, net_bytes: 0, peak_bytes: 0, elapsed: Duration::ZERO },
42}) }; }
43
44fn account(old: usize, new: usize, allocation: bool, reallocation: bool) {
45 let _ = STATE.try_with(|cell| {
46 let mut state = cell.get();
47 if state.active {
48 state.counts.net_bytes += new as i128 - old as i128;
49 state.counts.peak_bytes = state
50 .counts
51 .peak_bytes
52 .max(usize::try_from(state.counts.net_bytes).unwrap_or(0));
53 state.counts.allocations += usize::from(allocation);
54 state.counts.reallocations += usize::from(reallocation);
55 cell.set(state);
56 }
57 });
58}
59
60pub struct MeasuredAllocator<A = System> {
68 allocator: A,
69}
70impl<A> MeasuredAllocator<A> {
71 #[must_use]
73 pub const fn new(allocator: A) -> Self {
74 Self { allocator }
75 }
76}
77
78#[expect(
79 unsafe_code,
80 reason = "forward the GlobalAlloc contract to the caller-selected allocator"
81)]
82unsafe impl<A: GlobalAlloc> GlobalAlloc for MeasuredAllocator<A> {
83 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
84 let pointer = unsafe { self.allocator.alloc(layout) };
86 if !pointer.is_null() {
87 account(0, layout.size(), true, false);
88 }
89 pointer
90 }
91 unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
92 let pointer = unsafe { self.allocator.alloc_zeroed(layout) };
94 if !pointer.is_null() {
95 account(0, layout.size(), true, false);
96 }
97 pointer
98 }
99 unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
100 account(layout.size(), 0, false, false);
101 unsafe { self.allocator.dealloc(pointer, layout) };
103 }
104 unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, size: usize) -> *mut u8 {
105 let result = unsafe { self.allocator.realloc(pointer, layout, size) };
107 if !result.is_null() {
108 account(layout.size(), size, false, true);
109 }
110 result
111 }
112}
113
114#[derive(Clone, Copy, Debug, Eq, PartialEq)]
121pub struct AlreadyMeasuring;
122impl std::fmt::Display for AlreadyMeasuring {
123 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124 f.write_str("allocation measurement already active on this thread")
125 }
126}
127impl std::error::Error for AlreadyMeasuring {}
128
129struct Guard;
130impl Drop for Guard {
131 fn drop(&mut self) {
132 STATE.with(|cell| cell.set(State::default()));
133 }
134}
135
136pub fn measure(
144 iterations: usize,
145 mut operation: impl FnMut(),
146) -> Result<Measurement, AlreadyMeasuring> {
147 STATE.with(|cell| {
148 if cell.get().active {
149 return Err(AlreadyMeasuring);
150 }
151 cell.set(State {
152 active: true,
153 ..State::default()
154 });
155 Ok(())
156 })?;
157 let guard = Guard;
158 let started = Instant::now();
159 for _ in 0..iterations {
160 operation();
161 }
162 let elapsed = started.elapsed();
163 let mut counts = STATE.with(|cell| cell.get().counts);
164 drop(guard);
165 counts.elapsed = elapsed;
166 Ok(counts)
167}