Skip to content

Commit d30191c

Browse files
committed
Add Pool type
1 parent 9095ddc commit d30191c

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

util/pool.hh

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
#pragma once
2+
#include <array>
3+
#include <cstddef>
4+
5+
namespace cpputil
6+
{
7+
8+
// Hold static memory for a maximum number of objects of a given type T
9+
// Default constructs one when asked to create()
10+
template<typename T, size_t MaxEntries>
11+
struct Pool {
12+
13+
struct Entry {
14+
T data;
15+
bool used = false;
16+
};
17+
std::array<Entry, MaxEntries> entries{};
18+
19+
Pool() = default;
20+
21+
// Returns ptr to a default-constructed T
22+
// Returns nullptr if none available
23+
T *create() {
24+
for (auto &entry : entries) {
25+
if (!entry.used) {
26+
entry.used = true;
27+
entry.data = T{};
28+
return &entry.data;
29+
}
30+
}
31+
32+
return nullptr;
33+
}
34+
35+
// Returns ptr to a T in an unspecificed state
36+
// Returns nullptr if none available
37+
T *create_for_overwrite() {
38+
for (auto &entry : entries) {
39+
if (!entry.used) {
40+
entry.used = true;
41+
return &entry.data;
42+
}
43+
}
44+
45+
return nullptr;
46+
}
47+
48+
// Returns whether item was found
49+
bool destroy(T *item) {
50+
for (auto &entry : entries) {
51+
if (entry.used && item == &entry.data) {
52+
entry.used = false;
53+
return true;
54+
}
55+
}
56+
return false;
57+
}
58+
};
59+
} // namespace cpputil

0 commit comments

Comments
 (0)