pub struct MemoryTracker { /* private fields */ }
Expand description
Core memory tracking functionality.
The MemoryTracker maintains records of all memory allocations and deallocations, provides statistics, and supports exporting data in various formats.
Implementations§
Source§impl MemoryTracker
impl MemoryTracker
Sourcepub fn fast_track_allocation(
&self,
ptr: usize,
size: usize,
var_name: String,
) -> TrackingResult<()>
pub fn fast_track_allocation( &self, ptr: usize, size: usize, var_name: String, ) -> TrackingResult<()>
Fast track allocation for testing (minimal overhead)
Sourcepub fn track_allocation(&self, ptr: usize, size: usize) -> TrackingResult<()>
pub fn track_allocation(&self, ptr: usize, size: usize) -> TrackingResult<()>
Track a new memory allocation using bounded stats.
Sourcepub fn track_allocation_with_context(
&self,
ptr: usize,
size: usize,
inferred_var_name: String,
inferred_type_name: String,
) -> TrackingResult<()>
pub fn track_allocation_with_context( &self, ptr: usize, size: usize, inferred_var_name: String, inferred_type_name: String, ) -> TrackingResult<()>
Track a memory allocation with enhanced context information
Sourcepub fn track_deallocation(&self, ptr: usize) -> TrackingResult<()>
pub fn track_deallocation(&self, ptr: usize) -> TrackingResult<()>
Track a memory deallocation using bounded stats.
Sourcepub fn create_synthetic_allocation(
&self,
ptr: usize,
size: usize,
var_name: String,
type_name: String,
_creation_time: u64,
) -> TrackingResult<()>
pub fn create_synthetic_allocation( &self, ptr: usize, size: usize, var_name: String, type_name: String, _creation_time: u64, ) -> TrackingResult<()>
Create synthetic allocation with proper var_name and type_name
Sourcepub fn associate_var(
&self,
ptr: usize,
var_name: String,
type_name: String,
) -> TrackingResult<()>
pub fn associate_var( &self, ptr: usize, var_name: String, type_name: String, ) -> TrackingResult<()>
Associate a variable name and type with an allocation.
Sourcepub fn track_smart_pointer_clone(
&self,
clone_ptr: usize,
source_ptr: usize,
_data_ptr: usize,
_new_ref_count: usize,
_weak_count: usize,
) -> TrackingResult<()>
pub fn track_smart_pointer_clone( &self, clone_ptr: usize, source_ptr: usize, _data_ptr: usize, _new_ref_count: usize, _weak_count: usize, ) -> TrackingResult<()>
Track smart pointer clone relationship
Sourcepub fn update_smart_pointer_ref_count(
&self,
ptr: usize,
strong_count: usize,
weak_count: usize,
) -> TrackingResult<()>
pub fn update_smart_pointer_ref_count( &self, ptr: usize, strong_count: usize, weak_count: usize, ) -> TrackingResult<()>
Update reference count for a smart pointer
Sourcepub fn create_smart_pointer_allocation(
&self,
ptr: usize,
size: usize,
var_name: String,
type_name: String,
creation_time: u64,
ref_count: usize,
data_ptr: usize,
) -> TrackingResult<()>
pub fn create_smart_pointer_allocation( &self, ptr: usize, size: usize, var_name: String, type_name: String, creation_time: u64, ref_count: usize, data_ptr: usize, ) -> TrackingResult<()>
Create a specialized synthetic allocation for smart pointers
Sourcepub fn track_deallocation_with_lifetime(
&self,
ptr: usize,
lifetime_ms: u64,
) -> TrackingResult<()>
pub fn track_deallocation_with_lifetime( &self, ptr: usize, lifetime_ms: u64, ) -> TrackingResult<()>
Track a memory deallocation with precise lifetime information.
Sourcepub fn track_smart_pointer_deallocation(
&self,
ptr: usize,
lifetime_ms: u64,
_final_ref_count: usize,
) -> TrackingResult<()>
pub fn track_smart_pointer_deallocation( &self, ptr: usize, lifetime_ms: u64, _final_ref_count: usize, ) -> TrackingResult<()>
Track the deallocation of a smart pointer with enhanced metadata.
Sourcepub fn record_ownership_event(&self, ptr: usize, event_type: OwnershipEventType)
pub fn record_ownership_event(&self, ptr: usize, event_type: OwnershipEventType)
Record an ownership event for detailed lifecycle tracking
Sourcepub fn get_ownership_summary(&self, ptr: usize) -> Option<OwnershipSummary>
pub fn get_ownership_summary(&self, ptr: usize) -> Option<OwnershipSummary>
Get ownership summary for an allocation
Sourcepub fn export_ownership_history(&self) -> Result<String, String>
pub fn export_ownership_history(&self) -> Result<String, String>
Export ownership history to JSON
Source§impl MemoryTracker
impl MemoryTracker
Sourcepub fn export_interactive_dashboard<P: AsRef<Path>>(
&self,
path: P,
) -> TrackingResult<()>
pub fn export_interactive_dashboard<P: AsRef<Path>>( &self, path: P, ) -> TrackingResult<()>
Export interactive HTML dashboard with embedded SVG charts.
This method creates a comprehensive HTML dashboard that includes:
- Memory usage statistics and charts
- Allocation timeline visualization
- Type-based memory analysis
- Interactive filtering and sorting
- Embedded CSS and JavaScript for offline viewing
§Arguments
path
- The output path for the HTML file
§Examples
// Export to default location
tracker.export_interactive_dashboard("memory_report.html")?;
// Export to specific directory
tracker.export_interactive_dashboard("reports/detailed_analysis.html")?;
§Features
- Self-contained: All CSS, JavaScript, and data embedded in single HTML file
- Interactive: Click, filter, and drill down into memory data
- Responsive: Works on desktop and mobile browsers
- Offline: No external dependencies, works without internet connection
- Comprehensive: Includes all major memory analysis views
§Performance
HTML export is generally fast (1-3 seconds) as it focuses on visualization rather than comprehensive data processing. The file size depends on the amount of tracking data but is typically 1-10MB.
Sourcepub fn export_interactive_dashboard_with_ffi<P: AsRef<Path>>(
&self,
path: P,
unsafe_ffi_tracker: Option<&UnsafeFFITracker>,
) -> TrackingResult<()>
pub fn export_interactive_dashboard_with_ffi<P: AsRef<Path>>( &self, path: P, unsafe_ffi_tracker: Option<&UnsafeFFITracker>, ) -> TrackingResult<()>
Export HTML dashboard with custom unsafe FFI tracker data.
This method allows including custom unsafe FFI analysis data in the HTML export, providing enhanced security and safety analysis in the dashboard.
§Arguments
path
- The output path for the HTML fileunsafe_ffi_tracker
- Optional unsafe FFI tracker for enhanced analysis
§Examples
use memscope_rs::get_global_unsafe_ffi_tracker;
let unsafe_tracker = get_global_unsafe_ffi_tracker();
tracker.export_interactive_dashboard_with_ffi(
"enhanced_report.html",
Some(&unsafe_tracker)
)?;
Sourcepub fn export_html_summary<P: AsRef<Path>>(&self, path: P) -> TrackingResult<()>
pub fn export_html_summary<P: AsRef<Path>>(&self, path: P) -> TrackingResult<()>
Generate HTML summary report with key metrics.
This method creates a lightweight HTML summary that focuses on key metrics and insights rather than comprehensive data visualization.
§Arguments
path
- The output path for the HTML summary
§Examples
// Generate quick summary report
tracker.export_html_summary("summary.html")?;
§Features
- Lightweight: Smaller file size, faster generation
- Key metrics: Focus on most important memory statistics
- Executive summary: High-level insights and recommendations
- Quick loading: Optimized for fast viewing and sharing
Source§impl MemoryTracker
impl MemoryTracker
Sourcepub fn export_to_json<P: AsRef<Path>>(&self, path: P) -> TrackingResult<()>
pub fn export_to_json<P: AsRef<Path>>(&self, path: P) -> TrackingResult<()>
Export memory tracking data to 4 separate JSON files.
This method exports data to 4 specialized files:
- {name}_memory_analysis.json: Memory allocation patterns and statistics
- {name}_lifetime.json: Variable lifetime and scope analysis
- {name}_unsafe_ffi.json: Unsafe operations and FFI tracking
- {name}_variable_relationships.json: Variable dependency graph and relationships
§Export Modes
§Default Mode (Fast - Recommended)
let tracker = get_global_tracker();
tracker.export_to_json("output").unwrap();
// OR explicitly
tracker.export_to_json_with_options("output", ExportJsonOptions::default()).unwrap();
- Performance: ~2-5 seconds for typical datasets
- Data: Only user-tracked variables get full enrichment
- Use case: Normal development, HTML rendering, production monitoring
§Complete Mode (Slow - Debug Only)
let tracker = get_global_tracker();
let mut options = ExportJsonOptions::default();
options.security_analysis = true;
tracker.export_to_json_with_options("output", options).unwrap();
- Performance: ~10-40 seconds (5-10x slower!)
- Data: ALL allocations including system internals get full enrichment
- Use case: Deep debugging, memory leak investigation, system analysis
- ⚠️ Warning: Very slow, generates large files, may impact application performance
Sourcepub fn export_to_json_with_options<P: AsRef<Path>>(
&self,
path: P,
options: ExportJsonOptions,
) -> TrackingResult<()>
pub fn export_to_json_with_options<P: AsRef<Path>>( &self, path: P, options: ExportJsonOptions, ) -> TrackingResult<()>
Export memory tracking data with custom options.
§Examples
§Fast mode (default - recommended for most users)
let tracker = get_global_tracker();
tracker.export_to_json_with_options("output", ExportJsonOptions::default()).unwrap();
§Complete mode (slow - for debugging)
let tracker = get_global_tracker();
let mut options = ExportJsonOptions::default();
options.security_analysis = true;
options.schema_validation = true;
tracker.export_to_json_with_options("debug_output", options).unwrap();
Sourcepub fn get_memory_by_type(&self) -> TrackingResult<Vec<TypeMemoryUsage>>
pub fn get_memory_by_type(&self) -> TrackingResult<Vec<TypeMemoryUsage>>
Get memory usage by type for export
Source§impl MemoryTracker
impl MemoryTracker
Sourcepub fn analyze_memory_layout(
&self,
type_name: &str,
size: usize,
) -> Option<MemoryLayoutInfo>
pub fn analyze_memory_layout( &self, type_name: &str, size: usize, ) -> Option<MemoryLayoutInfo>
Analyze memory layout information with enhanced container analysis
Sourcepub fn analyze_memory_fragmentation(&self) -> EnhancedFragmentationAnalysis
pub fn analyze_memory_fragmentation(&self) -> EnhancedFragmentationAnalysis
Analyze memory fragmentation
Sourcepub fn analyze_generic_type(
&self,
type_name: &str,
size: usize,
) -> Option<GenericTypeInfo>
pub fn analyze_generic_type( &self, type_name: &str, size: usize, ) -> Option<GenericTypeInfo>
Analyze generic type information
Sourcepub fn analyze_dynamic_type(
&self,
type_name: &str,
size: usize,
) -> Option<DynamicTypeInfo>
pub fn analyze_dynamic_type( &self, type_name: &str, size: usize, ) -> Option<DynamicTypeInfo>
Analyze dynamic type information (trait objects)
Sourcepub fn collect_runtime_state(&self) -> RuntimeStateInfo
pub fn collect_runtime_state(&self) -> RuntimeStateInfo
Collect runtime state information
Sourcepub fn analyze_type_relationships(
&self,
type_name: &str,
) -> Option<TypeRelationshipInfo>
pub fn analyze_type_relationships( &self, type_name: &str, ) -> Option<TypeRelationshipInfo>
Analyze type relationships
Sourcepub fn track_type_usage(&self, type_name: &str) -> Option<TypeUsageInfo>
pub fn track_type_usage(&self, type_name: &str) -> Option<TypeUsageInfo>
Track type usage with enhanced statistics collection
Sourcepub fn analyze_stack_allocation(
&self,
type_name: &str,
ptr: usize,
) -> Option<StackAllocationInfo>
pub fn analyze_stack_allocation( &self, type_name: &str, ptr: usize, ) -> Option<StackAllocationInfo>
Analyze stack allocation information
Source§impl MemoryTracker
impl MemoryTracker
Sourcepub fn get_stats(&self) -> TrackingResult<MemoryStats>
pub fn get_stats(&self) -> TrackingResult<MemoryStats>
Get current memory statistics with advanced analysis.
Sourcepub fn get_active_allocations(&self) -> TrackingResult<Vec<AllocationInfo>>
pub fn get_active_allocations(&self) -> TrackingResult<Vec<AllocationInfo>>
Get all currently active allocations.
Sourcepub fn get_allocation_history(&self) -> TrackingResult<Vec<AllocationInfo>>
pub fn get_allocation_history(&self) -> TrackingResult<Vec<AllocationInfo>>
Get the complete allocation history.
Sourcepub fn set_fast_mode(&self, enabled: bool)
pub fn set_fast_mode(&self, enabled: bool)
Enable or disable fast mode.
Sourcepub fn is_fast_mode(&self) -> bool
pub fn is_fast_mode(&self) -> bool
Check if fast mode is enabled.
Sourcepub fn enable_fast_mode(&self)
pub fn enable_fast_mode(&self)
Enable fast mode for testing
Sourcepub fn export_memory_analysis<P: AsRef<Path>>(
&self,
path: P,
) -> TrackingResult<()>
pub fn export_memory_analysis<P: AsRef<Path>>( &self, path: P, ) -> TrackingResult<()>
Export memory analysis visualization to SVG file. All output files are automatically placed in the MemoryAnalysis/ directory.
§Arguments
path
- Output filename for the memory analysis SVG file (recommended: “program_name_memory_analysis.svg”)
Sourcepub fn ensure_memory_analysis_path<P: AsRef<Path>>(&self, path: P) -> PathBuf
pub fn ensure_memory_analysis_path<P: AsRef<Path>>(&self, path: P) -> PathBuf
Ensure the memory analysis path exists and return the full path
Sourcepub fn export_to_binary<P: AsRef<Path>>(&self, path: P) -> TrackingResult<()>
pub fn export_to_binary<P: AsRef<Path>>(&self, path: P) -> TrackingResult<()>
Export memory tracking data to binary format (.memscope file). All output files are automatically placed in the MemoryAnalysis/ directory. This method exports user-defined variables only (default behavior for compatibility).
§Arguments
path
- Base filename for the binary export (extension .memscope will be added automatically)
§Example
let tracker = get_global_tracker();
tracker.export_to_binary("my_program")?;
// Creates: MemoryAnalysis/my_program.memscope
Sourcepub fn export_to_binary_with_mode<P: AsRef<Path>>(
&self,
path: P,
mode: BinaryExportMode,
) -> TrackingResult<()>
pub fn export_to_binary_with_mode<P: AsRef<Path>>( &self, path: P, mode: BinaryExportMode, ) -> TrackingResult<()>
Export memory tracking data to binary format with specified mode. All output files are automatically placed in the MemoryAnalysis/ directory. This method provides flexible export options for different use cases.
§Arguments
path
- Base filename for the binary export (extension .memscope will be added automatically)mode
- Export mode (UserOnly for small files, Full for complete data)
§Example
let tracker = get_global_tracker();
// Export only user variables (small, fast)
tracker.export_to_binary_with_mode("my_program_user", BinaryExportMode::UserOnly)?;
// Export all data (large, complete)
tracker.export_to_binary_with_mode("my_program_full", BinaryExportMode::Full)?;
Sourcepub fn export_user_binary<P: AsRef<Path>>(&self, path: P) -> TrackingResult<()>
pub fn export_user_binary<P: AsRef<Path>>(&self, path: P) -> TrackingResult<()>
Export only user-defined variables to binary format (.memscope file). This method filters allocations to include only those with variable names, resulting in smaller binary files and faster JSON conversion. The binary file will contain only user-defined variables, not system allocations.
§Arguments
path
- Base filename for the binary export (extension .memscope will be added automatically)
§Example
let tracker = get_global_tracker();
tracker.export_user_binary("my_program_user")?;
// Creates: MemoryAnalysis/my_program_user.memscope (user variables only)
Sourcepub fn export_full_binary<P: AsRef<Path>>(&self, path: P) -> TrackingResult<()>
pub fn export_full_binary<P: AsRef<Path>>(&self, path: P) -> TrackingResult<()>
Export all allocations (user + system) to binary format (.memscope file). This method includes all tracked allocations with null field elimination for optimal storage efficiency. Uses optimized processing for large datasets.
§Arguments
path
- Base filename for the binary export (extension .memscope will be added automatically)
§Example
let tracker = get_global_tracker();
tracker.export_full_binary("my_program_full")?;
// Creates: MemoryAnalysis/my_program_full.memscope
Sourcepub fn parse_binary_to_standard_json<P: AsRef<Path>>(
binary_path: P,
base_name: &str,
) -> TrackingResult<()>
pub fn parse_binary_to_standard_json<P: AsRef<Path>>( binary_path: P, base_name: &str, ) -> TrackingResult<()>
Convert binary file to standard JSON format (4 separate files)
This method reads a .memscope binary file and generates the standard 4-file JSON output format used by export_to_json.
§Arguments
binary_path
- Path to input .memscope filebase_name
- Base name for output files (will create 4 files with different suffixes)
§Examples
MemoryTracker::parse_binary_to_standard_json("data.memscope", "project_name")?;
Sourcepub fn parse_binary_to_json<P: AsRef<Path>>(
binary_path: P,
json_path: P,
) -> TrackingResult<()>
pub fn parse_binary_to_json<P: AsRef<Path>>( binary_path: P, json_path: P, ) -> TrackingResult<()>
Convert binary file to single JSON format (legacy compatibility)
§Examples
MemoryTracker::parse_binary_to_json("data.memscope", "data.json")?;
Sourcepub fn parse_binary_to_html<P: AsRef<Path>>(
binary_path: P,
html_path: P,
) -> TrackingResult<()>
pub fn parse_binary_to_html<P: AsRef<Path>>( binary_path: P, html_path: P, ) -> TrackingResult<()>
Convert binary file to HTML format
This method reads a .memscope binary file and generates an HTML report with memory allocation analysis and visualization.
§Arguments
binary_path
- Path to input .memscope filehtml_path
- Path for output HTML file
§Examples
MemoryTracker::parse_binary_to_html("data.memscope", "report.html")?;
Sourcepub fn export_binary_to_html<P: AsRef<Path>>(
binary_path: P,
html_path: P,
) -> TrackingResult<()>
pub fn export_binary_to_html<P: AsRef<Path>>( binary_path: P, html_path: P, ) -> TrackingResult<()>
Alias for parse_binary_to_html for backward compatibility
Sourcepub fn export_lifecycle_timeline<P: AsRef<Path>>(
&self,
path: P,
) -> TrackingResult<()>
pub fn export_lifecycle_timeline<P: AsRef<Path>>( &self, path: P, ) -> TrackingResult<()>
Export interactive lifecycle timeline showing variable lifecycles and relationships. This creates an advanced timeline with variable birth, life, death, and cross-section interactivity. All output files are automatically placed in the MemoryAnalysis/ directory.
§Arguments
path
- Output filename for the lifecycle timeline SVG file (recommended: “program_name_lifecycle.svg”)
Sourcepub fn analyze_drop_chain(
&self,
ptr: usize,
type_name: &str,
) -> Option<DropChainAnalysis>
pub fn analyze_drop_chain( &self, ptr: usize, type_name: &str, ) -> Option<DropChainAnalysis>
Analyze drop chain for an object being deallocated
Source§impl MemoryTracker
Ultra-fast export implementation (legacy methods for backward compatibility)
impl MemoryTracker
Ultra-fast export implementation (legacy methods for backward compatibility)
Sourcepub fn export_optimized_json_files<P: AsRef<Path>>(
&self,
base_path: P,
) -> TrackingResult<()>
pub fn export_optimized_json_files<P: AsRef<Path>>( &self, base_path: P, ) -> TrackingResult<()>
Optimized export to standard 4 JSON files (replaces export_separated_json_simple)
Sourcepub fn export_optimized_json_files_with_complex_types<P: AsRef<Path>>(
&self,
base_path: P,
) -> TrackingResult<()>
pub fn export_optimized_json_files_with_complex_types<P: AsRef<Path>>( &self, base_path: P, ) -> TrackingResult<()>
Export to 5 JSON files including complex types analysis
Sourcepub fn export_optimized_json_files_with_options<P: AsRef<Path>>(
&self,
base_path: P,
options: OptimizedExportOptions,
) -> TrackingResult<()>
pub fn export_optimized_json_files_with_options<P: AsRef<Path>>( &self, base_path: P, options: OptimizedExportOptions, ) -> TrackingResult<()>
Optimized export to standard 4 JSON files with custom options
Sourcepub fn export_extensible_json_files<P: AsRef<Path>>(
&self,
base_path: P,
file_types: &[JsonFileType],
) -> TrackingResult<()>
pub fn export_extensible_json_files<P: AsRef<Path>>( &self, base_path: P, file_types: &[JsonFileType], ) -> TrackingResult<()>
A generic export method reserved for future expansion. can easily add a 5th and 6th JSON file
Sourcepub fn export_extensible_json_files_with_options<P: AsRef<Path>>(
&self,
base_path: P,
file_types: &[JsonFileType],
options: OptimizedExportOptions,
) -> TrackingResult<()>
pub fn export_extensible_json_files_with_options<P: AsRef<Path>>( &self, base_path: P, file_types: &[JsonFileType], options: OptimizedExportOptions, ) -> TrackingResult<()>
A generic export method reserved for future expansion. can easily add a 5th and 6th JSON file
Source§impl MemoryTracker
impl MemoryTracker
Sourcepub fn export_to_json_optimized<P: AsRef<Path>>(
&self,
path: P,
) -> TrackingResult<ComplexTypeExportResult>
pub fn export_to_json_optimized<P: AsRef<Path>>( &self, path: P, ) -> TrackingResult<ComplexTypeExportResult>
Export tracking data with complex type optimization (separate files for better performance)
Trait Implementations§
Source§impl Default for MemoryTracker
impl Default for MemoryTracker
Auto Trait Implementations§
impl !Freeze for MemoryTracker
impl RefUnwindSafe for MemoryTracker
impl Send for MemoryTracker
impl Sync for MemoryTracker
impl Unpin for MemoryTracker
impl UnwindSafe for MemoryTracker
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read more