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
//! Fragmentation analysis types.
//!
//! This module contains types for analyzing memory fragmentation,
//! including block distribution, metrics, and cause analysis.

use serde::{Deserialize, Serialize};

use super::allocation::ImpactLevel;

/// Enhanced memory fragmentation analysis.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EnhancedFragmentationAnalysis {
    /// Total heap size.
    pub total_heap_size: usize,
    /// Used heap size.
    pub used_heap_size: usize,
    /// Free heap size.
    pub free_heap_size: usize,
    /// Number of free blocks.
    pub free_block_count: usize,
    /// Free block size distribution.
    pub free_block_distribution: Vec<BlockSizeRange>,
    /// Fragmentation metrics.
    pub fragmentation_metrics: FragmentationMetrics,
    /// Allocation patterns causing fragmentation.
    pub fragmentation_causes: Vec<FragmentationCause>,
}

/// Block size range for distribution analysis.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BlockSizeRange {
    /// Minimum size in range.
    pub min_size: usize,
    /// Maximum size in range.
    pub max_size: usize,
    /// Number of blocks in this range.
    pub block_count: usize,
    /// Total size of blocks in this range.
    pub total_size: usize,
}

/// Fragmentation metrics.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FragmentationMetrics {
    /// External fragmentation ratio.
    pub external_fragmentation: f64,
    /// Internal fragmentation ratio.
    pub internal_fragmentation: f64,
    /// Largest free block size.
    pub largest_free_block: usize,
    /// Average free block size.
    pub average_free_block_size: f64,
    /// Fragmentation severity level.
    pub severity_level: FragmentationSeverity,
}

/// Fragmentation severity levels.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum FragmentationSeverity {
    /// Low fragmentation severity.
    Low,
    /// Moderate fragmentation severity.
    Moderate,
    /// High fragmentation severity.
    High,
    /// Critical fragmentation severity.
    Critical,
}

/// Fragmentation cause analysis.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FragmentationCause {
    /// Cause type.
    pub cause_type: FragmentationCauseType,
    /// Description of the cause.
    pub description: String,
    /// Impact on fragmentation.
    pub impact_level: ImpactLevel,
    /// Suggested mitigation.
    pub mitigation_suggestion: String,
}

/// Types of fragmentation causes.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub enum FragmentationCauseType {
    /// Mixed allocation sizes.
    MixedAllocationSizes,
    /// Frequent allocation/deallocation.
    FrequentAllocDealloc,
    /// Long-lived allocations blocking coalescing.
    LongLivedAllocations,
    /// Poor allocation strategy.
    PoorAllocationStrategy,
    /// Memory leaks.
    MemoryLeaks,
}

// Implement From trait for converting from core::types to capture::types
impl From<crate::core::types::EnhancedFragmentationAnalysis> for EnhancedFragmentationAnalysis {
    fn from(old: crate::core::types::EnhancedFragmentationAnalysis) -> Self {
        Self {
            total_heap_size: old.total_heap_size,
            used_heap_size: old.used_heap_size,
            free_heap_size: old.free_heap_size,
            free_block_count: old.free_block_count,
            free_block_distribution: old
                .free_block_distribution
                .into_iter()
                .map(|b| BlockSizeRange {
                    min_size: b.min_size,
                    max_size: b.max_size,
                    block_count: b.block_count,
                    total_size: b.total_size,
                })
                .collect(),
            fragmentation_metrics: FragmentationMetrics {
                external_fragmentation: old.fragmentation_metrics.external_fragmentation,
                internal_fragmentation: old.fragmentation_metrics.internal_fragmentation,
                largest_free_block: old.fragmentation_metrics.largest_free_block,
                average_free_block_size: old.fragmentation_metrics.average_free_block_size,
                severity_level: match old.fragmentation_metrics.severity_level {
                    crate::core::types::FragmentationSeverity::Low => FragmentationSeverity::Low,
                    crate::core::types::FragmentationSeverity::Moderate => {
                        FragmentationSeverity::Moderate
                    }
                    crate::core::types::FragmentationSeverity::High => FragmentationSeverity::High,
                    crate::core::types::FragmentationSeverity::Critical => {
                        FragmentationSeverity::Critical
                    }
                },
            },
            fragmentation_causes: old
                .fragmentation_causes
                .into_iter()
                .map(|c| FragmentationCause {
                    cause_type: match c.cause_type {
                        crate::core::types::FragmentationCauseType::MixedAllocationSizes => {
                            FragmentationCauseType::MixedAllocationSizes
                        }
                        crate::core::types::FragmentationCauseType::FrequentAllocDealloc => {
                            FragmentationCauseType::FrequentAllocDealloc
                        }
                        crate::core::types::FragmentationCauseType::LongLivedAllocations => {
                            FragmentationCauseType::LongLivedAllocations
                        }
                        crate::core::types::FragmentationCauseType::PoorAllocationStrategy => {
                            FragmentationCauseType::PoorAllocationStrategy
                        }
                        crate::core::types::FragmentationCauseType::MemoryLeaks => {
                            FragmentationCauseType::MemoryLeaks
                        }
                    },
                    description: c.description,
                    impact_level: match c.impact_level {
                        crate::core::types::ImpactLevel::Low => ImpactLevel::Low,
                        crate::core::types::ImpactLevel::Medium => ImpactLevel::Medium,
                        crate::core::types::ImpactLevel::High => ImpactLevel::High,
                        crate::core::types::ImpactLevel::Critical => ImpactLevel::Critical,
                    },
                    mitigation_suggestion: c.mitigation_suggestion,
                })
                .collect(),
        }
    }
}

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

    #[test]
    fn test_enhanced_fragmentation_analysis() {
        let analysis = EnhancedFragmentationAnalysis {
            total_heap_size: 1024 * 1024,
            used_heap_size: 512 * 1024,
            free_heap_size: 512 * 1024,
            free_block_count: 10,
            free_block_distribution: vec![],
            fragmentation_metrics: FragmentationMetrics {
                external_fragmentation: 0.3,
                internal_fragmentation: 0.1,
                largest_free_block: 256 * 1024,
                average_free_block_size: 51200.0,
                severity_level: FragmentationSeverity::Low,
            },
            fragmentation_causes: vec![],
        };

        assert_eq!(analysis.total_heap_size, 1024 * 1024);
        assert_eq!(analysis.free_block_count, 10);
    }

    #[test]
    fn test_fragmentation_severity() {
        let severity = FragmentationSeverity::High;
        assert!(matches!(severity, FragmentationSeverity::High));
    }

    #[test]
    fn test_fragmentation_cause_type() {
        let cause = FragmentationCauseType::MixedAllocationSizes;
        assert!(matches!(
            cause,
            FragmentationCauseType::MixedAllocationSizes
        ));
    }

    #[test]
    fn test_block_size_range_creation() {
        let range = BlockSizeRange {
            min_size: 0,
            max_size: 1024,
            block_count: 50,
            total_size: 25600,
        };

        assert_eq!(range.min_size, 0);
        assert_eq!(range.max_size, 1024);
        assert_eq!(range.block_count, 50);
        assert_eq!(range.total_size, 25600);
    }

    #[test]
    fn test_block_size_range_serialization() {
        let range = BlockSizeRange {
            min_size: 1024,
            max_size: 4096,
            block_count: 25,
            total_size: 64000,
        };

        let json = serde_json::to_string(&range).unwrap();
        let deserialized: BlockSizeRange = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, range);
    }

    #[test]
    fn test_fragmentation_metrics_all_severities() {
        let severities = [
            FragmentationSeverity::Low,
            FragmentationSeverity::Moderate,
            FragmentationSeverity::High,
            FragmentationSeverity::Critical,
        ];

        for severity in severities {
            let metrics = FragmentationMetrics {
                external_fragmentation: 0.5,
                internal_fragmentation: 0.2,
                largest_free_block: 1024,
                average_free_block_size: 512.0,
                severity_level: severity.clone(),
            };
            assert_eq!(metrics.severity_level, severity);
        }
    }

    #[test]
    fn test_fragmentation_metrics_boundary_values() {
        let metrics = FragmentationMetrics {
            external_fragmentation: 0.0,
            internal_fragmentation: 1.0,
            largest_free_block: 0,
            average_free_block_size: 0.0,
            severity_level: FragmentationSeverity::Critical,
        };

        assert!((metrics.external_fragmentation - 0.0).abs() < f64::EPSILON);
        assert!((metrics.internal_fragmentation - 1.0).abs() < f64::EPSILON);
        assert_eq!(metrics.largest_free_block, 0);
    }

    #[test]
    fn test_fragmentation_metrics_serialization() {
        let metrics = FragmentationMetrics {
            external_fragmentation: 0.75,
            internal_fragmentation: 0.25,
            largest_free_block: 2048,
            average_free_block_size: 1024.0,
            severity_level: FragmentationSeverity::High,
        };

        let json = serde_json::to_string(&metrics).unwrap();
        let deserialized: FragmentationMetrics = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, metrics);
    }

    #[test]
    fn test_fragmentation_cause_creation() {
        let cause = FragmentationCause {
            cause_type: FragmentationCauseType::FrequentAllocDealloc,
            description: "Frequent allocation and deallocation pattern".to_string(),
            impact_level: ImpactLevel::High,
            mitigation_suggestion: "Use object pooling".to_string(),
        };

        assert!(matches!(
            cause.cause_type,
            FragmentationCauseType::FrequentAllocDealloc
        ));
        assert_eq!(
            cause.description,
            "Frequent allocation and deallocation pattern"
        );
        assert!(matches!(cause.impact_level, ImpactLevel::High));
    }

    #[test]
    fn test_all_fragmentation_cause_types() {
        let cause_types = [
            FragmentationCauseType::MixedAllocationSizes,
            FragmentationCauseType::FrequentAllocDealloc,
            FragmentationCauseType::LongLivedAllocations,
            FragmentationCauseType::PoorAllocationStrategy,
            FragmentationCauseType::MemoryLeaks,
        ];

        for cause_type in cause_types {
            let cause = FragmentationCause {
                cause_type: cause_type.clone(),
                description: "Test description".to_string(),
                impact_level: ImpactLevel::Low,
                mitigation_suggestion: "Test mitigation".to_string(),
            };
            assert_eq!(cause.cause_type, cause_type);
        }
    }

    #[test]
    fn test_fragmentation_cause_serialization() {
        let cause = FragmentationCause {
            cause_type: FragmentationCauseType::MemoryLeaks,
            description: "Memory leak detected".to_string(),
            impact_level: ImpactLevel::Critical,
            mitigation_suggestion: "Fix memory leaks".to_string(),
        };

        let json = serde_json::to_string(&cause).unwrap();
        let deserialized: FragmentationCause = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, cause);
    }

    #[test]
    fn test_all_fragmentation_severities_serialization() {
        let severities = vec![
            FragmentationSeverity::Low,
            FragmentationSeverity::Moderate,
            FragmentationSeverity::High,
            FragmentationSeverity::Critical,
        ];

        for severity in severities {
            let json = serde_json::to_string(&severity).unwrap();
            let deserialized: FragmentationSeverity = serde_json::from_str(&json).unwrap();
            assert_eq!(deserialized, severity);
        }
    }

    #[test]
    fn test_all_cause_types_serialization() {
        let cause_types = vec![
            FragmentationCauseType::MixedAllocationSizes,
            FragmentationCauseType::FrequentAllocDealloc,
            FragmentationCauseType::LongLivedAllocations,
            FragmentationCauseType::PoorAllocationStrategy,
            FragmentationCauseType::MemoryLeaks,
        ];

        for cause_type in cause_types {
            let json = serde_json::to_string(&cause_type).unwrap();
            let deserialized: FragmentationCauseType = serde_json::from_str(&json).unwrap();
            assert_eq!(deserialized, cause_type);
        }
    }

    #[test]
    fn test_enhanced_fragmentation_analysis_with_distribution() {
        let distribution = vec![
            BlockSizeRange {
                min_size: 0,
                max_size: 256,
                block_count: 100,
                total_size: 12800,
            },
            BlockSizeRange {
                min_size: 256,
                max_size: 1024,
                block_count: 50,
                total_size: 32000,
            },
        ];

        let causes = vec![FragmentationCause {
            cause_type: FragmentationCauseType::MixedAllocationSizes,
            description: "Mixed allocation sizes".to_string(),
            impact_level: ImpactLevel::Medium,
            mitigation_suggestion: "Use size classes".to_string(),
        }];

        let analysis = EnhancedFragmentationAnalysis {
            total_heap_size: 1024 * 1024,
            used_heap_size: 768 * 1024,
            free_heap_size: 256 * 1024,
            free_block_count: 150,
            free_block_distribution: distribution.clone(),
            fragmentation_metrics: FragmentationMetrics {
                external_fragmentation: 0.6,
                internal_fragmentation: 0.15,
                largest_free_block: 65536,
                average_free_block_size: 1706.0,
                severity_level: FragmentationSeverity::Moderate,
            },
            fragmentation_causes: causes.clone(),
        };

        assert_eq!(analysis.free_block_distribution.len(), 2);
        assert_eq!(analysis.free_block_distribution[0].block_count, 100);
        assert_eq!(analysis.fragmentation_causes.len(), 1);
    }

    #[test]
    fn test_enhanced_fragmentation_analysis_serialization() {
        let analysis = EnhancedFragmentationAnalysis {
            total_heap_size: 2048 * 1024,
            used_heap_size: 1024 * 1024,
            free_heap_size: 1024 * 1024,
            free_block_count: 25,
            free_block_distribution: vec![BlockSizeRange {
                min_size: 0,
                max_size: 4096,
                block_count: 25,
                total_size: 51200,
            }],
            fragmentation_metrics: FragmentationMetrics {
                external_fragmentation: 0.4,
                internal_fragmentation: 0.1,
                largest_free_block: 32768,
                average_free_block_size: 40960.0,
                severity_level: FragmentationSeverity::Low,
            },
            fragmentation_causes: vec![],
        };

        let json = serde_json::to_string(&analysis).unwrap();
        let deserialized: EnhancedFragmentationAnalysis = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized, analysis);
    }

    #[test]
    fn test_enhanced_fragmentation_analysis_clone() {
        let analysis = EnhancedFragmentationAnalysis {
            total_heap_size: 1024,
            used_heap_size: 512,
            free_heap_size: 512,
            free_block_count: 5,
            free_block_distribution: vec![],
            fragmentation_metrics: FragmentationMetrics {
                external_fragmentation: 0.5,
                internal_fragmentation: 0.2,
                largest_free_block: 256,
                average_free_block_size: 102.4,
                severity_level: FragmentationSeverity::Moderate,
            },
            fragmentation_causes: vec![],
        };

        let cloned = analysis.clone();
        assert_eq!(cloned.total_heap_size, analysis.total_heap_size);
        assert_eq!(cloned.free_block_count, analysis.free_block_count);
    }

    #[test]
    fn test_enhanced_fragmentation_analysis_debug() {
        let analysis = EnhancedFragmentationAnalysis {
            total_heap_size: 1024,
            used_heap_size: 512,
            free_heap_size: 512,
            free_block_count: 5,
            free_block_distribution: vec![],
            fragmentation_metrics: FragmentationMetrics {
                external_fragmentation: 0.5,
                internal_fragmentation: 0.2,
                largest_free_block: 256,
                average_free_block_size: 102.4,
                severity_level: FragmentationSeverity::Low,
            },
            fragmentation_causes: vec![],
        };

        let debug_str = format!("{:?}", analysis);
        assert!(debug_str.contains("EnhancedFragmentationAnalysis"));
        assert!(debug_str.contains("total_heap_size"));
    }

    #[test]
    fn test_block_size_range_equality() {
        let range1 = BlockSizeRange {
            min_size: 0,
            max_size: 1024,
            block_count: 10,
            total_size: 5120,
        };
        let range2 = BlockSizeRange {
            min_size: 0,
            max_size: 1024,
            block_count: 10,
            total_size: 5120,
        };
        let range3 = BlockSizeRange {
            min_size: 0,
            max_size: 2048,
            block_count: 10,
            total_size: 5120,
        };

        assert_eq!(range1, range2);
        assert_ne!(range1, range3);
    }

    #[test]
    fn test_fragmentation_severity_equality() {
        assert_eq!(FragmentationSeverity::Low, FragmentationSeverity::Low);
        assert_ne!(FragmentationSeverity::Low, FragmentationSeverity::High);
        assert_ne!(
            FragmentationSeverity::Moderate,
            FragmentationSeverity::Critical
        );
    }

    #[test]
    fn test_fragmentation_cause_type_equality() {
        assert_eq!(
            FragmentationCauseType::MixedAllocationSizes,
            FragmentationCauseType::MixedAllocationSizes
        );
        assert_ne!(
            FragmentationCauseType::MixedAllocationSizes,
            FragmentationCauseType::MemoryLeaks
        );
    }

    #[test]
    fn test_fragmentation_cause_with_all_impact_levels() {
        let impact_levels = [
            ImpactLevel::Low,
            ImpactLevel::Medium,
            ImpactLevel::High,
            ImpactLevel::Critical,
        ];

        for impact in impact_levels {
            let cause = FragmentationCause {
                cause_type: FragmentationCauseType::PoorAllocationStrategy,
                description: "Test".to_string(),
                impact_level: impact.clone(),
                mitigation_suggestion: "Fix it".to_string(),
            };
            assert_eq!(cause.impact_level, impact);
        }
    }

    #[test]
    fn test_empty_free_block_distribution() {
        let analysis = EnhancedFragmentationAnalysis {
            total_heap_size: 1024,
            used_heap_size: 0,
            free_heap_size: 1024,
            free_block_count: 0,
            free_block_distribution: vec![],
            fragmentation_metrics: FragmentationMetrics {
                external_fragmentation: 0.0,
                internal_fragmentation: 0.0,
                largest_free_block: 1024,
                average_free_block_size: 0.0,
                severity_level: FragmentationSeverity::Low,
            },
            fragmentation_causes: vec![],
        };

        assert!(analysis.free_block_distribution.is_empty());
        assert_eq!(analysis.free_block_count, 0);
    }

    #[test]
    fn test_large_heap_analysis() {
        let analysis = EnhancedFragmentationAnalysis {
            total_heap_size: usize::MAX / 2,
            used_heap_size: usize::MAX / 4,
            free_heap_size: usize::MAX / 4,
            free_block_count: 1000000,
            free_block_distribution: vec![],
            fragmentation_metrics: FragmentationMetrics {
                external_fragmentation: f64::MAX,
                internal_fragmentation: f64::MIN,
                largest_free_block: usize::MAX,
                average_free_block_size: f64::INFINITY,
                severity_level: FragmentationSeverity::Critical,
            },
            fragmentation_causes: vec![],
        };

        assert_eq!(analysis.total_heap_size, usize::MAX / 2);
        assert!(
            analysis
                .fragmentation_metrics
                .external_fragmentation
                .is_finite()
                || analysis
                    .fragmentation_metrics
                    .external_fragmentation
                    .is_infinite()
        );
    }
}