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
//!
//! An instrumenting allocator wrapper to compute (scoped) peak memory consumption.
//!
//! ## Example
//!
//! ```
//! use peakmem_alloc::*;
//! use std::alloc::System;
//!
//! #[global_allocator]
//! static GLOBAL: &PeakAlloc<System> = &INSTRUMENTED_SYSTEM;
//!
//! fn main() {
//!    GLOBAL.reset_peak_memory();
//!    let _x: Vec<u8> = Vec::with_capacity(1_024);
//!    println!(
//!        "Peak Memory used by function : {:#?}",
//!        GLOBAL.get_peak_memory()
//!    );
//! }
//! ```

#![deny(
    missing_debug_implementations,
    missing_copy_implementations,
    trivial_casts,
    trivial_numeric_casts,
    unused_import_braces,
    unused_imports,
    unused_qualifications,
    missing_docs
)]
#![cfg_attr(doc_cfg, feature(allocator_api))]
#![cfg_attr(doc_cfg, feature(doc_cfg))]

use std::{
    alloc::{GlobalAlloc, Layout, System},
    sync::atomic::{AtomicIsize, AtomicUsize, Ordering},
};

/// The PeakAllocTrait trait provides a common interface for all allocators.
///
/// This is mainly to allow for generic functions that can work with any allocator with type erasure.
///
pub trait PeakAllocTrait {
    /// Resets the peak memory to 0
    fn reset_peak_memory(&self);

    /// Get the peak memory consumption. This is the maximum that has been allocated since the last reset.
    ///
    /// Note that allocations of other threads may interfere with a measurement of a scope.
    fn get_peak_memory(&self) -> usize;
}

/// An allocator middleware which keeps track of peak memory consumption.
#[derive(Default, Debug)]
pub struct PeakAlloc<T: GlobalAlloc> {
    peak_bytes_allocated_tracker: AtomicIsize,
    peak_bytes_allocated: AtomicUsize,
    inner: T,
}

/// An instrumented instance of the system allocator.
pub static INSTRUMENTED_SYSTEM: PeakAlloc<System> = PeakAlloc {
    peak_bytes_allocated_tracker: AtomicIsize::new(0),
    peak_bytes_allocated: AtomicUsize::new(0),
    inner: System,
};

impl PeakAlloc<System> {
    /// Provides access to an instrumented instance of the system allocator.
    pub const fn system() -> Self {
        PeakAlloc {
            peak_bytes_allocated_tracker: AtomicIsize::new(0),
            peak_bytes_allocated: AtomicUsize::new(0),
            inner: System,
        }
    }
}

impl<T: GlobalAlloc> PeakAllocTrait for PeakAlloc<T> {
    /// Resets the peak memory to 0
    #[inline]
    fn reset_peak_memory(&self) {
        self.peak_bytes_allocated.store(0, Ordering::SeqCst);
        self.peak_bytes_allocated_tracker.store(0, Ordering::SeqCst);
    }

    /// Get the peak memory consumption
    #[inline]
    fn get_peak_memory(&self) -> usize {
        self.peak_bytes_allocated.load(Ordering::SeqCst)
    }
}
impl<T: GlobalAlloc> PeakAlloc<T> {
    /// Provides access to an instrumented instance of the given global
    /// allocator.
    pub const fn new(inner: T) -> Self {
        PeakAlloc {
            peak_bytes_allocated_tracker: AtomicIsize::new(0),
            peak_bytes_allocated: AtomicUsize::new(0),
            inner,
        }
    }

    #[inline]
    fn track_alloc(&self, bytes: usize) {
        let prev = self
            .peak_bytes_allocated_tracker
            .fetch_add(bytes as isize, Ordering::SeqCst);
        let current_peak = (prev + bytes as isize).max(0) as usize;
        self.peak_bytes_allocated
            .fetch_max(current_peak, Ordering::SeqCst);
    }

    #[inline]
    fn track_dealloc(&self, bytes: usize) {
        self.peak_bytes_allocated_tracker
            .fetch_sub(bytes as isize, Ordering::SeqCst);
    }
}

unsafe impl<'a, T: GlobalAlloc + 'a> GlobalAlloc for &'a PeakAlloc<T> {
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        (*self).alloc(layout)
    }

    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        (*self).dealloc(ptr, layout)
    }

    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
        (*self).alloc_zeroed(layout)
    }

    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
        (*self).realloc(ptr, layout, new_size)
    }
}

unsafe impl<T: GlobalAlloc> GlobalAlloc for PeakAlloc<T> {
    #[inline]
    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
        self.track_alloc(layout.size());
        self.inner.alloc(layout)
    }

    #[inline]
    unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
        self.track_dealloc(layout.size());
        self.inner.dealloc(ptr, layout)
    }

    #[inline]
    unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
        self.track_alloc(layout.size());
        self.inner.alloc_zeroed(layout)
    }

    #[inline]
    unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
        match new_size.cmp(&layout.size()) {
            std::cmp::Ordering::Greater => {
                let difference = new_size - layout.size();
                self.track_alloc(difference);
            }
            std::cmp::Ordering::Less => {
                let difference = layout.size() - new_size;
                self.track_dealloc(difference);
            }
            _ => {}
        }

        self.inner.realloc(ptr, layout, new_size)
    }
}