Skip to main content

gc/
malloc.rs

1/// Default GC trigger threshold, matching QuickJS `JS_NewRuntime2`.
2pub const DEFAULT_GC_THRESHOLD: usize = 256 * 1024;
3
4/// Per-allocation accounting overhead, matching QuickJS `MALLOC_OVERHEAD` on non-Apple platforms.
5pub const MALLOC_OVERHEAD: usize = 8;
6
7/// Tracked heap usage, matching QuickJS `JSMallocState`.
8#[derive(Debug, Clone, Default)]
9pub struct MallocState {
10    pub malloc_count: usize,
11    pub malloc_size: usize,
12    pub malloc_limit: usize,
13}
14
15impl MallocState {
16    pub fn new() -> Self {
17        Self::default()
18    }
19
20    pub fn set_limit(&mut self, limit: usize) {
21        self.malloc_limit = limit;
22    }
23
24    pub fn would_exceed(&self, size: usize) -> bool {
25        if self.malloc_limit == 0 {
26            return false;
27        }
28        self.malloc_size.saturating_add(size) > self.malloc_limit.saturating_sub(1)
29    }
30
31    pub fn record_alloc(&mut self, usable_size: usize) {
32        self.malloc_count += 1;
33        self.malloc_size += usable_size + MALLOC_OVERHEAD;
34    }
35
36    pub fn record_free(&mut self, usable_size: usize) {
37        self.malloc_count = self.malloc_count.saturating_sub(1);
38        self.malloc_size = self
39            .malloc_size
40            .saturating_sub(usable_size + MALLOC_OVERHEAD);
41    }
42}