memscope-rs 0.2.6

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
654
655
//! Common utility functions shared across modules

use std::hash::{Hash, Hasher};
use std::thread::ThreadId;
use std::time::{SystemTime, UNIX_EPOCH};

/// Get current timestamp in nanoseconds since Unix epoch
pub fn current_timestamp_nanos() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_nanos() as u64
}

/// Convert ThreadId to u64 for serialization and storage.
///
/// This uses a hash-based approach since ThreadId cannot be directly
/// converted to u64. The hash is consistent for the same ThreadId.
pub fn thread_id_to_u64(thread_id: ThreadId) -> u64 {
    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    thread_id.hash(&mut hasher);
    hasher.finish()
}

/// Capture-local thread identity, safe even inside allocator callbacks during
/// Rust thread bootstrap. Calling `std::thread::current()` there can initialize
/// runtime TLS before `spawn` installs its thread handle and abort the process.
/// These monotonically assigned IDs are not OS CPU IDs or hashed Rust ThreadIds.
pub fn current_thread_id_u64() -> u64 {
    static NEXT_THREAD_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
    thread_local! {
        static CAPTURE_THREAD_ID: u64 = NEXT_THREAD_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    }
    CAPTURE_THREAD_ID.with(|id| *id)
}

/// Format bytes in a human-readable format
pub fn format_bytes(bytes: usize) -> String {
    const KB: usize = 1024;
    const MB: usize = KB * 1024;
    const GB: usize = MB * 1024;
    const TB: usize = GB * 1024;
    const PB: usize = TB * 1024;

    if bytes < KB {
        format!("{bytes}B")
    } else if bytes < MB {
        format!("{:.1}KB", bytes as f64 / KB as f64)
    } else if bytes < GB {
        format!("{:.1}MB", bytes as f64 / MB as f64)
    } else if bytes < TB {
        format!("{:.1}GB", bytes as f64 / GB as f64)
    } else if bytes < PB {
        format!("{:.1}TB", bytes as f64 / TB as f64)
    } else {
        format!("{:.1}PB", bytes as f64 / PB as f64)
    }
}

/// Simplify Rust type names for better readability - Enhanced Unknown Type identification
pub fn simplify_type_name(type_name: &str) -> (String, String) {
    // Handle empty or explicitly unknown types first
    if type_name.is_empty() || type_name == "Unknown" {
        return ("Unknown Type".to_string(), "Unknown".to_string());
    }

    // Clean up the type name - remove extra whitespace and normalize
    let clean_type = type_name.trim();

    // Enhanced pattern matching with more comprehensive coverage
    if clean_type.contains("Vec<") || clean_type.contains("vec::Vec") {
        let inner = extract_generic_type(clean_type, "Vec");
        (format!("Vec<{inner}>"), "Collections".to_string())
    } else if clean_type.contains("HashMap") || clean_type.contains("hash_map") {
        ("HashMap<K,V>".to_string(), "Collections".to_string())
    } else if clean_type.contains("BTreeMap") || clean_type.contains("btree_map") {
        ("BTreeMap<K,V>".to_string(), "Collections".to_string())
    } else if clean_type.contains("BTreeSet") || clean_type.contains("btree_set") {
        ("BTreeSet<T>".to_string(), "Collections".to_string())
    } else if clean_type.contains("HashSet") || clean_type.contains("hash_set") {
        ("HashSet<T>".to_string(), "Collections".to_string())
    } else if clean_type.contains("VecDeque") || clean_type.contains("vec_deque") {
        ("VecDeque<T>".to_string(), "Collections".to_string())
    } else if clean_type.contains("Box<") || clean_type.contains("boxed::Box") {
        let inner = extract_generic_type(clean_type, "Box");
        if inner.contains("String") || inner.contains("string::String") {
            ("String".to_string(), "Basic Types".to_string())
        } else if inner.contains("HashMap") || inner.contains("hash_map") {
            ("HashMap<K,V>".to_string(), "Collections".to_string())
        } else if inner.contains("BTreeMap") || inner.contains("btree_map") {
            ("BTreeMap<K,V>".to_string(), "Collections".to_string())
        } else if inner.contains("BTreeSet") || inner.contains("btree_set") {
            ("BTreeSet<T>".to_string(), "Collections".to_string())
        } else if inner.contains("HashSet") || inner.contains("hash_set") {
            ("HashSet<T>".to_string(), "Collections".to_string())
        } else if inner.contains("VecDeque") || inner.contains("vec_deque") {
            ("VecDeque<T>".to_string(), "Collections".to_string())
        } else if inner.contains("Vec") || inner.contains("vec::Vec") {
            let vec_inner = extract_generic_type(&inner, "Vec");
            (format!("Vec<{vec_inner}>"), "Collections".to_string())
        } else {
            (format!("Box<{inner}>"), "Smart Pointers".to_string())
        }
    } else if clean_type.contains("Rc<") || clean_type.contains("rc::Rc") {
        let inner = extract_generic_type(clean_type, "Rc");
        if inner.contains("String") || inner.contains("string::String") {
            ("String".to_string(), "Basic Types".to_string())
        } else {
            (format!("Rc<{inner}>"), "Smart Pointers".to_string())
        }
    } else if clean_type.contains("Arc<") || clean_type.contains("sync::Arc") {
        let inner = extract_generic_type(clean_type, "Arc");
        if inner.contains("String") || inner.contains("string::String") {
            ("String".to_string(), "Basic Types".to_string())
        } else {
            (format!("Arc<{inner}>"), "Smart Pointers".to_string())
        }
    } else if clean_type.contains("String") || clean_type.contains("string::String") {
        ("String".to_string(), "Basic Types".to_string())
    } else if clean_type.contains("LinkedList") {
        ("LinkedList<T>".to_string(), "Collections".to_string())
    } else if clean_type.contains("&str") || clean_type == "str" {
        ("&str".to_string(), "Basic Types".to_string())
    } else if clean_type.contains("CString") || clean_type.contains("CStr") {
        ("CString".to_string(), "Basic Types".to_string())
    } else if clean_type.contains("OsString") || clean_type.contains("OsStr") {
        ("OsString".to_string(), "Basic Types".to_string())
    } else if clean_type.contains("PathBuf") || clean_type.contains("Path") {
        ("PathBuf".to_string(), "Basic Types".to_string())
    } else if clean_type.contains("Option<") {
        ("Option<T>".to_string(), "Optionals".to_string())
    } else if clean_type.contains("Result<") {
        ("Result<T,E>".to_string(), "Results".to_string())
    } else if clean_type.matches("i32").count() > 0
        || clean_type.matches("u32").count() > 0
        || clean_type.matches("i64").count() > 0
        || clean_type.matches("u64").count() > 0
        || clean_type.matches("f64").count() > 0
        || clean_type.matches("f32").count() > 0
        || clean_type.matches("i8").count() > 0
        || clean_type.matches("u8").count() > 0
        || clean_type.matches("i16").count() > 0
        || clean_type.matches("u16").count() > 0
        || clean_type.matches("isize").count() > 0
        || clean_type.matches("usize").count() > 0
        || clean_type.matches("bool").count() > 0
        || clean_type.matches("char").count() > 0
    {
        let primitive = clean_type.split("::").last().unwrap_or(clean_type);
        (primitive.to_string(), "Basic Types".to_string())
    } else if clean_type.contains("[") && clean_type.contains("]") {
        ("Array".to_string(), "Arrays".to_string())
    } else if clean_type.starts_with("(") && clean_type.ends_with(")") {
        ("Tuple".to_string(), "Tuples".to_string())
    } else if clean_type.contains("Mutex<") || clean_type.contains("RwLock<") {
        ("Mutex/RwLock".to_string(), "Synchronization".to_string())
    } else if clean_type.contains("Cell<") || clean_type.contains("RefCell<") {
        (
            "Cell/RefCell".to_string(),
            "Interior Mutability".to_string(),
        )
    } else if clean_type.contains("Weak<") {
        ("Weak<T>".to_string(), "Smart Pointers".to_string())
    } else if clean_type.starts_with("std::")
        || clean_type.starts_with("alloc::")
        || clean_type.starts_with("core::")
    {
        let simplified = clean_type.split("::").last().unwrap_or(clean_type);
        (simplified.to_string(), "Standard Library".to_string())
    } else if clean_type.contains("::") {
        // Handle custom types with namespaces
        let parts: Vec<&str> = clean_type.split("::").collect();
        if parts.len() >= 2 {
            // Use the original clean_type as fallback if parts is somehow empty
            let type_part = parts.last().unwrap_or(&clean_type);

            // Determine category based on namespace and type patterns
            let category = if parts
                .iter()
                .any(|&part| part.contains("error") || part.contains("Error"))
                || type_part.ends_with("Error")
                || type_part.contains("Err")
            {
                "Error Types"
            } else if type_part.ends_with("Config") || type_part.ends_with("Settings") {
                "Configuration"
            } else if type_part.ends_with("Builder") || type_part.ends_with("Factory") {
                "Builders"
            } else if parts
                .iter()
                .any(|&part| part == "std" || part == "core" || part == "alloc")
            {
                "Standard Library"
            } else if parts
                .iter()
                .any(|&part| part.contains("test") || part.contains("mock"))
            {
                "Test Types"
            } else if parts.len() > 2 {
                // Deep namespace suggests library or framework type
                "Library Types"
            } else {
                "Custom Types"
            };

            (type_part.to_string(), category.to_string())
        } else {
            // Single part, no namespace
            let category = if clean_type.ends_with("Error") || clean_type.contains("Err") {
                "Error Types"
            } else if clean_type.ends_with("Config") || clean_type.ends_with("Settings") {
                "Configuration"
            } else if clean_type.ends_with("Builder") || clean_type.ends_with("Factory") {
                "Builders"
            } else if clean_type.chars().next().is_some_and(|c| c.is_uppercase()) {
                // Starts with uppercase, likely a struct/enum
                "Custom Types"
            } else {
                // Lowercase, might be a function type or other
                "Other Types"
            };

            (clean_type.to_string(), category.to_string())
        }
    } else {
        // For simple type names without namespace
        if !clean_type.is_empty() {
            (clean_type.to_string(), "Custom Types".to_string())
        } else {
            ("Unknown Type".to_string(), "Unknown".to_string())
        }
    }
}

/// Extract generic type parameter for display
pub fn extract_generic_type(type_name: &str, container: &str) -> String {
    if let Some(start) = type_name.find(&format!("{container}<")) {
        let content_start = start + container.len() + 1;
        let content = &type_name[content_start..];

        let mut depth = 1;
        let mut end = 0;

        for (i, c) in content.char_indices() {
            match c {
                '<' => depth += 1,
                '>' => {
                    depth -= 1;
                    if depth == 0 {
                        end = i;
                        break;
                    }
                }
                _ => {}
            }
        }

        if end > 0 {
            let inner = &content[..end];
            return inner.split("::").last().unwrap_or(inner).to_string();
        }
    }
    "?".to_string()
}

/// Get a simplified type name for display
pub fn get_simple_type(type_name: &str) -> String {
    if type_name.contains("String") {
        "String".to_string()
    } else if type_name.contains("Vec") {
        "Vec".to_string()
    } else if type_name.contains("Box") {
        "Box".to_string()
    } else if type_name.contains("Rc") {
        "Rc".to_string()
    } else if type_name.contains("Arc") {
        "Arc".to_string()
    } else if type_name.contains("HashMap") {
        "HashMap".to_string()
    } else {
        type_name
            .split("::")
            .last()
            .unwrap_or("Unknown")
            .to_string()
    }
}

/// Get color for category - Enhanced with new categories
pub fn get_category_color(category: &str) -> String {
    match category {
        "Collections" => "#3498db".to_string(),               // Blue
        "Basic Types" => "#27ae60".to_string(),               // Green for Basic Types
        "Strings" => "#27ae60".to_string(),                   // Green (legacy support)
        "Text" => "#27ae60".to_string(),                      // Green (legacy support)
        "Smart Pointers" => "#e74c3c".to_string(),            // Red
        "Reference Counted" => "#f39c12".to_string(),         // Orange
        "Thread-Safe Shared" => "#9b59b6".to_string(),        // Purple
        "Primitives" => "#1abc9c".to_string(),                // Teal
        "Arrays" => "#34495e".to_string(),                    // Dark Gray
        "Tuples" => "#16a085".to_string(),                    // Dark Teal
        "Optionals" => "#8e44ad".to_string(),                 // Dark Purple
        "Results" => "#d35400".to_string(),                   // Dark Orange
        "Standard Library" => "#2980b9".to_string(),          // Dark Blue
        "Custom Types" => "#c0392b".to_string(),              // Dark Red
        "Synchronization" => "#e67e22".to_string(),           // Orange
        "Interior Mutability" => "#95a5a6".to_string(),       // Light Gray
        "Error Types" => "#e74c3c".to_string(),               // Red
        "Configuration" => "#3498db".to_string(),             // Blue
        "Builders" => "#9b59b6".to_string(),                  // Purple
        "Runtime/System Allocation" => "#bdc3c7".to_string(), // Light Gray for system allocations
        "Unknown" => "#bdc3c7".to_string(),                   // Light Gray (legacy support)
        _ => "#7f8c8d".to_string(),                           // Medium Gray for other unknowns
    }
}

/// Get type-specific gradient colors for enhanced visualization
pub fn get_type_gradient_colors(type_name: &str) -> (&'static str, &'static str) {
    match type_name {
        "String" => ("#00BCD4", "#00ACC1"),  // Teal gradient
        "Vec" => ("#2196F3", "#1976D2"),     // Blue gradient
        "Box" => ("#F44336", "#D32F2F"),     // Red gradient
        "HashMap" => ("#4CAF50", "#388E3C"), // Green gradient
        "Rc" => ("#FF9800", "#F57C00"),      // Orange gradient
        "Arc" => ("#9C27B0", "#7B1FA2"),     // Purple gradient
        _ => ("#607D8B", "#455A64"),         // Blue-gray gradient for custom types
    }
}

/// Get color based on type for consistent visualization
pub fn get_type_color(type_name: &str) -> &'static str {
    match type_name {
        "String" => "#2ecc71",
        "Vec" => "#3498db",
        "Box" => "#e74c3c",
        "HashMap" => "#f39c12",
        "Rc" => "#9b59b6",
        "Arc" => "#1abc9c",
        _ => "#95a5a6",
    }
}

/// Enhanced type hierarchy classification for treemap visualization
#[derive(Debug, Clone)]
pub struct TypeHierarchy {
    /// Major category: Collections, Strings, Smart Pointers, etc.
    pub major_category: String,
    /// Sub category: Maps, Sequences, Owned, Shared, etc.
    pub sub_category: String,
    /// Specific type: HashMap, Vec, Box, etc.
    pub specific_type: String,
    /// Full type name: HashMap<String, i32>
    pub full_type: String,
}

/// Get comprehensive type hierarchy for treemap visualization
pub fn get_type_category_hierarchy(type_name: &str) -> TypeHierarchy {
    // Handle empty or unknown types first
    if type_name.is_empty() || type_name == "Unknown" {
        return TypeHierarchy {
            major_category: "Unknown".to_string(),
            sub_category: "Unidentified".to_string(),
            specific_type: "Unknown Type".to_string(),
            full_type: type_name.to_string(),
        };
    }

    // Collections
    if type_name.contains("HashMap") || type_name.contains("hash::map") {
        let inner = extract_generic_params(type_name, "HashMap");
        TypeHierarchy {
            major_category: "Collections".to_string(),
            sub_category: "Maps".to_string(),
            specific_type: "HashMap".to_string(),
            full_type: if inner.is_empty() {
                "HashMap".to_string()
            } else {
                format!("HashMap<{inner}>")
            },
        }
    } else if type_name.contains("BTreeMap") || type_name.contains("btree::map") {
        let inner = extract_generic_params(type_name, "BTreeMap");
        TypeHierarchy {
            major_category: "Collections".to_string(),
            sub_category: "Maps".to_string(),
            specific_type: "BTreeMap".to_string(),
            full_type: if inner.is_empty() {
                "BTreeMap".to_string()
            } else {
                format!("BTreeMap<{inner}>")
            },
        }
    } else if type_name.contains("HashSet") || type_name.contains("hash::set") {
        let inner = extract_generic_params(type_name, "HashSet");
        TypeHierarchy {
            major_category: "Collections".to_string(),
            sub_category: "Sets".to_string(),
            specific_type: "HashSet".to_string(),
            full_type: if inner.is_empty() {
                "HashSet".to_string()
            } else {
                format!("HashSet<{inner}>")
            },
        }
    } else if type_name.contains("Vec") && !type_name.contains("VecDeque") {
        let inner = extract_generic_params(type_name, "Vec");
        TypeHierarchy {
            major_category: "Collections".to_string(),
            sub_category: "Sequences".to_string(),
            specific_type: "Vec".to_string(),
            full_type: if inner.is_empty() {
                "Vec".to_string()
            } else {
                format!("Vec<{inner}>")
            },
        }
    } else if type_name.contains("VecDeque") {
        let inner = extract_generic_params(type_name, "VecDeque");
        TypeHierarchy {
            major_category: "Collections".to_string(),
            sub_category: "Sequences".to_string(),
            specific_type: "VecDeque".to_string(),
            full_type: if inner.is_empty() {
                "VecDeque".to_string()
            } else {
                format!("VecDeque<{inner}>")
            },
        }
    }
    // Strings
    else if type_name.contains("String") && !type_name.contains("<") {
        TypeHierarchy {
            major_category: "Strings".to_string(),
            sub_category: "Owned".to_string(),
            specific_type: "String".to_string(),
            full_type: "String".to_string(),
        }
    } else if type_name.contains("&str") || (type_name.contains("str") && type_name.contains("&")) {
        TypeHierarchy {
            major_category: "Strings".to_string(),
            sub_category: "Borrowed".to_string(),
            specific_type: "&str".to_string(),
            full_type: "&str".to_string(),
        }
    }
    // Smart Pointers
    else if type_name.contains("Box<") {
        let inner = extract_generic_params(type_name, "Box");
        TypeHierarchy {
            major_category: "Smart Pointers".to_string(),
            sub_category: "Owned".to_string(),
            specific_type: "Box".to_string(),
            full_type: if inner.is_empty() {
                "Box".to_string()
            } else {
                format!("Box<{inner}>")
            },
        }
    } else if type_name.contains("Rc<") {
        let inner = extract_generic_params(type_name, "Rc");
        TypeHierarchy {
            major_category: "Smart Pointers".to_string(),
            sub_category: "Reference Counted".to_string(),
            specific_type: "Rc".to_string(),
            full_type: if inner.is_empty() {
                "Rc".to_string()
            } else {
                format!("Rc<{inner}>")
            },
        }
    } else if type_name.contains("Arc<") {
        let inner = extract_generic_params(type_name, "Arc");
        TypeHierarchy {
            major_category: "Smart Pointers".to_string(),
            sub_category: "Thread-Safe Shared".to_string(),
            specific_type: "Arc".to_string(),
            full_type: if inner.is_empty() {
                "Arc".to_string()
            } else {
                format!("Arc<{inner}>")
            },
        }
    }
    // Primitives
    else if is_primitive_type(type_name) {
        let clean_type = type_name.split("::").last().unwrap_or(type_name);
        let sub_cat = if clean_type.contains("i") || clean_type.contains("u") {
            "Integers"
        } else if clean_type.contains("f") {
            "Floats"
        } else if clean_type == "bool" {
            "Boolean"
        } else {
            "Other"
        };
        TypeHierarchy {
            major_category: "Primitives".to_string(),
            sub_category: sub_cat.to_string(),
            specific_type: clean_type.to_string(),
            full_type: clean_type.to_string(),
        }
    }
    // Fallback
    else {
        let simplified = type_name.split("::").last().unwrap_or(type_name);
        TypeHierarchy {
            major_category: "Custom Types".to_string(),
            sub_category: "User Defined".to_string(),
            specific_type: simplified.to_string(),
            full_type: simplified.to_string(),
        }
    }
}

/// Extract generic parameters from type names (enhanced version)
pub fn extract_generic_params(type_name: &str, container: &str) -> String {
    if let Some(start) = type_name.find(&format!("{container}<")) {
        let start = start + container.len() + 1;
        if let Some(end) = find_matching_bracket(type_name, start - 1) {
            let inner = &type_name[start..end];
            // Simplify the inner type
            return inner.split("::").last().unwrap_or(inner).to_string();
        }
    }
    String::new()
}

/// Find matching closing bracket for generic types
fn find_matching_bracket(s: &str, start: usize) -> Option<usize> {
    let chars: Vec<char> = s.chars().collect();
    if start >= chars.len() || chars[start] != '<' {
        return None;
    }

    let mut depth = 1;
    for (i, item) in chars.iter().enumerate().skip(start + 1) {
        match item {
            '<' => depth += 1,
            '>' => {
                depth -= 1;
                if depth == 0 {
                    return Some(i);
                }
            }
            _ => {}
        }
    }
    None
}

/// Check if a type is a primitive type
pub fn is_primitive_type(type_name: &str) -> bool {
    let clean_type = type_name.split("::").last().unwrap_or(type_name);
    matches!(
        clean_type,
        "i8" | "i16"
            | "i32"
            | "i64"
            | "i128"
            | "isize"
            | "u8"
            | "u16"
            | "u32"
            | "u64"
            | "u128"
            | "usize"
            | "f32"
            | "f64"
            | "bool"
            | "char"
    )
}

/// Extract array information for display
pub fn extract_array_info(type_name: &str) -> String {
    if let Some(start) = type_name.find('[') {
        if let Some(end) = type_name.find(']') {
            if end > start {
                return type_name[start..=end].to_string();
            }
        }
    }
    "Array".to_string()
}

/// Extract standard library module name
pub fn extract_std_module(type_name: &str) -> String {
    let parts: Vec<&str> = type_name.split("::").collect();
    if parts.len() >= 2 {
        match parts[1] {
            "collections" => "Collections".to_string(),
            "sync" => "Synchronization".to_string(),
            "thread" => "Threading".to_string(),
            "fs" => "File System".to_string(),
            "net" => "Networking".to_string(),
            "io" => "Input/Output".to_string(),
            _ => "Other".to_string(),
        }
    } else {
        "Other".to_string()
    }
}

// ============================================================================
// Thread Utilities (merged from thread_utils.rs)
// ============================================================================

use std::thread;
use std::time::Duration;

/// Extension trait for JoinHandle to add timeout functionality
pub trait JoinHandleExt<T> {
    /// Join with a timeout, returning an error if the timeout is exceeded
    ///
    /// This implementation properly handles timeout by using a dedicated timeout thread
    /// that will exit immediately, avoiding resource leaks. The original thread continues
    /// running in the background if it doesn't finish within the timeout.
    fn join_timeout(self, timeout: Duration) -> Result<T, Box<dyn std::any::Any + Send + 'static>>;
}

impl<T: Send + 'static> JoinHandleExt<T> for thread::JoinHandle<T> {
    fn join_timeout(self, timeout: Duration) -> Result<T, Box<dyn std::any::Any + Send + 'static>> {
        // If the thread is already finished, just join it
        if self.is_finished() {
            return self.join().map_err(|e| Box::new(e) as _);
        }

        // Use a channel to communicate result or timeout
        let (tx, rx) = std::sync::mpsc::channel();

        // Spawn a thread that will join the original thread and send the result
        thread::spawn(move || {
            let result = self.join();
            // Ignore send errors - the receiver might have been dropped due to timeout
            let _ = tx.send(result);
        });

        // Wait for either the thread to finish or timeout to occur
        match rx.recv_timeout(timeout) {
            Ok(result) => result.map_err(|e| Box::new(e) as _),
            Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {
                // Timeout occurred - the original thread continues running in background
                // This is unavoidable in Rust without thread cancellation
                Err(Box::new("Thread join timed out") as _)
            }
            Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
                // Sender disconnected unexpectedly
                Err(Box::new("Thread communication error") as _)
            }
        }
    }
}

#[cfg(test)]
mod tests;