1use serde::{Deserialize, Serialize};
4
5#[derive(Debug, thiserror::Error)]
7pub enum TrackingError {
8 #[error("Failed to acquire lock: {0}")]
10 LockError(String),
11
12 #[error("Invalid pointer association: {ptr:?}")]
14 InvalidPointer {
15 ptr: usize,
17 },
18
19 #[error("Allocation tracking disabled")]
21 TrackingDisabled,
22
23 #[error("Memory corruption detected")]
25 MemoryCorruption,
26
27 #[error("Serialization error: {0}")]
29 SerializationError(String),
30
31 #[error("IO error: {0}")]
33 IoError(#[from] std::io::Error),
34}
35
36pub type TrackingResult<T> = Result<T, TrackingError>;
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct AllocationInfo {
42 pub ptr: usize,
44 pub size: usize,
46 pub timestamp_alloc: u128,
48 pub timestamp_dealloc: Option<u128>,
50 pub var_name: Option<String>,
52 pub type_name: Option<String>,
54 pub thread_id: String,
56 #[cfg(feature = "backtrace")]
58 pub backtrace: Option<Vec<String>>,
59}
60
61impl AllocationInfo {
62 pub fn new(ptr: usize, size: usize) -> Self {
64 let timestamp = std::time::SystemTime::now()
65 .duration_since(std::time::UNIX_EPOCH)
66 .unwrap_or_default()
67 .as_millis();
68
69 let thread_id = format!("{:?}", std::thread::current().id());
70
71 Self {
72 ptr,
73 size,
74 timestamp_alloc: timestamp,
75 timestamp_dealloc: None,
76 var_name: None,
77 type_name: None,
78 thread_id,
79 #[cfg(feature = "backtrace")]
80 backtrace: None,
81 }
82 }
83
84 pub fn mark_deallocated(&mut self) {
86 let timestamp = std::time::SystemTime::now()
87 .duration_since(std::time::UNIX_EPOCH)
88 .unwrap_or_default()
89 .as_millis();
90
91 self.timestamp_dealloc = Some(timestamp);
92 }
93
94 pub fn is_active(&self) -> bool {
96 self.timestamp_dealloc.is_none()
97 }
98
99 pub fn lifetime_ms(&self) -> Option<u128> {
101 self.timestamp_dealloc
102 .map(|dealloc| dealloc - self.timestamp_alloc)
103 }
104}
105
106#[derive(Debug, Clone, Serialize, Deserialize, Default)]
108pub struct MemoryStats {
109 pub total_allocations: usize,
111 pub total_deallocations: usize,
113 pub total_allocated: usize,
115 pub total_deallocated: usize,
117 pub active_allocations: usize,
119 pub active_memory: usize,
121 pub peak_allocations: usize,
123 pub peak_memory: usize,
125}
126
127#[derive(Debug, Clone, Serialize, Deserialize)]
129pub struct TypeMemoryUsage {
130 pub type_name: String,
132 pub total_size: usize,
134 pub allocation_count: usize,
136}
137
138#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct HotspotInfo {
141 pub location: String,
143 pub count: usize,
145 pub total_size: usize,
147 pub average_size: f64,
149}