Skip to main content

euv_performance/allocator/
impl.rs

1use super::*;
2
3/// Lock-free allocation recording helpers for `CountingAllocator`.
4impl CountingAllocator {
5    /// Records one completed heap allocation when tracking is active.
6    ///
7    /// # Arguments
8    ///
9    /// - `usize` - Allocated byte size from `Layout::size`.
10    #[inline(always)]
11    fn record_alloc(size: usize) {
12        if ALLOC_TRACK_DEPTH.load(Ordering::Relaxed) == 0 {
13            return;
14        }
15        let bytes: u64 = size as u64;
16        let signed: i64 = size as i64;
17        let _: u64 = ALLOC_COUNT.fetch_add(1, Ordering::Relaxed);
18        let _: u64 = BYTES_ALLOCATED.fetch_add(bytes, Ordering::Relaxed);
19        let _: i64 = LIVE_ALLOCS_DELTA.fetch_add(1, Ordering::Relaxed);
20        let next_live: i64 = LIVE_BYTES_DELTA
21            .fetch_add(signed, Ordering::Relaxed)
22            .saturating_add(signed);
23        if next_live > 0 {
24            let _: u64 = PEAK_LIVE_BYTES.fetch_max(next_live as u64, Ordering::Relaxed);
25        }
26    }
27
28    /// Records one completed heap deallocation when tracking is active.
29    ///
30    /// # Arguments
31    ///
32    /// - `usize` - Deallocated byte size from `Layout::size`.
33    #[inline(always)]
34    fn record_dealloc(size: usize) {
35        if ALLOC_TRACK_DEPTH.load(Ordering::Relaxed) == 0 {
36            return;
37        }
38        let bytes: u64 = size as u64;
39        let signed: i64 = size as i64;
40        let _: u64 = FREE_COUNT.fetch_add(1, Ordering::Relaxed);
41        let _: u64 = BYTES_FREED.fetch_add(bytes, Ordering::Relaxed);
42        let _: i64 = LIVE_ALLOCS_DELTA.fetch_sub(1, Ordering::Relaxed);
43        let _: i64 = LIVE_BYTES_DELTA.fetch_sub(signed, Ordering::Relaxed);
44    }
45
46    /// Records one completed heap reallocation when tracking is active.
47    ///
48    /// # Arguments
49    ///
50    /// - `usize` - Previous byte size from `Layout::size`.
51    /// - `usize` - New requested byte size.
52    #[inline(always)]
53    fn record_realloc(old_size: usize, new_size: usize) {
54        if ALLOC_TRACK_DEPTH.load(Ordering::Relaxed) == 0 {
55            return;
56        }
57        let _: u64 = ALLOC_COUNT.fetch_add(1, Ordering::Relaxed);
58        let _: u64 = FREE_COUNT.fetch_add(1, Ordering::Relaxed);
59        let _: u64 = BYTES_ALLOCATED.fetch_add(new_size as u64, Ordering::Relaxed);
60        let _: u64 = BYTES_FREED.fetch_add(old_size as u64, Ordering::Relaxed);
61        let delta: i64 = (new_size as i64).saturating_sub(old_size as i64);
62        let next_live: i64 = LIVE_BYTES_DELTA
63            .fetch_add(delta, Ordering::Relaxed)
64            .saturating_add(delta);
65        if next_live > 0 {
66            let _: u64 = PEAK_LIVE_BYTES.fetch_max(next_live as u64, Ordering::Relaxed);
67        }
68    }
69}
70
71/// Global allocator delegation with relaxed fast-path counting for `CountingAllocator`.
72unsafe impl GlobalAlloc for CountingAllocator {
73    /// Allocates memory through the system allocator and records bytes when tracking is active.
74    ///
75    /// # Arguments
76    ///
77    /// - `&Self` - Counting allocator reference.
78    /// - `Layout` - Requested memory layout.
79    ///
80    /// # Returns
81    ///
82    /// - `*mut u8` - Pointer to allocated memory or null on allocation failure.
83    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
84        let ptr: *mut u8 = unsafe { System.alloc(layout) };
85        if !ptr.is_null() {
86            Self::record_alloc(layout.size());
87        }
88        ptr
89    }
90
91    /// Deallocates memory through the system allocator and records freed bytes when tracking is active.
92    ///
93    /// # Arguments
94    ///
95    /// - `&Self` - Counting allocator reference.
96    /// - `*mut u8` - Pointer to previously allocated memory.
97    /// - `Layout` - Original allocation layout.
98    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
99        Self::record_dealloc(layout.size());
100        unsafe { System.dealloc(ptr, layout) };
101    }
102
103    /// Allocates zero-initialized memory through the system allocator and records bytes when tracking is active.
104    ///
105    /// # Arguments
106    ///
107    /// - `&Self` - Counting allocator reference.
108    /// - `Layout` - Requested memory layout.
109    ///
110    /// # Returns
111    ///
112    /// - `*mut u8` - Pointer to zeroed memory or null on allocation failure.
113    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
114        let ptr: *mut u8 = unsafe { System.alloc_zeroed(layout) };
115        if !ptr.is_null() {
116            Self::record_alloc(layout.size());
117        }
118        ptr
119    }
120
121    /// Reallocates memory through the system allocator and records byte deltas when tracking is active.
122    ///
123    /// # Arguments
124    ///
125    /// - `&Self` - Counting allocator reference.
126    /// - `*mut u8` - Pointer to previously allocated memory.
127    /// - `Layout` - Previous allocation layout.
128    /// - `usize` - New requested byte size.
129    ///
130    /// # Returns
131    ///
132    /// - `*mut u8` - Pointer to reallocated memory or null on failure.
133    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
134        let next: *mut u8 = unsafe { System.realloc(ptr, layout, new_size) };
135        if !next.is_null() {
136            Self::record_realloc(layout.size(), new_size);
137        }
138        next
139    }
140}
141
142/// Delta arithmetic for `RawAllocCounters`.
143impl RawAllocCounters {
144    /// Computes an `AllocationSnapshot` delta relative to an earlier `before` counter capture.
145    ///
146    /// # Arguments
147    ///
148    /// - `&Self` - Later counter snapshot.
149    /// - `RawAllocCounters` - Earlier baseline counter snapshot.
150    ///
151    /// # Returns
152    ///
153    /// - `AllocationSnapshot` - Exact allocation and byte delta between `before` and `self`.
154    #[must_use]
155    pub fn delta_since(&self, before: RawAllocCounters) -> AllocationSnapshot {
156        let alloc_count: u64 = self
157            .get_alloc_count()
158            .saturating_sub(before.get_alloc_count());
159        let free_count: u64 = self
160            .get_free_count()
161            .saturating_sub(before.get_free_count());
162        let bytes_allocated: u64 = self
163            .get_bytes_allocated()
164            .saturating_sub(before.get_bytes_allocated());
165        let bytes_freed: u64 = self
166            .get_bytes_freed()
167            .saturating_sub(before.get_bytes_freed());
168        let signed_live_bytes: i64 = self
169            .get_live_bytes_delta()
170            .saturating_sub(before.get_live_bytes_delta());
171        let signed_live_allocs: i64 = self
172            .get_live_allocs_delta()
173            .saturating_sub(before.get_live_allocs_delta());
174        let live_bytes_delta: u64 = if signed_live_bytes > 0 {
175            signed_live_bytes as u64
176        } else {
177            0
178        };
179        let live_allocs_delta: u64 = if signed_live_allocs > 0 {
180            signed_live_allocs as u64
181        } else {
182            0
183        };
184        let peak_live_bytes: u64 = self.get_peak_live_bytes().max(live_bytes_delta);
185        AllocationSnapshot::new(
186            alloc_count,
187            free_count,
188            bytes_allocated,
189            bytes_freed,
190            live_bytes_delta,
191            live_allocs_delta,
192            peak_live_bytes,
193        )
194    }
195}
196
197/// Scoped allocation tracking lifecycle for `AllocationScopeGuard`.
198impl AllocationScopeGuard {
199    /// Enters a serialized allocation tracking scope, resetting live-delta and peak counters on outermost entry.
200    ///
201    /// # Returns
202    ///
203    /// - `Self` - Active RAII scope guard that disables tracking on drop.
204    #[must_use]
205    pub fn enter() -> Self {
206        let already_in_scope: bool = ALLOC_THREAD_IN_SCOPE.with(|flag: &Cell<bool>| flag.get());
207        if already_in_scope {
208            let _: usize = ALLOC_TRACK_DEPTH.fetch_add(1, Ordering::AcqRel);
209            let start_counters: RawAllocCounters = snapshot_raw_alloc_counters();
210            return Self {
211                _lock_guard: None,
212                owns_scope: false,
213                start_counters,
214            };
215        }
216        let lock_guard: MutexGuard<'static, ()> = ALLOC_SCOPE_LOCK
217            .lock()
218            .unwrap_or_else(|poisoned: PoisonError<MutexGuard<'static, ()>>| poisoned.into_inner());
219        ALLOC_THREAD_IN_SCOPE.with(|flag: &Cell<bool>| flag.set(true));
220        LIVE_BYTES_DELTA.store(0, Ordering::Relaxed);
221        LIVE_ALLOCS_DELTA.store(0, Ordering::Relaxed);
222        PEAK_LIVE_BYTES.store(0, Ordering::Relaxed);
223        let _: usize = ALLOC_TRACK_DEPTH.fetch_add(1, Ordering::AcqRel);
224        fence(Ordering::SeqCst);
225        let start_counters: RawAllocCounters = snapshot_raw_alloc_counters();
226        Self {
227            _lock_guard: Some(lock_guard),
228            owns_scope: true,
229            start_counters,
230        }
231    }
232
233    /// Returns the cumulative `AllocationSnapshot` recorded since this guard was entered.
234    ///
235    /// # Arguments
236    ///
237    /// - `&Self` - Active allocation scope guard.
238    ///
239    /// # Returns
240    ///
241    /// - `AllocationSnapshot` - Elapsed allocation counts and bytes inside this scope.
242    #[must_use]
243    pub fn elapsed_snapshot(&self) -> AllocationSnapshot {
244        let Self { start_counters, .. } = *self;
245        fence(Ordering::SeqCst);
246        snapshot_raw_alloc_counters().delta_since(start_counters)
247    }
248}
249
250/// Automatic scope teardown for `AllocationScopeGuard`.
251impl Drop for AllocationScopeGuard {
252    /// Decrements the active tracking depth and releases thread scope ownership on drop.
253    ///
254    /// # Arguments
255    ///
256    /// - `&Self` - Dropping allocation scope guard.
257    fn drop(&mut self) {
258        let Self { owns_scope, .. } = *self;
259        fence(Ordering::SeqCst);
260        let _: usize = ALLOC_TRACK_DEPTH.fetch_sub(1, Ordering::AcqRel);
261        if owns_scope {
262            ALLOC_THREAD_IN_SCOPE.with(|flag: &Cell<bool>| flag.set(false));
263        }
264    }
265}