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
use std::marker::PhantomData;

use crate::{
    immix::{
        errors::ImmixError,
        ptr::{RawPtr, TypedPtr},
        Immix,
    },
    object::{environment::Environment, Object},
};

#[derive(Debug)]
pub struct Heap {
    obj_immix: Immix<usize, Object>,
    // env_immix: Immix<usize, Environment<String>>,
    count: usize,
}

impl Heap {
    pub fn new() -> Self {
        Self {
            count: 0,
            obj_immix: Immix::new(),
        }
    }

    /// allocate object into heap
    pub fn enlist(
        &mut self,
        env: &mut Environment<String>,
        id: String,
        obj: Object,
    ) -> Result<RawPtr<Object>, ImmixError> {
        let ptr = self.obj_immix.alloc(self.count, obj)?;
        self.count += 1;
        let typed: TypedPtr<Object> = TypedPtr {
            ptr,
            tag: PhantomData,
        };

        env.set(id, typed.clone());

        Ok(RawPtr::new(typed.ptr.data as *const Object))
    }

    pub fn get(env: &mut Environment<String>, key: String) -> Option<TypedPtr<Object>> {
        env.get_clone(&key)
    }

    /// mark and sweep
    pub fn run_gc(&mut self, env: &mut Environment<String>) {
        self.obj_immix.unmark_all();

        // mark all reachables
        env.mark_all();

        // manage memory
        self.obj_immix.sweep()
    }
}