-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobjectList.hpp
167 lines (134 loc) · 2.25 KB
/
objectList.hpp
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
#ifndef LIERO_OBJECTLIST_HPP
#define LIERO_OBJECTLIST_HPP
#include <cstddef>
#include <cassert>
struct ObjectListBase
{
ObjectListBase* nextFree;
bool used;
/*
ObjectListBase* prev;
ObjectListBase* next;*/
};
template<typename T, int Limit>
struct ObjectList
{
struct iterator
{
iterator(T* cur_)
: cur(cur_)
{
while(!cur->used)
++cur;
}
iterator& operator++()
{
do
{
++cur;
}
while(!cur->used);
return *this;
}
T& operator*()
{
assert(cur->used);
return *cur;
}
T* operator->()
{
assert(cur->used);
return cur;
}
bool operator!=(iterator b)
{
return cur != b.cur;
}
T* cur;
};
ObjectList()
{
clear();
}
T* getFreeObject()
{
T* ptr = static_cast<T*>(nextFree);
nextFree = ptr->nextFree;
ptr->used = true;
/*
sentinel.prev->next = ptr;
ptr->prev = sentinel.prev;
ptr->next = &sentinel;
sentinel.prev = ptr;
*/
++count;
return ptr;
}
T* newObjectReuse()
{
T* ret;
if(!nextFree)
ret = &arr[Limit - 1];
else
ret = getFreeObject();
assert(ret->used);
return ret;
}
T* newObject()
{
if(!nextFree)
return 0;
T* ret = getFreeObject();
assert(ret->used);
return ret;
}
iterator begin()
{
return iterator(&arr[0]);
}
iterator end()
{
return iterator(&arr[Limit]);
}
void free(T* ptr)
{
assert(ptr->used);
if(ptr->used)
{
ptr->nextFree = nextFree;
nextFree = ptr;
ptr->used = false;
assert(count > 0);
--count;
}
}
void free(iterator i)
{
free(&*i);
}
void clear()
{
count = 0;
/*
sentinel.prev = &sentinel;
sentinel.next = &sentinel;*/
arr[Limit].used = true; // Sentinel
for(std::size_t i = 0; i < Limit - 1; ++i)
{
arr[i].nextFree = &arr[i + 1];
arr[i].used = false;
}
arr[Limit - 1].nextFree = 0;
arr[Limit - 1].used = false;
nextFree = &arr[0];
}
std::size_t size() const
{
return count;
}
T arr[Limit + 1]; // One sentinel
ObjectListBase* nextFree;
//ObjectListBase sentinel;
std::size_t count;
};
#endif // LIERO_OBJECTLIST_HPP