1 /* ScummVM - Graphic Adventure Engine
3 * ScummVM is the legal property of its developers, whose names
4 * are too numerous to list here. Please refer to the COPYRIGHT
5 * file distributed with this source distribution.
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 #ifndef COMMON_MEMORYPOOL_H
27 #define COMMON_MEMORYPOOL_H
29 #include "common/scummsys.h"
30 #include "common/array.h"
37 MemoryPool(const MemoryPool
&);
38 MemoryPool
& operator=(const MemoryPool
&);
48 size_t _chunksPerPage
;
51 void addPageToPool(const Page
&page
);
52 bool isPointerInPage(void *ptr
, const Page
&page
);
55 MemoryPool(size_t chunkSize
);
59 void freeChunk(void *ptr
);
61 void freeUnusedPages();
63 size_t getChunkSize() const { return _chunkSize
; }
66 template<size_t CHUNK_SIZE
, size_t NUM_INTERNAL_CHUNKS
= 32>
67 class FixedSizeMemoryPool
: public MemoryPool
{
70 REAL_CHUNK_SIZE
= (CHUNK_SIZE
+ sizeof(void*) - 1) & (~(sizeof(void*) - 1))
73 byte _storage
[NUM_INTERNAL_CHUNKS
* REAL_CHUNK_SIZE
];
75 FixedSizeMemoryPool() : MemoryPool(CHUNK_SIZE
) {
76 assert(REAL_CHUNK_SIZE
== _chunkSize
);
77 // Insert some static storage
78 Page internalPage
= { _storage
, NUM_INTERNAL_CHUNKS
};
79 addPageToPool(internalPage
);
83 template<size_t CHUNK_SIZE
>
84 class FixedSizeMemoryPool
<CHUNK_SIZE
,0> : public MemoryPool
{
86 FixedSizeMemoryPool() : MemoryPool(CHUNK_SIZE
) {}
90 template<class T
, size_t NUM_INTERNAL_CHUNKS
= 32>
91 class ObjectPool
: public FixedSizeMemoryPool
<sizeof(T
), NUM_INTERNAL_CHUNKS
> {
93 void deleteChunk(T
*ptr
) {
99 } // End of namespace Common
101 // Provide a custom placement new operator, using an arbitrary
104 // This *should* work with all C++ implementations, but may not.
106 // For details on using placement new for custom allocators, see e.g.
107 // <http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.14>
109 inline void* operator new(size_t nbytes
, Common::MemoryPool
& pool
) {
110 assert(nbytes
<= pool
.getChunkSize());
111 return pool
.allocChunk();
114 inline void operator delete(void* p
, Common::MemoryPool
& pool
) {