co_ecs 0.9.0
Cobalt ECS
Loading...
Searching...
No Matches
linear_allocator.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <cstddef>
4#include <memory>
5
7
8namespace co_ecs::detail {
9
14class linear_allocator {
15public:
19 explicit constexpr linear_allocator(void* ptr, std::size_t size) noexcept : _ptr(ptr), _head(ptr), _size(size) {
20 }
21
23 linear_allocator(const linear_allocator&) = delete;
24
26 linear_allocator& operator=(const linear_allocator&) = delete;
27
29 linear_allocator(linear_allocator&&) = default;
30
32 linear_allocator& operator=(linear_allocator&&) = default;
33
38 auto allocate(std::size_t size, std::size_t alignment = alignof(std::max_align_t)) noexcept -> void* {
39 assert(is_power_of_2(alignment) && "Alignment must be a power of two");
40
41 auto space_left = _size - (static_cast<char*>(_head) - static_cast<char*>(_ptr));
42 auto ptr = std::align(alignment, size, _head, space_left);
43 if (!ptr) {
44 return nullptr;
45 }
46 _head = static_cast<char*>(ptr) + size;
47 return ptr;
48 }
49
51 constexpr void reset() noexcept {
52 _head = _ptr;
53 }
54
55private:
56 void* _head;
57 void* _ptr;
58 std::size_t _size;
59};
60
61
62} // namespace co_ecs::detail
Definition component.hpp:17
constexpr auto is_power_of_2(auto value) -> bool
Check if value is a power of 2.
Definition bits.hpp:17