AI 24/25 Project Software
Documentation for the AI 24/25 course programming project software
Loading...
Searching...
No Matches
segmented_memory_pool.h
1#pragma once
2
3#include <cassert>
4#include <memory>
5#include <vector>
6
7namespace probfd::storage {
8
9template <std::size_t SEGMENT_SIZE = 16384>
10class SegmentedMemoryPool {
11 std::size_t space_left_ = 0;
12 void* current_ = nullptr;
13 std::vector<void*> segments_;
14
15public:
16 SegmentedMemoryPool() = default;
17
18 ~SegmentedMemoryPool()
19 {
20 for (void* segment : segments_) {
21 delete[] (reinterpret_cast<char*>(segment));
22 }
23 }
24
25 template <typename T>
26 T* allocate(const std::size_t elements)
27 {
28 const std::size_t size = elements * sizeof(T);
29
30 assert(size <= SEGMENT_SIZE);
31
32 if (!std::align(alignof(T), size, current_, space_left_)) {
33 space_left_ = SEGMENT_SIZE;
34 current_ = ::operator new[](SEGMENT_SIZE);
35 segments_.push_back(current_);
36 }
37
38 T* res = reinterpret_cast<T*>(current_);
39 current_ = reinterpret_cast<char*>(current_) + size;
40 space_left_ -= size;
41 return res;
42 }
43
44 [[nodiscard]]
45 std::size_t size_in_bytes() const
46 {
47 return segments_.size() * SEGMENT_SIZE;
48 }
49};
50
51} // namespace probfd::storage
This namespace contains commonly used storage and container types.
Definition per_state_storage.h:16