Website Summary Files Commits Branches @commit @diff @stats
path: root / gctest / src / gc_dummy.cpp
blob: 68fc86d1ef938fedf4b9b1847ddb033b1cd1db81 (plain) (blame)
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
#include <memory>

#include "gc.h"

class DummyGC : public GarbageCollector
{
public:
    DummyGC(unsigned gcInterval)
        : m_GCInterval(gcInterval)
    {}

    void* Allocate(size_t size) override {
        if (++m_AllocsSinceGC == m_GCInterval)
        {
            GC();
            m_AllocsSinceGC = 0;
        }
        auto memory = ::operator new(size);
        m_Allocated.insert(static_cast<Object*>(memory));
        return memory;
    }

    void SetRoot(Object** root) override { m_Root = root; }

    void VisitReference(Object*, Object** to, void*) override
    {
        auto insert = m_Visited.insert(*to);
        if (insert.second)
        {
            (*to)->VisitReferences(this, nullptr);
        }
    }

    void GC()
    {
        m_Visited.clear();
        m_Visited.insert(*m_Root);
        (*m_Root)->VisitReferences(this, nullptr);

        for (auto object: m_Allocated)
        {
            if (m_Visited.find(object) == m_Visited.end())
            {
                object->~Object();
                ::operator delete(object);
            }
        }
        m_Allocated = m_Visited;
    }

    void Shutdown() override
    {
        for (auto object: m_Allocated)
        {
            object->~Object();
            ::operator delete(object);
        }

    }

    Object** m_Root;
    std::unordered_set<Object*> m_Allocated;
    std::unordered_set<Object*> m_Visited;
    unsigned m_GCInterval;
    unsigned m_AllocsSinceGC = 0;
};

std::unique_ptr<GarbageCollector> CreateGarbageCollector(int, char*[])
{
    return std::unique_ptr<GarbageCollector>(new DummyGC(1024));
}