MemoryTracker

Struct MemoryTracker 

Source
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

Source

pub fn fast_track_allocation( &self, ptr: usize, size: usize, var_name: String, ) -> TrackingResult<()>

Fast track allocation for testing (minimal overhead)

Source

pub fn track_allocation(&self, ptr: usize, size: usize) -> TrackingResult<()>

Track a new memory allocation using bounded stats.

Source

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

Source

pub fn track_deallocation(&self, ptr: usize) -> TrackingResult<()>

Track a memory deallocation using bounded stats.

Source

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

Source

pub fn associate_var( &self, ptr: usize, var_name: String, type_name: String, ) -> TrackingResult<()>

Associate a variable name and type with an allocation.

Source

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

Source

pub fn update_smart_pointer_ref_count( &self, ptr: usize, strong_count: usize, weak_count: usize, ) -> TrackingResult<()>

Update reference count for a smart pointer

Source

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

Source

pub fn track_deallocation_with_lifetime( &self, ptr: usize, lifetime_ms: u64, ) -> TrackingResult<()>

Track a memory deallocation with precise lifetime information.

Source

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.

Source

pub fn record_ownership_event(&self, ptr: usize, event_type: OwnershipEventType)

Record an ownership event for detailed lifecycle tracking

Source

pub fn get_ownership_summary(&self, ptr: usize) -> Option<OwnershipSummary>

Get ownership summary for an allocation

Source

pub fn export_ownership_history(&self) -> Result<String, String>

Export ownership history to JSON

Source§

impl MemoryTracker

Source

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.

Source

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 file
  • unsafe_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)
)?;
Source

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

Source

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
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
Source

pub fn export_to_json_with_options<P: AsRef<Path>>( &self, path: P, options: ExportJsonOptions, ) -> TrackingResult<()>

Export memory tracking data with custom options.

§Examples
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();
Source

pub fn get_memory_by_type(&self) -> TrackingResult<Vec<TypeMemoryUsage>>

Get memory usage by type for export

Source§

impl MemoryTracker

Source

pub fn analyze_memory_layout( &self, type_name: &str, size: usize, ) -> Option<MemoryLayoutInfo>

Analyze memory layout information with enhanced container analysis

Source

pub fn analyze_memory_fragmentation(&self) -> EnhancedFragmentationAnalysis

Analyze memory fragmentation

Source

pub fn analyze_generic_type( &self, type_name: &str, size: usize, ) -> Option<GenericTypeInfo>

Analyze generic type information

Source

pub fn analyze_dynamic_type( &self, type_name: &str, size: usize, ) -> Option<DynamicTypeInfo>

Analyze dynamic type information (trait objects)

Source

pub fn collect_runtime_state(&self) -> RuntimeStateInfo

Collect runtime state information

Source

pub fn analyze_type_relationships( &self, type_name: &str, ) -> Option<TypeRelationshipInfo>

Analyze type relationships

Source

pub fn track_type_usage(&self, type_name: &str) -> Option<TypeUsageInfo>

Track type usage with enhanced statistics collection

Source

pub fn analyze_stack_allocation( &self, type_name: &str, ptr: usize, ) -> Option<StackAllocationInfo>

Analyze stack allocation information

Source§

impl MemoryTracker

Source

pub fn new() -> Self

Create a new memory tracker.

Source

pub fn get_stats(&self) -> TrackingResult<MemoryStats>

Get current memory statistics with advanced analysis.

Source

pub fn get_active_allocations(&self) -> TrackingResult<Vec<AllocationInfo>>

Get all currently active allocations.

Source

pub fn get_allocation_history(&self) -> TrackingResult<Vec<AllocationInfo>>

Get the complete allocation history.

Source

pub fn set_fast_mode(&self, enabled: bool)

Enable or disable fast mode.

Source

pub fn is_fast_mode(&self) -> bool

Check if fast mode is enabled.

Source

pub fn enable_fast_mode(&self)

Enable fast mode for testing

Source

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”)
Source

pub fn ensure_memory_analysis_path<P: AsRef<Path>>(&self, path: P) -> PathBuf

Ensure the memory analysis path exists and return the full path

Source

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
Source

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)?;
Source

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)
Source

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
Source

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 file
  • base_name - Base name for output files (will create 4 files with different suffixes)
§Examples
MemoryTracker::parse_binary_to_standard_json("data.memscope", "project_name")?;
Source

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")?;
Source

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 file
  • html_path - Path for output HTML file
§Examples
MemoryTracker::parse_binary_to_html("data.memscope", "report.html")?;
Source

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

Source

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”)
Source

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)

Source

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)

Source

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

Source

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

Source

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

Source

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

Source

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

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Drop for MemoryTracker

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more