-
Notifications
You must be signed in to change notification settings - Fork 0
/
fixedpool.cpp
86 lines (65 loc) · 1.67 KB
/
fixedpool.cpp
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include "fixedpool.h"
#include "assert.h"
FixedPool::FixedPool(){
capacity = 0;
allocSize = 0;
mem = nullptr;
}
void FixedPool::Setup(int _allocSize, int count){
capacity = count;
allocSize = _allocSize;
mem = malloc(allocSize * count);
allocTracker.EnsureCapacity(count);
allocTracker.Clear();
}
void FixedPool::Destroy() {
capacity = 0;
allocSize = 0;
free(mem);
allocTracker.Clear();
}
void* FixedPool::Allocate(){
for (int i = 0; i < allocTracker.bytesAlloc/4; i++){
if (((unsigned int)allocTracker.values[i]) != 0xFFFFFFFF){
for (int j = 0; j < 32; j++){
if ((allocTracker.values[i] & (1 << j)) == 0){
int index = i * 32 + j;
allocTracker.SetBit(i, true);
void* ptr = ((char*)mem) + (index*allocSize);
return ptr;
}
}
ASSERT_WARN("%s", "Issue with alloc tracker, very strange.");
}
}
ASSERT_WARN("%s", "Could not allocate out of fixed pool.");
return nullptr;
}
void FixedPool::Deallocate(void* ptr){
int index = (int)(((char*)ptr - (char*)mem) / allocSize);
//Pointers should never be unaligned
ASSERT((char*)mem + (index * allocSize) == ptr);
ASSERT(index >= 0 && index < capacity);
allocTracker.SetBit(index, false);
}
#if defined(FIXEDPOOL_TEST_MAIN)
#include "macros.h"
CREATE_TEST_CASE("Fixed pool...is this used?"){
FixedPool pool;
pool.Setup((int)sizeof(int), 70);
for (int t = 0; t < 20; t++){
void* allocs[68] = {};
for (int i = 0; i < BNS_ARRAY_COUNT(allocs); i++){
allocs[i] = pool.Allocate();
}
for (int i = 0; i < BNS_ARRAY_COUNT(allocs); i++){
pool.Deallocate(allocs[i]);
}
}
for (int i = 0; i < 70; i++) {
ASSERT(!pool.allocTracker.GetBit(i));
}
pool.Destroy();
return 0;
}
#endif