| 1 |
#ifndef OBJECTPOOL_HH |
| 2 |
#define OBJECTPOOL_HH |
| 3 |
|
| 4 |
#include "narrow.hh" |
| 5 |
#include "unreachable.hh" |
| 6 |
#include "xrange.hh" |
| 7 |
|
| 8 |
#include <array> |
| 9 |
#include <cstdint> |
| 10 |
#include <memory> |
| 11 |
#include <vector> |
| 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 |
template<typename T> |
| 55 |
class ObjectPool |
| 56 |
{ |
| 57 |
public: |
| 58 |
using Index = uint32_t; |
| 59 |
|
| 60 |
struct EmplaceResult { |
| 61 |
Index idx; |
| 62 |
T* ptr; |
| 63 |
}; |
| 64 |
|
| 65 |
private: |
| 66 |
union Element { |
| 67 |
Element() {} |
| 68 |
~Element() {} |
| 69 |
|
| 70 |
Index next; |
| 71 |
T t; |
| 72 |
}; |
| 73 |
using Element256 = std::array<Element, 256>; |
| 74 |
|
| 75 |
public: |
| 76 |
template<typename... Args> |
| 77 |
[[nodiscard]] EmplaceResult emplace(Args&& ...args) { |
| 78 |
Index idx; |
| 79 |
if (free != Index(-1)) { |
| 80 |
idx = free; |
| 81 |
free = get(idx).next; |
| 82 |
} else { |
| 83 |
if (cntr == 0) { |
| 84 |
pool.push_back(std::make_unique<Element256>()); |
| 85 |
} |
| 86 |
idx = Index(((pool.size() - 1) << 8) + cntr); |
| 87 |
++cntr; |
| 88 |
} |
| 89 |
T* ptr = &get(idx).t; |
| 90 |
new(ptr) T(std::forward<Args>(args)...); |
| 91 |
return {idx, ptr}; |
| 92 |
} |
| 93 |
|
| 94 |
[[nodiscard]] const T& operator[](Index idx) const { return get(idx).t; } |
| 95 |
[[nodiscard]] T& operator[](Index idx) { return get(idx).t; } |
| 96 |
|
| 97 |
void remove(Index idx) { |
| 98 |
auto& elem = get(idx); |
| 99 |
elem.t.~T(); |
| 100 |
elem.next = free; |
| 101 |
free = idx; |
| 102 |
} |
| 103 |
|
| 104 |
void remove(const T* ptr) { |
| 105 |
remove(ptr2Index(ptr)); |
| 106 |
} |
| 107 |
|
| 108 |
Index ptr2Index(const T* ptr) const { |
| 109 |
for (auto i : xrange(pool.size())) { |
| 110 |
const auto& elem256 = *pool[i]; |
| 111 |
const T* begin = &elem256[0].t; |
| 112 |
const T* end = begin + 256; |
| 113 |
if ((begin <= ptr) && (ptr < end)) { |
| 114 |
return Index((i << 8) + (ptr - begin)); |
| 115 |
} |
| 116 |
} |
| 117 |
UNREACHABLE; |
| 118 |
} |
| 119 |
|
| 120 |
|
| 121 |
[[nodiscard]] Index capacity() const { |
| 122 |
return narrow<Index>(256 * pool.size()); |
| 123 |
} |
| 124 |
|
| 125 |
private: |
| 126 |
[[nodiscard]] const Element& get(Index idx) const { return (*pool[idx >> 8])[idx & 255]; } |
| 127 |
[[nodiscard]] Element& get(Index idx) { return (*pool[idx >> 8])[idx & 255]; } |
| 128 |
|
| 129 |
private: |
| 130 |
std::vector<std::unique_ptr<Element256>> pool; |
| 131 |
Index free = Index(-1); |
| 132 |
uint8_t cntr = 0; |
| 133 |
}; |
| 134 |
|
| 135 |
#endif |