1use serde::{Deserialize, Serialize};
2use std::fmt;
3
4#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
5pub struct HeapStats {
6 pub total_entries: usize,
7 pub object_count: usize,
8 pub array_count: usize,
9 pub function_count: usize,
10 pub string_count: usize,
11 pub memory_usage: usize,
12 pub fragmentation: f64,
13}
14
15impl HeapStats {
16 pub fn new() -> Self {
17 Self {
18 total_entries: 0,
19 object_count: 0,
20 array_count: 0,
21 function_count: 0,
22 string_count: 0,
23 memory_usage: 0,
24 fragmentation: 0.0,
25 }
26 }
27
28 pub fn update_counts(&mut self, object_count: usize, array_count: usize, function_count: usize, string_count: usize) {
29 self.object_count = object_count;
30 self.array_count = array_count;
31 self.function_count = function_count;
32 self.string_count = string_count;
33 self.total_entries = object_count + array_count + function_count + string_count;
34 }
35
36 pub fn set_memory_usage(&mut self, usage: usize) {
37 self.memory_usage = usage;
38 }
39
40 pub fn set_fragmentation(&mut self, fragmentation: f64) {
41 self.fragmentation = fragmentation;
42 }
43
44 pub fn get_efficiency(&self) -> f64 {
45 if self.total_entries == 0 {
46 1.0
47 } else {
48 (self.memory_usage as f64) / (self.total_entries as f64)
49 }
50 }
51}
52
53impl Default for HeapStats {
54 fn default() -> Self {
55 Self::new()
56 }
57}
58
59impl fmt::Display for HeapStats {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 write!(
62 f,
63 "HeapStats {{ total: {}, objects: {}, arrays: {}, functions: {}, strings: {}, memory: {} bytes, fragmentation: {:.2}% }}",
64 self.total_entries,
65 self.object_count,
66 self.array_count,
67 self.function_count,
68 self.string_count,
69 self.memory_usage,
70 self.fragmentation * 100.0
71 )
72 }
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
76pub struct HeapMetrics {
77 pub allocation_count: usize,
78 pub deallocation_count: usize,
79 pub gc_cycles: usize,
80 pub last_gc_duration: std::time::Duration,
81}
82
83impl HeapMetrics {
84 pub fn new() -> Self {
85 Self {
86 allocation_count: 0,
87 deallocation_count: 0,
88 gc_cycles: 0,
89 last_gc_duration: std::time::Duration::ZERO,
90 }
91 }
92
93 pub fn record_allocation(&mut self) {
94 self.allocation_count += 1;
95 }
96
97 pub fn record_deallocation(&mut self) {
98 self.deallocation_count += 1;
99 }
100
101 pub fn record_gc_cycle(&mut self, duration: std::time::Duration) {
102 self.gc_cycles += 1;
103 self.last_gc_duration = duration;
104 }
105
106 pub fn get_allocation_rate(&self) -> f64 {
107 if self.gc_cycles == 0 {
108 0.0
109 } else {
110 self.allocation_count as f64 / self.gc_cycles as f64
111 }
112 }
113}
114
115impl Default for HeapMetrics {
116 fn default() -> Self {
117 Self::new()
118 }
119}