Divide Framework 0.1
A free and open-source 3D Framework under heavy development
Loading...
Searching...
No Matches
PoolAllocator.cpp
Go to the documentation of this file.
1
2/*
3 Author : Tobias Stein
4 Date : 22nd October, 2016
5 File : PoolAllocator.cpp
6
7 Pool allocator.
8
9 All Rights Reserved. (c) Copyright 2016.
10*/
11
13
14namespace ECS { namespace Memory { namespace Allocator {
15
16 PoolAllocator::PoolAllocator(size_t memSize, const void* mem, size_t objectSize, u8 objectAlignment) :
17 IAllocator(memSize, mem),
18 OBJECT_SIZE(objectSize),
19 OBJECT_ALIGNMENT(objectAlignment)
20 {
21 this->clear();
22 }
23
25 {
26 this->freeList = nullptr;
27 }
28
29
30 void* PoolAllocator::allocate(size_t memSize, u8 alignment)
31 {
32 assert(memSize > 0 && "allocate called with memSize = 0.");
33 assert(memSize == this->OBJECT_SIZE && alignment == this->OBJECT_ALIGNMENT);
34
35 if (this->freeList == nullptr)
36 return nullptr;
37
38 // get free slot
39 void* p = this->freeList;
40
41 // point to next free slot
42 this->freeList = (void**)(*this->freeList);
43
44 this->m_MemoryUsed += this->OBJECT_SIZE;
45 this->m_MemoryAllocations++;
46
47 return p;
48 }
49
50
51 void PoolAllocator::free(void* mem)
52 {
53 // put this slot back to free list
54 *((void**)mem) = this->freeList;
55
56 this->freeList = (void**)mem;
57
58 this->m_MemoryUsed -= this->OBJECT_SIZE;
59 this->m_MemoryAllocations--;
60 }
61
62
64 {
65 u8 adjustment = GetAdjustment(this->m_MemoryFirstAddress, this->OBJECT_ALIGNMENT);
66
67 size_t numObjects = (size_t)floor((this->m_MemorySize - adjustment) / this->OBJECT_SIZE);
68
69 union
70 {
71 void* asVoidPtr;
72 uptr asUptr;
73 };
74
75 asVoidPtr = (void*)this->m_MemoryFirstAddress;
76
77 // align start address
78 asUptr += adjustment;
79
80 this->freeList = (void**)asVoidPtr;
81
82 void** p = this->freeList;
83
84 for (size_t i = 0; i < (numObjects - 1); ++i)
85 {
86 *p = (void*)((uptr)p + this->OBJECT_SIZE);
87
88 p = (void**)*p;
89 }
90
91 *p = nullptr;
92 }
93
94}}} // namespace ECS::Memory::Allocator
PoolAllocator(size_t memSize, const void *mem, size_t objectSize, u8 objectAlignment)
virtual void * allocate(size_t size, u8 alignment) override
virtual void free(void *p) override
static u8 GetAdjustment(const void *address, u8 alignment)
Definition: IAllocator.h:27
uintptr_t uptr
Definition: Platform.h:64
uint8_t u8
Definition: Platform.h:49