sandbox
Loading...
Searching...
No Matches
monotonic_arena.hpp
1// SPDX-License-Identifier: MIT
2#ifndef LIBSBX_MEMORY_MONOTONIC_ARENA_HPP_
3#define LIBSBX_MEMORY_MONOTONIC_ARENA_HPP_
4
5namespace sbx::memory {
6
8
9public:
10
11 using pointer = std::uint8_t*;
12
13 monotonic_arena(pointer buffer, std::size_t size)
14 : _buffer{buffer},
15 _size{size},
16 _offset{0} { }
17
18 auto allocate(std::size_t count, std::size_t align) -> pointer {
19 const auto current = reinterpret_cast<std::size_t>(_buffer + _offset);
20 const auto aligned = (current + align - 1) & ~(align - 1);
21 const auto new_offset = aligned - reinterpret_cast<std::size_t>(_buffer) + count;
22
23 if (new_offset > _size) {
24 throw std::bad_alloc{};
25 }
26
27 _offset = new_offset;
28
29 return reinterpret_cast<std::uint8_t*>(aligned);
30 }
31
32private:
33
34 pointer _buffer;
35 std::size_t _size;
36 std::size_t _offset;
37
38}; // class monotonic_arena
39
40template<typename Type, std::size_t Size>
42
43 template<typename T, std::size_t S>
44 friend class monotonic_arena_allocator;
45
46public:
47
48 using value_type = Type;
49 using pointer = value_type*;
50
51 template<typename Other>
52 struct rebind {
54 }; // struct rebind
55
56 monotonic_arena_allocator(std::span<std::uint8_t, Size> buffer) noexcept
57 : _buffer{buffer},
58 _arena(_buffer.data(), _buffer.size()) { }
59
60 template<typename Other>
61 monotonic_arena_allocator(const monotonic_arena_allocator<Other, Size>& other) noexcept
62 : _buffer{other._buffer},
63 _arena(other._arena) {}
64
65 auto allocate(std::size_t count) -> pointer {
66 return static_cast<pointer>(_arena.allocate(sizeof(value_type) * count, alignof(value_type)));
67 }
68
69 auto deallocate(pointer, std::size_t) noexcept -> void {
70 // no-op (monotonic)
71 }
72
73private:
74
75 std::span<std::uint8_t, Size> _buffer;
76 monotonic_arena _arena;
77
78}; // class monotonic_arena_allocator
79
80template<typename Key, typename Value, std::size_t Size>
81using monotonic_arena_map_allocator = monotonic_arena_allocator<std::pair<const Key, Value>, Size>;
82
83} // namespace sbx::memory
84
85#endif // LIBSBX_MEMORY_MONOTONIC_ARENA_HPP_
Definition: monotonic_arena.hpp:41
Definition: monotonic_arena.hpp:7
Definition: monotonic_arena.hpp:52