blob: 884c9cfe495e4a6f05db0eae2b4a8612fc47fc85 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
#include "memory_pool.h"
namespace Slang
{
const size_t kPoolSegmentSize = 4 << 20; // use 4MB segments
struct MemoryPoolSegment
{
unsigned char* data = nullptr;
size_t allocPtr = 0;
MemoryPoolSegment* nextSegment = nullptr;
};
MemoryPool::~MemoryPool()
{
while (curSegment)
{
auto nxtSegment = curSegment->nextSegment;
free(curSegment->data);
delete curSegment;
curSegment = nxtSegment;
}
}
void newSegment(MemoryPool* pool)
{
auto seg = new MemoryPoolSegment();
seg->nextSegment = pool->curSegment;
seg->data = (unsigned char*)malloc(kPoolSegmentSize);
pool->curSegment = seg;
}
void * MemoryPool::alloc(size_t size)
{
assert(size < kPoolSegmentSize);
// ensure there is a segment available
if (!curSegment)
newSegment(this);
if (curSegment->allocPtr + size > kPoolSegmentSize)
newSegment(this);
// alloc memory from current segment
void* rs = curSegment->data + curSegment->allocPtr;
curSegment->allocPtr += size;
return rs;
}
void * MemoryPool::allocZero(size_t size)
{
auto rs = alloc(size);
memset(rs, 0, size);
return rs;
}
}
|