-
Notifications
You must be signed in to change notification settings - Fork 0
/
StupidAlocator.hpp
60 lines (50 loc) · 1.15 KB
/
StupidAlocator.hpp
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
#pragma once
template <size_t SIZE>
struct StupidAllocator
{
static constexpr size_t ALLOC_SIZE = SIZE;
union Block
{
char data[SIZE];
Block* next;
};
Block* m_Next;
size_t m_Count;
StupidAllocator() : m_Next(), m_Count() {}
void fill()
{
const size_t COUNT = 16;
char *buf = new char[ALLOC_SIZE * COUNT];
for (size_t i = 0; i < COUNT; i++)
{
Block* b = reinterpret_cast<Block*>(&buf[i * SIZE]);
b->next = m_Next;
m_Next = b;
}
}
char* internal_alloc()
{
if (nullptr == m_Next)
fill();
char* r = m_Next->data;
m_Next = m_Next->next;
++m_Count;
return r;
}
void internal_free(char* aPtr)
{
Block* b = reinterpret_cast<Block*>(aPtr);
b->next = m_Next;
m_Next = b;
--m_Count;
}
static StupidAllocator& instance() { static StupidAllocator inst; return inst; }
static char* alloc()
{
return instance().internal_alloc();
}
static void free(char* aPtr)
{
instance().internal_free(aPtr);
}
};