Aeon Engine c550894
AeonGames Open Source Game Engine
Loading...
Searching...
No Matches
MemoryPool.cpp
1/*
2Copyright (C) 2019,2025 Rodrigo Jose Hernandez Cordoba
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16#include "aeongames/MemoryPool.hpp"
17namespace AeonGames
18{
19 MemoryPool::MemoryPool ( size_t aBlockSize, size_t aNumOfBlocks ) :
20 mBlockSize{aBlockSize},
21 mNumOfBlocks{aNumOfBlocks},
22 mNumOfFreeBlocks{aNumOfBlocks},
23 mNumOfInitializedBlocks{0},
24 mMemory ( static_cast<std::vector<uint8_t>::size_type> ( mBlockSize * mNumOfBlocks ) ),
25 mNext{mMemory.data() }
26 {
27 }
28
29 uint8_t * MemoryPool::AddrFromIndex ( size_t i ) const
30 {
31 return const_cast<uint8_t *> ( mMemory.data() ) + ( i * mBlockSize );
32 }
33
34 size_t MemoryPool::IndexFromAddr ( const uint8_t* p ) const
35 {
36 return ( ( ( size_t ) ( p - mMemory.data() ) ) / mBlockSize );
37 }
38
40 {
41 if ( mNumOfInitializedBlocks < mNumOfBlocks )
42 {
43 size_t* p = ( size_t* ) AddrFromIndex ( mNumOfInitializedBlocks );
44 *p = mNumOfInitializedBlocks + 1;
45 mNumOfInitializedBlocks++;
46 }
47 void* ret = nullptr;
48 if ( mNumOfFreeBlocks > 0 )
49 {
50 ret = ( void* ) mNext;
51 --mNumOfFreeBlocks;
52 if ( mNumOfFreeBlocks != 0 )
53 {
54 mNext = AddrFromIndex ( * ( ( size_t* ) mNext ) );
55 }
56 else
57 {
58 mNext = nullptr;
59 }
60 }
61 return ret;
62 }
63
64 void MemoryPool::DeAllocate ( void* p )
65 {
66 if ( mNext != nullptr )
67 {
68 ( * ( size_t* ) p ) = IndexFromAddr ( mNext );
69 mNext = ( uint8_t* ) p;
70 }
71 else
72 {
73 * ( ( size_t* ) p ) = mNumOfBlocks;
74 mNext = ( uint8_t* ) p;
75 }
76 ++mNumOfFreeBlocks;
77 }
78}
DLL void * Allocate()
Allocate a block from the pool.
DLL MemoryPool(size_t sizeOfEachBlock, size_t numOfBlocks)
Construct a memory pool.
DLL void DeAllocate(void *p)
Return a block to the pool.
<- This is here just for the literals
Definition AABB.hpp:31
STL namespace.