-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPoolAllocator.hpp
More file actions
97 lines (78 loc) · 2.67 KB
/
PoolAllocator.hpp
File metadata and controls
97 lines (78 loc) · 2.67 KB
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#pragma once
#include "Allocator.hpp"
#include "../core/Assertions.hpp"
namespace Caffeine {
class PoolAllocator final : public IAllocator {
public:
PoolAllocator(void* buffer, usize poolSize, usize slotSize, usize alignment = 8)
: m_poolStart(static_cast<u8*>(buffer))
, m_poolSize(poolSize)
, m_slotSize(slotSize)
, m_alignment(alignment)
{
CF_ASSERT(alignment >= 8, "Alignment must be at least 8");
CF_ASSERT((alignment & (alignment - 1)) == 0, "Alignment must be power of 2");
m_maxSlots = poolSize / slotSize;
initializeFreeList();
}
explicit PoolAllocator(usize poolSize, usize slotSize, usize alignment = 8)
: PoolAllocator(new u8[poolSize], poolSize, slotSize, alignment)
{
m_ownsBuffer = true;
}
~PoolAllocator() override {
if (m_ownsBuffer) {
delete[] m_poolStart;
}
}
void* alloc(usize size, usize alignment = 8) override {
(void)size;
(void)alignment;
CF_ASSERT(size <= m_slotSize, "Requested size exceeds slot size");
if (!m_freeList) {
return nullptr;
}
void* ptr = m_freeList;
m_freeList = *reinterpret_cast<u8**>(ptr);
++m_usedCount;
if (m_usedCount > m_peakSlots) m_peakSlots = m_usedCount;
return ptr;
}
void free(void* ptr) override {
if (!ptr) return;
*reinterpret_cast<u8**>(ptr) = m_freeList;
m_freeList = static_cast<u8*>(ptr);
--m_usedCount;
}
void reset() override {
initializeFreeList();
m_usedCount = 0;
}
usize usedMemory() const override { return m_usedCount * m_slotSize; }
usize totalSize() const override { return m_poolSize; }
usize peakMemory() const override { return m_peakSlots * m_slotSize; }
usize allocationCount() const override { return m_usedCount; }
const char* name() const override { return "Pool"; }
usize freeSlots() const { return m_maxSlots - m_usedCount; }
usize slotSize() const { return m_slotSize; }
usize maxSlots() const { return m_maxSlots; }
private:
void initializeFreeList() {
m_freeList = nullptr;
for (usize i = 0; i < m_maxSlots; ++i) {
u8* slot = m_poolStart + (i * m_slotSize);
*reinterpret_cast<u8**>(slot) = m_freeList;
m_freeList = slot;
}
}
u8* m_freeList = nullptr;
u8* m_poolStart = nullptr;
usize m_poolSize = 0;
usize m_slotSize = 0;
usize m_alignment = 8;
usize m_maxSlots = 0;
usize m_usedCount = 0;
usize m_peakSlots = 0;
bool m_ownsBuffer = false;
};
} // namespace Caffeine