Divide Framework 0.1
A free and open-source 3D Framework under heavy development
Loading...
Searching...
No Matches
StackAllocator.cpp
Go to the documentation of this file.
1
2/*
3 Author : Tobias Stein
4 Date : 22nd October, 2016
5 File : StackAllocator.cpp
6
7 Pool allocator.
8
9 All Rights Reserved. (c) Copyright 2016.
10*/
11
13
14namespace ECS { namespace Memory { namespace Allocator {
15
16 StackAllocator::StackAllocator(size_t memSize, const void* mem) :
17 IAllocator(memSize, mem)
18 {}
19
21 {
22 this->clear();
23 }
24
25 void* StackAllocator::allocate(size_t memSize, u8 alignment)
26 {
27 assert(memSize > 0 && "allocate called with memSize = 0.");
28
29 union
30 {
31 void* asVoidPtr;
32 uptr asUptr;
33 AllocMetaInfo* asMeta;
34 };
35
36 asVoidPtr = (void*)this->m_MemoryFirstAddress;
37
38 // current address
39 asUptr += this->m_MemoryUsed;
40
41 u8 adjustment = GetAdjustment(asVoidPtr, alignment, sizeof(AllocMetaInfo));
42
43 // check if there is enough memory available
44 if (this->m_MemoryUsed + memSize + adjustment > this->m_MemorySize)
45 {
46 // not enough memory
47 return nullptr;
48 }
49
50 // store alignment in allocation meta info
51 asMeta->adjustment = adjustment;
52
53 // determine aligned memory address
54 asUptr += adjustment;
55
56 // update book keeping
57 this->m_MemoryUsed += memSize + adjustment;
58 this->m_MemoryAllocations++;
59
60 // return aligned memory address
61 return asVoidPtr;
62 }
63
64 void StackAllocator::free(void* mem)
65 {
66 union
67 {
68 void* asVoidPtr;
69 uptr asUptr;
70 AllocMetaInfo* asMeta;
71 };
72
73 asVoidPtr = mem;
74
75 // get meta info
76 asUptr -= sizeof(AllocMetaInfo);
77
78 // free used memory
79 this->m_MemoryUsed -= ((uptr)this->m_MemoryFirstAddress + this->m_MemoryUsed) - ((uptr)mem + asMeta->adjustment);
80
81 // decrement allocation count
82 this->m_MemoryAllocations--;
83 }
84
86 {
87 // simply reset memory
88 this->m_MemoryUsed = 0;
89 this->m_MemoryAllocations = 0;
90 }
91
92} } } // namespace ECS::Memory::Allocator
virtual void free(void *p) override
StackAllocator(size_t memSize, const void *mem)
virtual void * allocate(size_t size, u8 alignment) 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