qudag_protocol/
allocator.rs1use std::alloc::System;
2use std::sync::atomic::{AtomicUsize, Ordering};
3
4pub struct TrackedAllocator {
6 allocated: AtomicUsize,
7 deallocated: AtomicUsize,
8 #[allow(dead_code)]
9 inner: System,
10}
11
12impl Default for TrackedAllocator {
13 fn default() -> Self {
14 Self::new()
15 }
16}
17
18impl TrackedAllocator {
19 pub const fn new() -> Self {
20 Self {
21 allocated: AtomicUsize::new(0),
22 deallocated: AtomicUsize::new(0),
23 inner: System,
24 }
25 }
26
27 pub fn allocated_bytes(&self) -> usize {
28 self.allocated.load(Ordering::SeqCst)
29 }
30
31 pub fn deallocated_bytes(&self) -> usize {
32 self.deallocated.load(Ordering::SeqCst)
33 }
34
35 pub fn current_usage(&self) -> usize {
36 self.allocated_bytes()
37 .saturating_sub(self.deallocated_bytes())
38 }
39}
40
41pub fn get_memory_usage() -> usize {
65 0
67}
68
69pub fn get_total_allocated() -> usize {
71 0
73}
74
75pub fn get_total_deallocated() -> usize {
77 0
79}
80
81#[cfg(test)]
82mod tests {
83 use super::*;
84 use std::mem;
85
86 #[test]
87 fn test_memory_tracking() {
88 let start_allocated = get_total_allocated();
90 let start_deallocated = get_total_deallocated();
91
92 let data = vec![0u8; 1024];
94 let allocated_size = mem::size_of_val(data.as_slice());
95
96 assert!(get_total_allocated() > start_allocated);
98 assert!(get_total_allocated() - start_allocated >= allocated_size);
99
100 drop(data);
102
103 assert!(get_total_deallocated() > start_deallocated);
105 assert!(get_total_deallocated() - start_deallocated >= allocated_size);
106 }
107}