1 /* This file is part of the Spring engine (GPL v2 or later), see LICENSE.html */
2 
3 #include "System/MemPool.h"
4 //#include "System/mmgr.h"
5 
6 CMemPool mempool;
7 
CMemPool()8 CMemPool::CMemPool()
9 {
10 	for (size_t a = 0; a < (MAX_MEM_SIZE + 1); a++) {
11 		nextFree[a] = NULL;
12 		poolSize[a] = 10;
13 	}
14 }
15 
Alloc(size_t numBytes)16 void* CMemPool::Alloc(size_t numBytes)
17 {
18 	if (UseExternalMemory(numBytes)) {
19 		return ::operator new(numBytes);
20 	} else {
21 		void* pnt = nextFree[numBytes];
22 
23 		if (pnt) {
24 			nextFree[numBytes] = (*(void**)pnt);
25 		} else {
26 			void* newBlock = ::operator new(numBytes * poolSize[numBytes]);
27 			allocated.push_back(newBlock);
28 			for (int i = 0; i < (poolSize[numBytes] - 1); ++i) {
29 				*(void**)&((char*)newBlock)[(i) * numBytes] = (void*)&((char*)newBlock)[(i + 1) * numBytes];
30 			}
31 
32 			*(void**)&((char*)newBlock)[(poolSize[numBytes] - 1) * numBytes] = 0;
33 
34 			pnt = newBlock;
35 			nextFree[numBytes] = (*(void**)pnt);
36 			poolSize[numBytes] *= 2;
37 		}
38 		return pnt;
39 	}
40 }
41 
Free(void * pnt,size_t numBytes)42 void CMemPool::Free(void* pnt, size_t numBytes)
43 {
44 	if (pnt == NULL) {
45 		return;
46 	}
47 
48 	if (UseExternalMemory(numBytes)) {
49 		::operator delete(pnt);
50 	} else {
51 		*(void**)pnt = nextFree[numBytes];
52 		nextFree[numBytes] = pnt;
53 	}
54 }
55 
~CMemPool()56 CMemPool::~CMemPool()
57 {
58 	for(std::vector<void *>::iterator i = allocated.begin(); i != allocated.end(); ++i)
59 		::operator delete(*i);
60 }
61