summaryrefslogtreecommitdiff
path: root/asl/memory/allocator.hpp
blob: a231558bd47364b19c5df7416100c2786b01069a (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
// Copyright 2025 Steven Le Rouzic
//
// SPDX-License-Identifier: BSD-3-Clause

#pragma once

#include "asl/base/meta.hpp"
#include "asl/memory/layout.hpp"
#include "asl/memory/memory.hpp"

namespace asl
{

template<typename T>
concept allocator = moveable<T> && equality_comparable<T> &&
    requires(T& alloc, layout layout, void* ptr)
    {
        { alloc.alloc(layout) } -> same_as<void*>;
        { alloc.realloc(ptr, layout, layout) } -> same_as<void*>;
        alloc.dealloc(ptr, layout);
    };

class GlobalHeap
{
public:
    static void* alloc(const layout&);
    static void* realloc(void* ptr, const layout& old, const layout& new_layout);
    static void dealloc(void* ptr, const layout&);

    constexpr bool operator==(const GlobalHeap&) const { return true; }
};
static_assert(allocator<GlobalHeap>);

using DefaultAllocator = GlobalHeap;

template<typename T>
T* alloc_new(allocator auto& a, auto&&... args)
{
    void* ptr = a.alloc(layout::of<T>());
    return construct_at<T>(ptr, std::forward<decltype(args)>(args)...);
}

template<typename T>
void alloc_delete(allocator auto& a, T* ptr)
{
    destroy(ptr);
    a.dealloc(ptr, layout::of<T>());
}

template<typename T>
constexpr T* alloc_new_default(auto&&... args)
{
    DefaultAllocator allocator{};
    return alloc_new<T>(allocator, std::forward<decltype(args)>(args)...);
}

template<typename T>
void alloc_delete_default(T* ptr)
{
    DefaultAllocator allocator{};
    alloc_delete(allocator, ptr);
}

} // namespace asl