memscope-rs 0.2.3

A memory tracking library for Rust applications.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
//! Memory statistics types.
//!
//! This module contains types for tracking memory usage statistics,
//! including allocation counts, memory sizes, and fragmentation analysis.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

use super::allocation::AllocationInfo;
use super::scope::ScopeLifecycleMetrics;

/// Memory statistics.
///
/// Comprehensive statistics about memory allocations, deallocations,
/// leaks, and fragmentation.
#[derive(Debug, Clone, Default, Serialize)]
pub struct MemoryStats {
    /// Total number of allocations made.
    pub total_allocations: usize,
    /// Total bytes allocated.
    pub total_allocated: usize,
    /// Number of currently active allocations.
    pub active_allocations: usize,
    /// Total bytes in active allocations.
    pub active_memory: usize,
    /// Peak number of concurrent allocations.
    pub peak_allocations: usize,
    /// Peak memory usage in bytes.
    pub peak_memory: usize,
    /// Total number of deallocations performed.
    pub total_deallocations: usize,
    /// Total bytes deallocated.
    pub total_deallocated: usize,
    /// Number of leaked allocations.
    pub leaked_allocations: usize,
    /// Total bytes in leaked allocations.
    pub leaked_memory: usize,
    /// Analysis of memory fragmentation.
    pub fragmentation_analysis: FragmentationAnalysis,
    /// Lifecycle statistics for scopes.
    pub lifecycle_stats: ScopeLifecycleMetrics,
    /// List of all allocation information.
    pub allocations: Vec<AllocationInfo>,
    /// Statistics for system library allocations.
    pub system_library_stats: SystemLibraryStats,
    /// Analysis of concurrent memory operations.
    pub concurrency_analysis: ConcurrencyAnalysis,
}

impl MemoryStats {
    /// Create a new empty MemoryStats.
    pub fn new() -> Self {
        Self {
            total_allocations: 0,
            total_allocated: 0,
            active_allocations: 0,
            active_memory: 0,
            peak_allocations: 0,
            peak_memory: 0,
            total_deallocations: 0,
            total_deallocated: 0,
            leaked_allocations: 0,
            leaked_memory: 0,
            fragmentation_analysis: FragmentationAnalysis::default(),
            lifecycle_stats: ScopeLifecycleMetrics::default(),
            allocations: Vec::new(),
            system_library_stats: SystemLibraryStats::default(),
            concurrency_analysis: ConcurrencyAnalysis::default(),
        }
    }
}

impl From<crate::core::types::MemoryStats> for MemoryStats {
    fn from(old: crate::core::types::MemoryStats) -> Self {
        Self {
            total_allocations: old.total_allocations,
            total_allocated: old.total_allocated,
            active_allocations: old.active_allocations,
            active_memory: old.active_memory,
            peak_allocations: old.peak_allocations,
            peak_memory: old.peak_memory,
            total_deallocations: old.total_deallocations,
            total_deallocated: old.total_deallocated,
            leaked_allocations: old.leaked_allocations,
            leaked_memory: old.leaked_memory,
            // Convert FragmentationAnalysis
            fragmentation_analysis: FragmentationAnalysis {
                fragmentation_ratio: old.fragmentation_analysis.fragmentation_ratio,
                largest_free_block: old.fragmentation_analysis.largest_free_block,
                smallest_free_block: old.fragmentation_analysis.smallest_free_block,
                free_block_count: old.fragmentation_analysis.free_block_count,
                total_free_memory: old.fragmentation_analysis.total_free_memory,
                external_fragmentation: old.fragmentation_analysis.external_fragmentation,
                internal_fragmentation: old.fragmentation_analysis.internal_fragmentation,
            },
            // Use default values for complex nested types to avoid unsafe conversions
            lifecycle_stats: ScopeLifecycleMetrics::default(),
            allocations: old.allocations.into_iter().map(|a| a.into()).collect(),
            system_library_stats: SystemLibraryStats::default(),
            concurrency_analysis: ConcurrencyAnalysis::default(),
        }
    }
}

/// Memory type analysis.
#[derive(Debug, Clone, Serialize)]
pub struct MemoryTypeInfo {
    /// Name of the memory type.
    pub type_name: String,
    /// Total size in bytes for this type.
    pub total_size: usize,
    /// Number of allocations of this type.
    pub allocation_count: usize,
    /// Average size of allocations for this type.
    pub average_size: usize,
    /// Size of the largest allocation for this type.
    pub largest_allocation: usize,
    /// Size of the smallest allocation for this type.
    pub smallest_allocation: usize,
    /// Number of currently active instances.
    pub active_instances: usize,
    /// Number of leaked instances.
    pub leaked_instances: usize,
}

/// Type memory usage information.
#[derive(Debug, Clone, Serialize)]
pub struct TypeMemoryUsage {
    /// Name of the type.
    pub type_name: String,
    /// Total size allocated for this type.
    pub total_size: usize,
    /// Number of allocations for this type.
    pub allocation_count: usize,
    /// Average allocation size for this type.
    pub average_size: f64,
    /// Peak memory usage for this type.
    pub peak_size: usize,
    /// Current memory usage for this type.
    pub current_size: usize,
    /// Memory efficiency score for this type.
    pub efficiency_score: f64,
}

/// Fragmentation analysis.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct FragmentationAnalysis {
    /// Ratio of fragmented to total memory.
    pub fragmentation_ratio: f64,
    /// Size of the largest free memory block.
    pub largest_free_block: usize,
    /// Size of the smallest free memory block.
    pub smallest_free_block: usize,
    /// Total number of free memory blocks.
    pub free_block_count: usize,
    /// Total amount of free memory.
    pub total_free_memory: usize,
    /// External fragmentation percentage.
    pub external_fragmentation: f64,
    /// Internal fragmentation percentage.
    pub internal_fragmentation: f64,
}

/// System library usage statistics.
#[derive(Debug, Clone, Default, Serialize)]
pub struct SystemLibraryStats {
    /// Usage statistics for standard collections.
    pub std_collections: LibraryUsage,
    /// Usage statistics for async runtime.
    pub async_runtime: LibraryUsage,
    /// Usage statistics for network I/O.
    pub network_io: LibraryUsage,
    /// Usage statistics for file system operations.
    pub file_system: LibraryUsage,
    /// Usage statistics for serialization.
    pub serialization: LibraryUsage,
    /// Usage statistics for regex operations.
    pub regex_engine: LibraryUsage,
    /// Usage statistics for cryptographic operations.
    pub crypto_security: LibraryUsage,
    /// Usage statistics for database operations.
    pub database: LibraryUsage,
    /// Usage statistics for graphics and UI.
    pub graphics_ui: LibraryUsage,
    /// Usage statistics for HTTP operations.
    pub http_stack: LibraryUsage,
}

/// Library usage information.
#[derive(Debug, Clone, Default, Serialize)]
pub struct LibraryUsage {
    /// Number of allocations.
    pub allocation_count: usize,
    /// Total bytes allocated.
    pub total_bytes: usize,
    /// Peak memory usage in bytes.
    pub peak_bytes: usize,
    /// Average allocation size.
    pub average_size: f64,
    /// Categorized usage statistics.
    pub categories: HashMap<String, usize>,
    /// Functions with high allocation activity.
    pub hotspot_functions: Vec<String>,
}

/// Concurrency safety analysis.
#[derive(Debug, Clone, Default, Serialize)]
pub struct ConcurrencyAnalysis {
    /// Thread Safety Allocations.
    pub thread_safety_allocations: usize,
    /// Shared Memory Bytes.
    pub shared_memory_bytes: usize,
    /// Mutex Protected.
    pub mutex_protected: usize,
    /// Arc Shared.
    pub arc_shared: usize,
    /// Rc Shared.
    pub rc_shared: usize,
    /// Channel Buffers.
    pub channel_buffers: usize,
    /// Thread Local Storage.
    pub thread_local_storage: usize,
    /// Atomic Operations.
    pub atomic_operations: usize,
    /// Lock Contention Risk.
    pub lock_contention_risk: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_memory_stats_creation() {
        let stats = MemoryStats::new();

        assert_eq!(stats.total_allocations, 0);
        assert_eq!(stats.total_allocated, 0);
        assert_eq!(stats.active_allocations, 0);
    }

    #[test]
    fn test_fragmentation_analysis_default() {
        let frag = FragmentationAnalysis::default();

        assert_eq!(frag.fragmentation_ratio, 0.0);
        assert_eq!(frag.largest_free_block, 0);
        assert_eq!(frag.free_block_count, 0);
    }

    #[test]
    fn test_system_library_stats_default() {
        let stats = SystemLibraryStats::default();

        assert_eq!(stats.std_collections.allocation_count, 0);
        assert_eq!(stats.async_runtime.total_bytes, 0);
        assert_eq!(stats.network_io.peak_bytes, 0);
    }

    #[test]
    fn test_library_usage_default() {
        let usage = LibraryUsage::default();

        assert_eq!(usage.allocation_count, 0);
        assert_eq!(usage.total_bytes, 0);
        assert_eq!(usage.average_size, 0.0);
        assert!(usage.categories.is_empty());
        assert!(usage.hotspot_functions.is_empty());
    }

    #[test]
    fn test_concurrency_analysis_default() {
        let analysis = ConcurrencyAnalysis::default();

        assert_eq!(analysis.thread_safety_allocations, 0);
        assert_eq!(analysis.shared_memory_bytes, 0);
        assert_eq!(analysis.mutex_protected, 0);
    }

    #[test]
    fn test_memory_stats_default() {
        let stats = MemoryStats::default();

        assert_eq!(stats.total_allocations, 0);
        assert_eq!(stats.active_memory, 0);
        assert_eq!(stats.peak_memory, 0);
        assert_eq!(stats.leaked_allocations, 0);
    }

    #[test]
    fn test_memory_stats_with_values() {
        let mut stats = MemoryStats::new();
        stats.total_allocations = 100;
        stats.total_allocated = 1024 * 1024;
        stats.active_allocations = 50;
        stats.active_memory = 512 * 1024;
        stats.peak_allocations = 75;
        stats.peak_memory = 768 * 1024;
        stats.total_deallocations = 50;
        stats.total_deallocated = 512 * 1024;
        stats.leaked_allocations = 5;
        stats.leaked_memory = 10240;

        assert_eq!(stats.total_allocations, 100);
        assert_eq!(stats.active_allocations, 50);
        assert_eq!(stats.leaked_allocations, 5);
    }

    #[test]
    fn test_fragmentation_analysis_with_values() {
        let frag = FragmentationAnalysis {
            fragmentation_ratio: 0.35,
            largest_free_block: 65536,
            smallest_free_block: 16,
            free_block_count: 128,
            total_free_memory: 524288,
            external_fragmentation: 0.25,
            internal_fragmentation: 0.10,
        };

        assert!((frag.fragmentation_ratio - 0.35).abs() < f64::EPSILON);
        assert_eq!(frag.free_block_count, 128);
        assert!((frag.external_fragmentation - 0.25).abs() < f64::EPSILON);
    }

    #[test]
    fn test_memory_type_info_creation() {
        let info = MemoryTypeInfo {
            type_name: "Vec<u8>".to_string(),
            total_size: 1024,
            allocation_count: 10,
            average_size: 102,
            largest_allocation: 512,
            smallest_allocation: 16,
            active_instances: 8,
            leaked_instances: 1,
        };

        assert_eq!(info.type_name, "Vec<u8>");
        assert_eq!(info.allocation_count, 10);
        assert_eq!(info.leaked_instances, 1);
    }

    #[test]
    fn test_type_memory_usage_creation() {
        let usage = TypeMemoryUsage {
            type_name: "String".to_string(),
            total_size: 2048,
            allocation_count: 20,
            average_size: 102.4,
            peak_size: 512,
            current_size: 256,
            efficiency_score: 0.85,
        };

        assert_eq!(usage.type_name, "String");
        assert!((usage.average_size - 102.4).abs() < f64::EPSILON);
        assert!((usage.efficiency_score - 0.85).abs() < f64::EPSILON);
    }

    #[test]
    fn test_library_usage_with_values() {
        let mut categories = HashMap::new();
        categories.insert("HashMap".to_string(), 1000);
        categories.insert("Vec".to_string(), 2000);

        let usage = LibraryUsage {
            allocation_count: 100,
            total_bytes: 10240,
            peak_bytes: 5120,
            average_size: 102.4,
            categories,
            hotspot_functions: vec!["push".to_string(), "insert".to_string()],
        };

        assert_eq!(usage.allocation_count, 100);
        assert_eq!(usage.categories.len(), 2);
        assert_eq!(usage.hotspot_functions.len(), 2);
    }

    #[test]
    fn test_system_library_stats_with_values() {
        let mut stats = SystemLibraryStats::default();
        stats.std_collections.allocation_count = 500;
        stats.async_runtime.total_bytes = 10240;
        stats.network_io.peak_bytes = 2048;
        stats.file_system.allocation_count = 100;
        stats.serialization.total_bytes = 4096;
        stats.regex_engine.allocation_count = 50;
        stats.crypto_security.total_bytes = 8192;
        stats.database.allocation_count = 200;
        stats.graphics_ui.total_bytes = 16384;
        stats.http_stack.allocation_count = 75;

        assert_eq!(stats.std_collections.allocation_count, 500);
        assert_eq!(stats.async_runtime.total_bytes, 10240);
    }

    #[test]
    fn test_concurrency_analysis_with_values() {
        let analysis = ConcurrencyAnalysis {
            thread_safety_allocations: 100,
            shared_memory_bytes: 10240,
            mutex_protected: 50,
            arc_shared: 30,
            rc_shared: 20,
            channel_buffers: 15,
            thread_local_storage: 10,
            atomic_operations: 200,
            lock_contention_risk: "Low".to_string(),
        };

        assert_eq!(analysis.thread_safety_allocations, 100);
        assert_eq!(analysis.arc_shared, 30);
        assert_eq!(analysis.lock_contention_risk, "Low");
    }

    #[test]
    fn test_memory_stats_serialization() {
        let stats = MemoryStats::new();

        let json = serde_json::to_string(&stats).unwrap();
        assert!(json.contains("total_allocations"));
        assert!(json.contains("active_memory"));
    }

    #[test]
    fn test_fragmentation_analysis_serialization() {
        let frag = FragmentationAnalysis {
            fragmentation_ratio: 0.5,
            largest_free_block: 1024,
            smallest_free_block: 16,
            free_block_count: 50,
            total_free_memory: 2048,
            external_fragmentation: 0.3,
            internal_fragmentation: 0.2,
        };

        let json = serde_json::to_string(&frag).unwrap();
        let deserialized: FragmentationAnalysis = serde_json::from_str(&json).unwrap();
        assert!((deserialized.fragmentation_ratio - frag.fragmentation_ratio).abs() < f64::EPSILON);
    }

    #[test]
    fn test_memory_type_info_serialization() {
        let info = MemoryTypeInfo {
            type_name: "HashMap<String, i32>".to_string(),
            total_size: 4096,
            allocation_count: 25,
            average_size: 163,
            largest_allocation: 1024,
            smallest_allocation: 64,
            active_instances: 20,
            leaked_instances: 2,
        };

        let json = serde_json::to_string(&info).unwrap();
        assert!(json.contains("HashMap"));
        assert!(json.contains("4096"));
    }

    #[test]
    fn test_type_memory_usage_serialization() {
        let usage = TypeMemoryUsage {
            type_name: "Box<dyn Any>".to_string(),
            total_size: 8192,
            allocation_count: 100,
            average_size: 81.92,
            peak_size: 2048,
            current_size: 1024,
            efficiency_score: 0.75,
        };

        let json = serde_json::to_string(&usage).unwrap();
        assert!(json.contains("Box"));
        assert!(json.contains("8192"));
    }

    #[test]
    fn test_library_usage_serialization() {
        let usage = LibraryUsage {
            allocation_count: 50,
            total_bytes: 5120,
            peak_bytes: 2560,
            average_size: 102.4,
            categories: HashMap::new(),
            hotspot_functions: vec![],
        };

        let json = serde_json::to_string(&usage).unwrap();
        assert!(json.contains("allocation_count"));
    }

    #[test]
    fn test_concurrency_analysis_serialization() {
        let analysis = ConcurrencyAnalysis {
            thread_safety_allocations: 10,
            shared_memory_bytes: 1024,
            mutex_protected: 5,
            arc_shared: 3,
            rc_shared: 2,
            channel_buffers: 1,
            thread_local_storage: 0,
            atomic_operations: 50,
            lock_contention_risk: "Medium".to_string(),
        };

        let json = serde_json::to_string(&analysis).unwrap();
        assert!(json.contains("thread_safety_allocations"));
    }

    #[test]
    fn test_boundary_values_memory_stats() {
        let mut stats = MemoryStats::new();
        stats.total_allocations = usize::MAX;
        stats.total_allocated = usize::MAX;
        stats.active_allocations = usize::MAX;
        stats.active_memory = usize::MAX;
        stats.peak_allocations = usize::MAX;
        stats.peak_memory = usize::MAX;

        assert_eq!(stats.total_allocations, usize::MAX);
        assert_eq!(stats.peak_memory, usize::MAX);
    }

    #[test]
    fn test_boundary_values_fragmentation() {
        let frag = FragmentationAnalysis {
            fragmentation_ratio: f64::MAX,
            largest_free_block: usize::MAX,
            smallest_free_block: usize::MAX,
            free_block_count: usize::MAX,
            total_free_memory: usize::MAX,
            external_fragmentation: f64::MAX,
            internal_fragmentation: f64::MAX,
        };

        assert!(frag.fragmentation_ratio.is_finite());
        assert_eq!(frag.largest_free_block, usize::MAX);
    }

    #[test]
    fn test_boundary_values_concurrency() {
        let analysis = ConcurrencyAnalysis {
            thread_safety_allocations: usize::MAX,
            shared_memory_bytes: usize::MAX,
            mutex_protected: usize::MAX,
            arc_shared: usize::MAX,
            rc_shared: usize::MAX,
            channel_buffers: usize::MAX,
            thread_local_storage: usize::MAX,
            atomic_operations: usize::MAX,
            lock_contention_risk: String::new(),
        };

        assert_eq!(analysis.thread_safety_allocations, usize::MAX);
        assert_eq!(analysis.atomic_operations, usize::MAX);
    }

    #[test]
    fn test_memory_stats_clone() {
        let mut stats = MemoryStats::new();
        stats.total_allocations = 42;

        let cloned = stats.clone();
        assert_eq!(cloned.total_allocations, 42);
    }

    #[test]
    fn test_memory_stats_debug() {
        let stats = MemoryStats::new();
        let debug_str = format!("{:?}", stats);

        assert!(debug_str.contains("MemoryStats"));
        assert!(debug_str.contains("total_allocations"));
    }

    #[test]
    fn test_fragmentation_analysis_clone() {
        let frag = FragmentationAnalysis {
            fragmentation_ratio: 0.75,
            largest_free_block: 2048,
            smallest_free_block: 32,
            free_block_count: 100,
            total_free_memory: 4096,
            external_fragmentation: 0.5,
            internal_fragmentation: 0.25,
        };

        let cloned = frag.clone();
        assert!((cloned.fragmentation_ratio - 0.75).abs() < f64::EPSILON);
    }

    #[test]
    fn test_library_usage_clone() {
        let usage = LibraryUsage {
            allocation_count: 25,
            total_bytes: 2560,
            peak_bytes: 1280,
            average_size: 102.4,
            categories: HashMap::new(),
            hotspot_functions: vec!["test".to_string()],
        };

        let cloned = usage.clone();
        assert_eq!(cloned.allocation_count, 25);
    }

    #[test]
    fn test_concurrency_analysis_clone() {
        let analysis = ConcurrencyAnalysis {
            thread_safety_allocations: 100,
            shared_memory_bytes: 2048,
            mutex_protected: 50,
            arc_shared: 25,
            rc_shared: 15,
            channel_buffers: 10,
            thread_local_storage: 5,
            atomic_operations: 200,
            lock_contention_risk: "High".to_string(),
        };

        let cloned = analysis.clone();
        assert_eq!(cloned.thread_safety_allocations, 100);
    }

    #[test]
    fn test_empty_library_usage_categories() {
        let usage = LibraryUsage::default();
        assert!(usage.categories.is_empty());
        assert!(usage.hotspot_functions.is_empty());
    }

    #[test]
    fn test_library_usage_with_categories() {
        let mut categories = HashMap::new();
        categories.insert("String".to_string(), 500);
        categories.insert("Vec".to_string(), 1000);

        let usage = LibraryUsage {
            allocation_count: 10,
            total_bytes: 1500,
            peak_bytes: 750,
            average_size: 150.0,
            categories,
            hotspot_functions: vec![],
        };

        assert_eq!(usage.categories.get("String"), Some(&500));
        assert_eq!(usage.categories.get("Vec"), Some(&1000));
        assert_eq!(usage.categories.get("HashMap"), None);
    }
}