memscope_rs/
types.rs

1//! Core types and error handling for the memscope-rs library.
2
3use serde::{Deserialize, Serialize};
4
5/// Error type for memory tracking operations
6#[derive(Debug, thiserror::Error)]
7pub enum TrackingError {
8    /// Failed to acquire a lock
9    #[error("Failed to acquire lock: {0}")]
10    LockError(String),
11
12    /// Invalid pointer for association
13    #[error("Invalid pointer association: {ptr:?}")]
14    InvalidPointer {
15        /// The invalid pointer address
16        ptr: usize,
17    },
18
19    /// Allocation tracking is disabled
20    #[error("Allocation tracking disabled")]
21    TrackingDisabled,
22
23    /// Memory corruption detected
24    #[error("Memory corruption detected")]
25    MemoryCorruption,
26
27    /// Serialization error
28    #[error("Serialization error: {0}")]
29    SerializationError(String),
30
31    /// IO error during export
32    #[error("IO error: {0}")]
33    IoError(#[from] std::io::Error),
34}
35
36/// Result type for tracking operations
37pub type TrackingResult<T> = Result<T, TrackingError>;
38
39/// Information about a memory allocation
40#[derive(Debug, Clone, Serialize, Deserialize)]
41pub struct AllocationInfo {
42    /// Memory address of the allocation
43    pub ptr: usize,
44    /// Size of the allocation in bytes
45    pub size: usize,
46    /// Timestamp when the allocation occurred (milliseconds since UNIX_EPOCH)
47    pub timestamp_alloc: u128,
48    /// Timestamp when the deallocation occurred (if applicable)
49    pub timestamp_dealloc: Option<u128>,
50    /// Optional name of the variable associated with this allocation
51    pub var_name: Option<String>,
52    /// Optional type name of the variable associated with this allocation
53    pub type_name: Option<String>,
54    /// Thread ID where the allocation occurred
55    pub thread_id: String,
56    /// Backtrace information (if available)
57    #[cfg(feature = "backtrace")]
58    pub backtrace: Option<Vec<String>>,
59}
60
61impl AllocationInfo {
62    /// Create a new allocation info
63    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    /// Mark this allocation as deallocated
85    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    /// Check if this allocation is still active
95    pub fn is_active(&self) -> bool {
96        self.timestamp_dealloc.is_none()
97    }
98
99    /// Get the lifetime of this allocation in milliseconds
100    pub fn lifetime_ms(&self) -> Option<u128> {
101        self.timestamp_dealloc
102            .map(|dealloc| dealloc - self.timestamp_alloc)
103    }
104}
105
106/// Memory usage statistics
107#[derive(Debug, Clone, Serialize, Deserialize, Default)]
108pub struct MemoryStats {
109    /// Total number of allocations tracked
110    pub total_allocations: usize,
111    /// Total number of deallocations tracked
112    pub total_deallocations: usize,
113    /// Total bytes allocated
114    pub total_allocated: usize,
115    /// Total bytes deallocated
116    pub total_deallocated: usize,
117    /// Current number of active allocations
118    pub active_allocations: usize,
119    /// Current bytes in active allocations
120    pub active_memory: usize,
121    /// Peak number of active allocations
122    pub peak_allocations: usize,
123    /// Peak memory usage in bytes
124    pub peak_memory: usize,
125}
126
127/// Memory usage by type
128#[derive(Debug, Clone, Serialize, Deserialize)]
129pub struct TypeMemoryUsage {
130    /// The name of the data type
131    pub type_name: String,
132    /// Total size in bytes for this type
133    pub total_size: usize,
134    /// Number of allocations for this type
135    pub allocation_count: usize,
136}
137
138/// Allocation hotspot information
139#[derive(Debug, Clone, Serialize, Deserialize)]
140pub struct HotspotInfo {
141    /// Location identifier (could be function name, file:line, etc.)
142    pub location: String,
143    /// Number of allocations from this location
144    pub count: usize,
145    /// Total size of allocations from this location
146    pub total_size: usize,
147    /// Average allocation size
148    pub average_size: f64,
149}