alloc_tracker 0.5.19

Memory allocation tracking utilities for benchmarks and performance analysis
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
//! Memory allocation tracking reports.

use std::collections::HashMap;
use std::fmt;

/// Thread-safe memory allocation tracking report.
///
/// A `Report` contains the captured memory allocation statistics from a [`Session`](crate::Session)
/// and can be safely sent to other threads for processing. Reports can be merged together
/// and processed independently.
///
/// # Examples
///
/// ```
/// use alloc_tracker::{Allocator, Session};
///
/// #[global_allocator]
/// static ALLOCATOR: Allocator<std::alloc::System> = Allocator::system();
///
/// # fn main() {
/// let session = Session::new();
/// {
///     let operation = session.operation("test_work");
///     let _span = operation.measure_process();
///     let _data = vec![1, 2, 3, 4, 5]; // This allocates memory
/// }
///
/// let report = session.to_report();
/// report.print_to_stdout();
/// # }
/// ```
///
/// # Merging reports
///
/// ```
/// use alloc_tracker::{Allocator, Report, Session};
///
/// #[global_allocator]
/// static ALLOCATOR: Allocator<std::alloc::System> = Allocator::system();
///
/// # fn main() {
/// // Create two separate sessions
/// let session1 = Session::new();
/// let session2 = Session::new();
///
/// // Record some work in each
/// {
///     let op1 = session1.operation("work");
///     let _span1 = op1.measure_process();
///     let _data1 = vec![1, 2, 3]; // This allocates memory
/// }
///
/// {
///     let op2 = session2.operation("work");
///     let _span2 = op2.measure_process();
///     let _data2 = vec![4, 5, 6, 7]; // This allocates more memory
/// }
///
/// // Convert to reports and merge
/// let report1 = session1.to_report();
/// let report2 = session2.to_report();
/// let merged = Report::merge(&report1, &report2);
///
/// merged.print_to_stdout();
/// # }
/// ```
#[derive(Clone, Debug, Default)]
pub struct Report {
    operations: HashMap<String, ReportOperation>,
}

/// Memory allocation statistics for a single operation in a report.
#[derive(Clone, Debug)]
#[expect(
    clippy::struct_field_names,
    reason = "field names are descriptive and clear"
)]
pub struct ReportOperation {
    total_bytes_allocated: u64,
    total_allocations_count: u64,
    total_iterations: u64,
}

impl Report {
    /// Creates an empty report.
    #[cfg(test)]
    #[must_use]
    pub(crate) fn new() -> Self {
        Self {
            operations: HashMap::new(),
        }
    }

    /// Creates a report from shared operation data.
    #[must_use]
    pub(crate) fn from_operation_data(
        operation_data: &HashMap<String, crate::operation_metrics::OperationMetrics>,
    ) -> Self {
        let report_operations = operation_data
            .iter()
            .map(|(name, op_data)| {
                (
                    name.clone(),
                    ReportOperation {
                        total_bytes_allocated: op_data.total_bytes_allocated,
                        total_allocations_count: op_data.total_allocations_count,
                        total_iterations: op_data.total_iterations,
                    },
                )
            })
            .collect();

        Self {
            operations: report_operations,
        }
    }

    /// Merges two reports into a new report.
    ///
    /// The resulting report contains the combined statistics from both input reports.
    /// Operations with the same name have their statistics combined as if all spans
    /// had been recorded through a single session.
    ///
    /// # Examples
    ///
    /// ```
    /// use alloc_tracker::{Allocator, Report, Session};
    ///
    /// #[global_allocator]
    /// static ALLOCATOR: Allocator<std::alloc::System> = Allocator::system();
    ///
    /// # fn main() {
    /// let session1 = Session::new();
    /// let session2 = Session::new();
    ///
    /// // Both sessions record the same operation name
    /// {
    ///     let op1 = session1.operation("common_work");
    ///     let _span1 = op1.measure_process();
    ///     let _data1 = vec![1, 2, 3]; // 3 elements
    /// }
    ///
    /// {
    ///     let op2 = session2.operation("common_work");
    ///     let _span2 = op2.measure_process();
    ///     let _data2 = vec![4, 5]; // 2 elements
    /// }
    ///
    /// let report1 = session1.to_report();
    /// let report2 = session2.to_report();
    ///
    /// // Merged report shows combined statistics (2 total iterations)
    /// let merged = Report::merge(&report1, &report2);
    /// # }
    /// ```
    #[must_use]
    pub fn merge(a: &Self, b: &Self) -> Self {
        let mut merged_operations = a.operations.clone();

        for (name, b_op) in &b.operations {
            merged_operations
                .entry(name.clone())
                .and_modify(|a_op| {
                    a_op.total_bytes_allocated = a_op
                        .total_bytes_allocated
                        .checked_add(b_op.total_bytes_allocated)
                        .expect("merging bytes allocated overflows u64 - this indicates an unrealistic scenario");

                    a_op.total_allocations_count = a_op
                        .total_allocations_count
                        .checked_add(b_op.total_allocations_count)
                        .expect("merging allocations count overflows u64 - this indicates an unrealistic scenario");

                    a_op.total_iterations = a_op
                        .total_iterations
                        .checked_add(b_op.total_iterations)
                        .expect("merging iteration counts overflows u64 - this indicates an unrealistic scenario");
                })
                .or_insert_with(|| b_op.clone());
        }

        Self {
            operations: merged_operations,
        }
    }

    /// Prints the memory allocation statistics to stdout.
    ///
    /// Prints nothing if no operations were captured. This may indicate that the session
    /// was part of a "list available benchmarks" probe run instead of some real activity,
    /// in which case printing anything might violate the output protocol the tool is speaking.
    #[cfg_attr(test, mutants::skip)] // Too difficult to test stdout output reliably - manually tested.
    pub fn print_to_stdout(&self) {
        if self.is_empty() {
            return;
        }
        println!("{self}");
    }

    /// Whether there is any recorded activity in this report.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.operations.is_empty() || self.operations.values().all(|op| op.total_iterations == 0)
    }

    /// Returns an iterator over the operation names and their statistics.
    ///
    /// This allows programmatic access to the same data that would be printed by
    /// [`print_to_stdout()`](Self::print_to_stdout).
    ///
    /// # Examples
    ///
    /// ```
    /// use alloc_tracker::{Allocator, Session};
    ///
    /// #[global_allocator]
    /// static ALLOCATOR: Allocator<std::alloc::System> = Allocator::system();
    ///
    /// # fn main() {
    /// let session = Session::new();
    /// {
    ///     let operation = session.operation("test_work");
    ///     let _span = operation.measure_process();
    ///     let _data = vec![1, 2, 3, 4, 5]; // This allocates memory
    /// }
    ///
    /// let report = session.to_report();
    /// for (name, op) in report.operations() {
    ///     println!(
    ///         "Operation '{}' had {} iterations",
    ///         name,
    ///         op.total_iterations()
    ///     );
    ///     println!("Mean bytes per iteration: {}", op.mean());
    ///     println!("Total bytes: {}", op.total_bytes_allocated());
    /// }
    /// # }
    /// ```
    pub fn operations(&self) -> impl Iterator<Item = (&str, &ReportOperation)> {
        self.operations.iter().map(|(name, op)| (name.as_str(), op))
    }
}

impl ReportOperation {
    /// Returns the total bytes allocated across all iterations for this operation.
    #[must_use]
    pub fn total_bytes_allocated(&self) -> u64 {
        self.total_bytes_allocated
    }

    /// Returns the total number of allocations across all iterations for this operation.
    #[must_use]
    pub fn total_allocations_count(&self) -> u64 {
        self.total_allocations_count
    }

    /// Returns the total number of iterations recorded for this operation.
    #[must_use]
    pub fn total_iterations(&self) -> u64 {
        self.total_iterations
    }

    /// Calculates the mean bytes allocated per iteration.
    #[expect(
        clippy::integer_division,
        reason = "we accept loss of precision for mean calculation"
    )]
    #[expect(
        clippy::arithmetic_side_effects,
        reason = "division by zero is guarded by if-else"
    )]
    #[must_use]
    pub fn mean_bytes(&self) -> u64 {
        if self.total_iterations == 0 {
            0
        } else {
            self.total_bytes_allocated / self.total_iterations
        }
    }

    /// Calculates the mean number of allocations per iteration.
    #[expect(
        clippy::integer_division,
        reason = "we accept loss of precision for mean calculation"
    )]
    #[expect(
        clippy::arithmetic_side_effects,
        reason = "division by zero is guarded by if-else"
    )]
    #[must_use]
    pub fn mean_allocations(&self) -> u64 {
        if self.total_iterations == 0 {
            0
        } else {
            self.total_allocations_count / self.total_iterations
        }
    }

    /// Calculates the mean bytes allocated per iteration.
    ///
    /// This is an alias for [`mean_bytes`](Self::mean_bytes) to maintain backward compatibility.
    #[must_use]
    pub fn mean(&self) -> u64 {
        self.mean_bytes()
    }
}

impl fmt::Display for ReportOperation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} bytes (mean)", self.mean_bytes())
    }
}

// No API contract to test - output format is not guaranteed.
#[cfg_attr(coverage_nightly, coverage(off))]
impl fmt::Display for Report {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.operations.values().all(|op| op.total_iterations == 0) {
            writeln!(f, "No allocation statistics captured.")?;
        } else {
            writeln!(f, "Allocation statistics:")?;
            writeln!(f)?;

            // Sort operations by name for consistent output
            let mut sorted_ops: Vec<_> = self.operations.iter().collect();
            sorted_ops.sort_by_key(|(name, _)| *name);

            // Calculate column widths
            let max_name_width = sorted_ops
                .iter()
                .map(|(name, _)| name.len())
                .max()
                .unwrap_or(0)
                .max("Operation".len());

            let max_bytes_width = sorted_ops
                .iter()
                .map(|(_, operation)| operation.mean_bytes().to_string().len())
                .max()
                .unwrap_or(0)
                .max("Mean bytes".len());

            let max_count_width = sorted_ops
                .iter()
                .map(|(_, operation)| operation.mean_allocations().to_string().len())
                .max()
                .unwrap_or(0)
                .max("Mean count".len());

            // Print table header
            writeln!(
                f,
                "| {:<name_width$} | {:>bytes_width$} | {:>count_width$} |",
                "Operation",
                "Mean bytes",
                "Mean count",
                name_width = max_name_width,
                bytes_width = max_bytes_width,
                count_width = max_count_width
            )?;

            // Print separator
            let separator_name_width = max_name_width
                .checked_add(2)
                .expect("operation name width fits in memory, adding 2 cannot overflow");
            let separator_bytes_width = max_bytes_width
                .checked_add(2)
                .expect("bytes width fits in memory, adding 2 cannot overflow");
            let separator_count_width = max_count_width
                .checked_add(2)
                .expect("count width fits in memory, adding 2 cannot overflow");
            writeln!(
                f,
                "|{:-<name_width$}|{:-<bytes_width$}|{:-<count_width$}|",
                "",
                "",
                "",
                name_width = separator_name_width,
                bytes_width = separator_bytes_width,
                count_width = separator_count_width
            )?;

            // Print table rows
            for (name, operation) in sorted_ops {
                writeln!(
                    f,
                    "| {:<name_width$} | {:>bytes_width$} | {:>count_width$} |",
                    name,
                    operation.mean_bytes(),
                    operation.mean_allocations(),
                    name_width = max_name_width,
                    bytes_width = max_bytes_width,
                    count_width = max_count_width
                )?;
            }
        }
        Ok(())
    }
}

#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use std::panic::RefUnwindSafe;
    use std::panic::UnwindSafe;

    use super::*;
    use crate::Session;
    use crate::allocator::register_fake_allocation;

    #[test]
    fn new_report_is_empty() {
        let report = Report::new();
        assert!(report.is_empty());
    }

    #[test]
    fn report_from_empty_session_is_empty() {
        let session = Session::new();
        let report = session.to_report();
        assert!(report.is_empty());
    }

    #[test]
    fn report_from_session_with_operations_is_not_empty() {
        let session = Session::new();
        {
            let operation = session.operation("test");
            let _span = operation.measure_thread();
            register_fake_allocation(100, 1);
        } // Span drops here, releasing the mutable borrow

        let report = session.to_report();
        assert!(!report.is_empty());
    }

    #[test]
    fn merge_empty_reports() {
        let report1 = Report::new();
        let report2 = Report::new();
        let merged = Report::merge(&report1, &report2);
        assert!(merged.is_empty());
    }

    #[test]
    fn merge_empty_with_non_empty() {
        let session = Session::new();
        {
            let operation = session.operation("test");
            let _span = operation.measure_thread();
            register_fake_allocation(100, 1);
        } // Span drops here

        let report1 = Report::new();
        let report2 = session.to_report();

        let merged1 = Report::merge(&report1, &report2);
        let merged2 = Report::merge(&report2, &report1);

        assert!(!merged1.is_empty());
        assert!(!merged2.is_empty());
    }

    #[test]
    fn merge_different_operations() {
        let session1 = Session::new();
        let session2 = Session::new();

        {
            let op1 = session1.operation("test1");
            let _span1 = op1.measure_thread();
            register_fake_allocation(100, 1);
        } // Span drops here

        {
            let op2 = session2.operation("test2");
            let _span2 = op2.measure_thread();
            register_fake_allocation(200, 2);
        } // Span drops here

        let report1 = session1.to_report();
        let report2 = session2.to_report();
        let merged = Report::merge(&report1, &report2);

        assert_eq!(merged.operations.len(), 2);
        assert!(merged.operations.contains_key("test1"));
        assert!(merged.operations.contains_key("test2"));
    }

    #[test]
    fn merge_same_operations() {
        let session1 = Session::new();
        let session2 = Session::new();

        {
            let op1 = session1.operation("test");
            let _span1 = op1.measure_thread();
            register_fake_allocation(100, 1);
        } // Span drops here

        {
            let op2 = session2.operation("test");
            let _span2 = op2.measure_thread();
            register_fake_allocation(200, 2);
        } // Span drops here

        let report1 = session1.to_report();
        let report2 = session2.to_report();
        let merged = Report::merge(&report1, &report2);

        assert_eq!(merged.operations.len(), 1);
        let merged_op = merged.operations.get("test").unwrap();
        assert_eq!(merged_op.total_iterations, 2); // 1 + 1
        assert_eq!(merged_op.total_bytes_allocated, 300); // 100 + 200
        assert_eq!(merged_op.total_allocations_count, 3); // 1 + 2
    }

    #[test]
    fn report_clone() {
        let session = Session::new();
        {
            let operation = session.operation("test");
            let _span = operation.measure_thread();
            register_fake_allocation(100, 1);
        } // Span drops here

        let report1 = session.to_report();
        let report2 = report1.clone();

        assert_eq!(report1.operations.len(), report2.operations.len());
    }

    #[test]
    fn report_operation_total_allocations_count_zero() {
        let operation = ReportOperation {
            total_bytes_allocated: 0,
            total_allocations_count: 0,
            total_iterations: 1,
        };

        assert_eq!(operation.total_allocations_count(), 0);
    }

    #[test]
    fn report_operation_total_allocations_count_multiple() {
        let operation = ReportOperation {
            total_bytes_allocated: 500,
            total_allocations_count: 25,
            total_iterations: 5,
        };

        assert_eq!(operation.total_allocations_count(), 25);
    }

    #[test]
    fn report_operation_total_allocations_count_consistency_with_session() {
        let session = Session::new();
        {
            let operation = session.operation("test_consistency");
            let _span = operation.measure_thread();
            // Simulate 3 allocations
            register_fake_allocation(300, 3);
        } // Span drops here

        let report = session.to_report();
        let operations: Vec<_> = report.operations().collect();
        assert_eq!(operations.len(), 1);

        let (_name, report_op) = operations.first().unwrap();
        assert_eq!(report_op.total_allocations_count(), 3);
        assert_eq!(report_op.total_bytes_allocated(), 300);
        assert_eq!(report_op.total_iterations(), 1);
    }

    // Static assertions for thread safety.
    static_assertions::assert_impl_all!(Report: Send, Sync);
    static_assertions::assert_impl_all!(ReportOperation: Send, Sync);

    // Static assertions for unwind safety.
    static_assertions::assert_impl_all!(Report: UnwindSafe, RefUnwindSafe);
    static_assertions::assert_impl_all!(
        ReportOperation: UnwindSafe, RefUnwindSafe
    );

    #[test]
    fn report_operation_display_shows_mean_bytes() {
        let operation = ReportOperation {
            total_bytes_allocated: 1000,
            total_allocations_count: 10,
            total_iterations: 4,
        };

        let display_output = operation.to_string();
        assert!(display_output.contains("bytes (mean)"));
        assert!(display_output.contains("250")); // 1000 / 4 = 250 mean bytes
    }

    #[test]
    fn empty_report_display_shows_no_statistics_message() {
        let report = Report::new();
        let display_output = report.to_string();
        assert!(display_output.contains("No allocation statistics captured."));
    }
}