aboutsummaryrefslogtreecommitdiff
path: root/src/common/Arena.hpp
blob: b5e1eb71d03bd8ead19c15f9f59aeaab70159171 (plain)
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
#pragma once

#include <cstddef>
#include <cstdint>
#include <cassert>

#include <vector>


class Arena {
public:
    Arena(size_t size) : buffer(size)
    {
    }

    template<typename T>
    size_t
    Align() const
    {
        size_t alignment = alignof(T);
        return (offset + alignment - 1) & ~(alignment - 1);
    }

    template<typename T, typename... Args>
    T&
    Allocate(Args&&... args)
    {
        offset = Align<T>();
        assert(offset + sizeof(T) <= buffer.size() && "Arena out of memory");

        T* ptr = new (&buffer[offset]) T(std::forward<Args>(args)...);
        objects.emplace_back(ptr, [](void* p) { static_cast<T*>(p)->~T(); });

        offset += sizeof(T);
        return *ptr;
    }

    void
    Reset()
    {
        for (auto& [ptr, dtor] : objects) {
            dtor(ptr);
        }
        objects.clear();
        offset = 0;
    }


    size_t offset = 0;
    std::vector<uint8_t> buffer;
    std::vector<std::pair<void*, void (*)(void*)>> objects;
};