nadir_platform/
alloc_counter.rs1use std::alloc::{GlobalAlloc, Layout, System};
30use std::cell::Cell;
31use std::sync::atomic::{AtomicU64, Ordering};
32
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35pub struct AllocCounts {
36 pub allocations: u64,
39 pub deallocations: u64,
41 pub bytes: u64,
44}
45
46impl AllocCounts {
47 #[must_use]
49 pub fn since(self, earlier: AllocCounts) -> AllocCounts {
50 AllocCounts {
51 allocations: self.allocations.wrapping_sub(earlier.allocations),
52 deallocations: self.deallocations.wrapping_sub(earlier.deallocations),
53 bytes: self.bytes.wrapping_sub(earlier.bytes),
54 }
55 }
56}
57
58pub fn thread_alloc_counts() -> AllocCounts {
60 THREAD.try_with(Cell::get).unwrap_or_default()
61}
62
63pub fn process_alloc_counts() -> AllocCounts {
65 AllocCounts {
66 allocations: PROCESS_ALLOCATIONS.load(Ordering::Relaxed),
67 deallocations: PROCESS_DEALLOCATIONS.load(Ordering::Relaxed),
68 bytes: PROCESS_BYTES.load(Ordering::Relaxed),
69 }
70}
71
72const ZERO: AllocCounts = AllocCounts {
73 allocations: 0,
74 deallocations: 0,
75 bytes: 0,
76};
77
78thread_local! {
79 static THREAD: Cell<AllocCounts> = const { Cell::new(ZERO) };
83}
84
85static PROCESS_ALLOCATIONS: AtomicU64 = AtomicU64::new(0);
86static PROCESS_DEALLOCATIONS: AtomicU64 = AtomicU64::new(0);
87static PROCESS_BYTES: AtomicU64 = AtomicU64::new(0);
88
89fn count_allocation(bytes: usize) {
92 let bytes = bytes as u64;
93 PROCESS_ALLOCATIONS.fetch_add(1, Ordering::Relaxed);
94 PROCESS_BYTES.fetch_add(bytes, Ordering::Relaxed);
95 let _ = THREAD.try_with(|counts| {
97 let mut thread = counts.get();
98 thread.allocations = thread.allocations.wrapping_add(1);
99 thread.bytes = thread.bytes.wrapping_add(bytes);
100 counts.set(thread);
101 });
102}
103
104fn count_deallocation() {
106 PROCESS_DEALLOCATIONS.fetch_add(1, Ordering::Relaxed);
107 let _ = THREAD.try_with(|counts| {
108 let mut thread = counts.get();
109 thread.deallocations = thread.deallocations.wrapping_add(1);
110 counts.set(thread);
111 });
112}
113
114struct Counting;
116
117#[global_allocator]
118static ALLOCATOR: Counting = Counting;
119
120unsafe impl GlobalAlloc for Counting {
125 unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
126 let pointer = unsafe { System.alloc(layout) };
129 if !pointer.is_null() {
130 count_allocation(layout.size());
131 }
132 pointer
133 }
134
135 unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
136 let pointer = unsafe { System.alloc_zeroed(layout) };
138 if !pointer.is_null() {
139 count_allocation(layout.size());
140 }
141 pointer
142 }
143
144 unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
145 let moved = unsafe { System.realloc(pointer, layout, new_size) };
149 if !moved.is_null() {
150 count_allocation(new_size);
151 }
152 moved
153 }
154
155 unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {
156 unsafe { System.dealloc(pointer, layout) };
159 count_deallocation();
160 }
161}
162
163#[cfg(test)]
164mod tests {
165 use std::hint::black_box;
166 use std::thread;
167
168 use super::*;
169
170 #[test]
171 fn a_box_counts_one_allocation_of_its_size_and_one_deallocation() {
172 let start = thread_alloc_counts();
173 let boxed = black_box(Box::new([7u8; 100]));
174 let allocated = thread_alloc_counts().since(start);
175 drop(boxed);
176 let freed = thread_alloc_counts().since(start);
177 assert_eq!(
178 allocated,
179 AllocCounts {
180 allocations: 1,
181 deallocations: 0,
182 bytes: 100
183 }
184 );
185 assert_eq!(
186 freed,
187 AllocCounts {
188 allocations: 1,
189 deallocations: 1,
190 bytes: 100
191 }
192 );
193 }
194
195 #[test]
196 fn a_vec_counts_its_growth_and_not_its_reuse() {
197 let start = thread_alloc_counts();
198 let mut numbers: Vec<u64> = Vec::with_capacity(4);
199 for number in 0..1000 {
200 numbers.push(black_box(number));
201 }
202 let grown = thread_alloc_counts().since(start);
203 assert!((2..=12).contains(&grown.allocations), "{grown:?}");
205 assert_eq!(
206 grown.deallocations, 0,
207 "a reallocation is not a deallocation"
208 );
209
210 numbers.clear();
211 let refilled = thread_alloc_counts();
212 for number in 0..1000 {
213 numbers.push(black_box(number));
214 }
215 assert_eq!(
216 thread_alloc_counts().since(refilled),
217 AllocCounts::default()
218 );
219 }
220
221 #[test]
222 fn another_threads_allocations_count_for_the_process_and_not_here() {
223 const MIB: u64 = 1 << 20;
224 let (here, process) = (thread_alloc_counts(), process_alloc_counts());
225 let theirs = thread::spawn(|| {
226 let start = thread_alloc_counts();
227 drop(black_box(vec![1u8; MIB as usize]));
228 thread_alloc_counts().since(start)
229 })
230 .join()
231 .expect("the thread runs");
232 assert_eq!(theirs.allocations, 1);
233 assert_eq!(theirs.bytes, MIB);
234 let mine = thread_alloc_counts().since(here);
236 assert!(mine.bytes < MIB, "{mine:?}");
237 assert!(process_alloc_counts().since(process).bytes >= MIB);
240 }
241}