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
/// Partial clone of rust-gc's mark and sweep implementation

use core::fmt;
use core::mem;
use core::ptr::{self, NonNull};
use core::cell::{Cell, RefCell};
use log;

mod data;
mod handle;

pub use data::GcTrace;
pub use handle::Gc;

use data::{GcBox, GcBoxHeader};


thread_local! {
    static GC_STATE: RefCell<GcState> = RefCell::new(GcState::default());
}

pub fn gc_collect(root: &impl GcTrace) {
    GC_STATE.with(|gc| {
        let mut gc = gc.borrow_mut();
        if gc.should_collect() {
            gc.collect_garbage(root)
        }
    })
}

pub fn gc_force(root: &impl GcTrace) {
    GC_STATE.with(|gc| {
        let mut gc = gc.borrow_mut();
        gc.collect_garbage(root)
    })
}

struct GcState {
    stats: GcStats,
    config: GcConfig,
    threshold: usize,
    boxes_start: Option<NonNull<GcBoxHeader>>,
}

#[derive(Debug)]
struct GcStats {
    allocated: usize,
    box_count: usize,
    cycle_count: usize,
}

struct GcConfig {
    threshold: u16,
    pause_factor: u16,  // percent memory use relative to last cycle before starting a new cycle
}

impl Default for GcConfig {
    fn default() -> Self {
        Self {
            threshold: 512, // Small because of stop-the-world. If we go incremental increase this to 8 kiB
            pause_factor: 160,
        }
    }
}

impl Default for GcState {
    fn default() -> Self {
        GcState::new(GcConfig::default())
    }
}

impl GcState {
    fn new(config: GcConfig) -> Self {
        let threshold = config.threshold as usize;
        
        Self {
            config,
            threshold,
            
            stats: GcStats {
                allocated: 0,
                box_count: 0,
                cycle_count: 0,
            },
            
            boxes_start: None,
        }
    }
    
    #[inline]
    fn should_collect(&self) -> bool {
        self.stats.allocated > self.threshold
    }
    
    fn insert(&mut self, mut gcbox: NonNull<GcBoxHeader>) {
        unsafe {
            let size = gcbox.as_ref().size();
            log::debug!("{:#X} allocate {} bytes", gcbox.as_ptr() as *const () as usize, size);
            
            gcbox.as_mut().set_next(self.boxes_start.take());
            self.boxes_start = Some(gcbox);
            self.stats.allocated += size;
            self.stats.box_count += 1;
        }
    }
    
    /// frees the GcBox, yielding it's next pointer
    fn free(&mut self, gcbox: NonNull<GcBoxHeader>) -> Option<NonNull<GcBoxHeader>> {
        let size = unsafe { gcbox.as_ref().size() };
        self.stats.allocated -= size;
        self.stats.box_count -= 1;
        log::debug!("{:#X} free {} bytes", gcbox.as_ptr() as *const () as usize, size);
        
        unsafe { GcBoxHeader::free(gcbox) }
    }
    
    fn collect_garbage(&mut self, root: &impl GcTrace) {
        log::debug!("Gc cycle begin ---");
        
        let allocated = self.stats.allocated;
        let box_count = self.stats.box_count;
        log::debug!("{}", self.stats);
        
        // mark
        root.trace();
        
        // sweep
        unsafe { self.sweep(); }
        self.stats.cycle_count = self.stats.cycle_count.wrapping_add(1);
        
        let freed = allocated - self.stats.allocated;
        let dropped = box_count - self.stats.box_count;
        log::debug!("Freed {} bytes ({} allocations)", freed, dropped);
        log::debug!("{}", self.stats);
        
        self.threshold = (self.stats.allocated * self.config.pause_factor as usize) / 100;
        log::debug!("Next collection at {} bytes", self.threshold);
        
        log::debug!("Gc cycle end ---");
    }
    
    unsafe fn sweep(&mut self) {
        let _guard = DropGuard::new();
        
        //boxes_start: Option<NonNull<GcBox<dyn GcTrace>>>,
        let mut prev_box = None;
        let mut next_box = self.boxes_start;
        while let Some(mut gcbox) = next_box {
            if gcbox.as_ref().is_marked() {
                gcbox.as_mut().set_marked(false);
                
                next_box = gcbox.as_ref().next();
                prev_box.replace(gcbox);
                
            } else {
                
                next_box = self.free(gcbox);
                if let Some(mut prev_box) = prev_box {
                    prev_box.as_mut().set_next(next_box);
                } else {
                    self.boxes_start = next_box;
                }
                
            }
        }
    }
}

impl Drop for GcState {
    fn drop(&mut self) {
        // unimplemented!()
    }
}


// Whether or not the thread is currently in the sweep phase of garbage collection.
thread_local!(pub static GC_SWEEP: Cell<bool> = Cell::new(false));

struct DropGuard;

impl DropGuard {
    fn new() -> DropGuard {
        GC_SWEEP.with(|flag| flag.set(true));
        DropGuard
    }
}

impl Drop for DropGuard {
    fn drop(&mut self) {
        GC_SWEEP.with(|flag| flag.set(false));
    }
}

fn deref_safe() -> bool {
    GC_SWEEP.with(|flag| !flag.get())
}


impl fmt::Display for GcStats {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            fmt, "Cycle {}: estimated usage {}u ({} allocations)", 
            self.cycle_count, self.allocated, self.box_count
        )
    }
}