summaryrefslogtreecommitdiff
path: root/deimos/core/allocator.h
blob: 4acdb6d5a4d93f3a656ecdbb1b481aa3f4ae5897 (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#pragma once

#include "deimos/core/base.h"
#include "deimos/core/id_name.h"

namespace deimos
{

struct MemoryScope { uint32 id; };

class IAllocator
{
protected:
    const MemoryScope m_scope;

public:
    constexpr explicit IAllocator(MemoryScope scope) : m_scope{scope} {}

    deimos_NO_COPY_MOVE(IAllocator);

    virtual ~IAllocator() = default;

    [[nodiscard]]
    virtual void* Reallocate(
        void* old_ptr, int64 old_size, int64 new_size,
        const char* file = __builtin_FILE(), int32 line = __builtin_LINE()) = 0;

    [[nodiscard]]
    constexpr void* Allocate(
        int64 new_size,
        const char* file = __builtin_FILE(), int32 line = __builtin_LINE())
    {
        return Reallocate(nullptr, 0, new_size, file, line);
    }

    constexpr void Free(
        void* old_ptr, int64 old_size,
        const char* file = __builtin_FILE(), int32 line = __builtin_LINE())
    {
        (void)Reallocate(old_ptr, old_size, 0, file, line);
    }

    template<typename T, typename... Args>
    T* New(
        Args&&... args,
        const char* file = __builtin_FILE(), int32 line = __builtin_LINE())
    {
        void* ptr = Allocate(sizeof(T), file, line);
        return new(ptr) T(std::forward<Args>(args)...);
    }

    template<typename T>
    void Delete(
        T* t,
        const char* file = __builtin_FILE(), int32 line = __builtin_LINE())
    {
        if constexpr (!kIsTriviallyDestructible<T>)
        {
            t->~T();
        }
        Free(t, sizeof(T), file, line);
    }
};

class AllocatorApi
{
public:
    static constexpr IdName kApiName{"deimos::AllocatorApi"};

    IAllocator* system{};
};

} // namespace deimos