GREM 3.12.0
Game/Rendering Engine Modules for C++
Loading...
Searching...
No Matches
StringPool.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Ivar Härnqvist
2// SPDX-License-Identifier: MIT
3
4#ifndef GREM_CORE_DATA_STRING_POOL_HPP
5#define GREM_CORE_DATA_STRING_POOL_HPP
6
8
12
13#include <algorithm> // std::min, std::max
14#include <bit> // std::bit_ceil, std::bit_cast
15#include <cstddef> // std::byte, std::size_t, std::ptrdiff_t
16#include <cstdint> // std::uint32_t
17#include <limits> // std::numeric_limits
18#include <stdexcept> // std::length_error
19#include <utility> // std::move
20
21namespace grem {
22
23struct StringID {
24 using index_type = std::uint32_t;
25
26 static const StringID EMPTY;
27 static const StringID INVALID;
28
29 [[nodiscard]] static constexpr StringID atExplicitOffset(index_type index) noexcept {
30 return StringID{index};
31 }
32
33 StringID() noexcept = default;
34
35 [[nodiscard]] constexpr bool operator==(const StringID&) const = default;
36 [[nodiscard]] constexpr auto operator<=>(const StringID&) const = default;
37
38 [[nodiscard]] constexpr index_type getIndex() const noexcept {
39 return index;
40 }
41
42private:
43 index_type index;
44
45 constexpr explicit StringID(index_type index) noexcept
46 : index(index) {}
47};
48
50inline constexpr StringID StringID::INVALID{std::numeric_limits<StringID::index_type>::max()};
51
52template <typename CharT, typename Allocator = std::allocator<CharT>>
54private:
55 using Length = std::uint32_t;
56
57 static constexpr std::size_t PADDED_LENGTH_SIZE_IN_CHARS = (sizeof(Length) + sizeof(CharT) - 1) / sizeof(CharT);
58 static constexpr std::size_t PADDED_LENGTH_SIZE_IN_BYTES = PADDED_LENGTH_SIZE_IN_CHARS * sizeof(CharT);
59
60 struct LengthAsBytes {
61 std::byte bytes[sizeof(Length)];
62 };
63
64 struct PaddedLengthAsBytes {
65 std::byte bytes[PADDED_LENGTH_SIZE_IN_BYTES]{};
66
67 constexpr PaddedLengthAsBytes() = default;
68
69 constexpr explicit PaddedLengthAsBytes(LengthAsBytes lengthBytes) {
70 for (std::size_t i = 0; i < PADDED_LENGTH_SIZE_IN_BYTES; ++i) {
71 bytes[i] = lengthBytes.bytes[i];
72 }
73 }
74
75 constexpr explicit operator LengthAsBytes() const {
76 LengthAsBytes result{};
77 for (std::size_t i = 0; i < sizeof(Length); ++i) {
78 result.bytes[i] = bytes[i];
79 }
80 return result;
81 }
82 };
83
84 struct LengthAsChars {
85 CharT chars[PADDED_LENGTH_SIZE_IN_CHARS];
86
87 constexpr void writeTo(CharT* output) const {
88 for (std::size_t i = 0; i < PADDED_LENGTH_SIZE_IN_CHARS; ++i) {
89 output[i] = chars[i];
90 }
91 }
92
93 constexpr void readFrom(const CharT* input) {
94 for (std::size_t i = 0; i < PADDED_LENGTH_SIZE_IN_CHARS; ++i) {
95 chars[i] = input[i];
96 }
97 }
98 };
99
100public:
101 using allocator_type = Allocator;
102
103 static constexpr std::size_t MAX_STRING_LENGTH{std::numeric_limits<Length>::max()};
104
105 constexpr StringPoolBase() noexcept
106 : StringPoolBase(0) {}
107
108 constexpr explicit StringPoolBase(std::size_t initialCapacity, const Allocator& allocator = Allocator())
109 : hashTableSlots(std::bit_ceil(initialCapacity + (initialCapacity + 1) / 2), StringID::INVALID, allocator)
110 , buffer(initialCapacity * 8, allocator) {}
111
112 constexpr explicit StringPoolBase(const Allocator& allocator)
113 : StringPoolBase(0, allocator) {}
114
115 constexpr StringPoolBase(const StringPoolBase& other)
116 : StringPoolBase(other, std::allocator_traits<Allocator>::select_on_container_copy_construction(other.get_allocator())) {}
117
118 constexpr StringPoolBase(const StringPoolBase& other, const Allocator& allocator)
119 : StringPoolBase(allocator) {
120 *this = other;
121 }
122
123 constexpr StringPoolBase(StringPoolBase&& other) noexcept = default;
124
125 constexpr StringPoolBase(StringPoolBase&& other, const Allocator& allocator) noexcept
126 : StringPoolBase(allocator) {
127 *this = std::move(other);
128 }
129
130 constexpr ~StringPoolBase() = default;
131
132 constexpr StringPoolBase& operator=(const StringPoolBase& other) = default;
133 constexpr StringPoolBase& operator=(StringPoolBase&& other) noexcept = default;
134
135 constexpr void clear() noexcept {
136 hashTableSlots.clear();
137 hashTableOccupancy = 0;
138 buffer.clear();
139 }
140
141 [[nodiscard]] constexpr StringID insert(StringViewBase<CharT> string) {
142 if (string.size() > MAX_STRING_LENGTH) {
143 throw std::length_error{"Maximum string length exceeded."};
144 }
145 if (hashTableOccupancy >= (hashTableSlots.size() / 3) * 2) {
146 const std::size_t newHashTableCapacity = std::max(hashTableSlots.size() * 2, std::size_t{64});
147 if (newHashTableCapacity <= hashTableSlots.size()) {
148 throw std::length_error{"Maximum string pool hash table capacity exceeded."};
149 }
150 Buffer<StringID, StringIDAllocator> newHashTableSlots(newHashTableCapacity, StringID::INVALID, hashTableSlots.get_allocator());
151 for (const StringID key : hashTableSlots) {
152 if (key != StringID::INVALID) {
153 const std::size_t hash = std::hash<StringViewBase<CharT>>{}((*this)[key]);
154 std::size_t slotIndex = hash & (newHashTableCapacity - 1);
155 while (newHashTableSlots[slotIndex] != StringID::INVALID) {
156 slotIndex = (slotIndex + 1) & (newHashTableCapacity - 1);
157 }
158 newHashTableSlots[slotIndex] = key;
159 }
160 }
161 hashTableSlots = std::move(newHashTableSlots);
162 }
163 if (hashTableOccupancy == 0 && !string.empty()) {
164 [[maybe_unused]] const StringID emptyStringID = insert({});
165 GREM_ASSERT(emptyStringID == StringID::EMPTY);
166 }
167 const std::size_t hash = std::hash<StringViewBase<CharT>>{}(string);
168 std::size_t slotIndex = hash & (hashTableSlots.size() - 1);
169 while (hashTableSlots[slotIndex] != StringID::INVALID && (*this)[hashTableSlots[slotIndex]] != string) {
170 slotIndex = (slotIndex + 1) & (hashTableSlots.size() - 1);
171 }
172 StringID& slot = hashTableSlots[slotIndex];
173 if (slot != StringID::INVALID) {
174 return slot;
175 }
176 const std::size_t offset = buffer.size();
177 const std::size_t addedSize = sizeof(LengthAsChars) + string.size() + 1;
178 constexpr std::size_t MAX_SIZE = std::min(std::size_t{std::numeric_limits<std::ptrdiff_t>::max()}, std::size_t{std::numeric_limits<StringID::index_type>::max()});
179 if (addedSize > MAX_SIZE || offset > MAX_SIZE - addedSize) {
180 throw std::length_error{"Maximum string pool size exceeded."};
181 }
182 buffer.resize(buffer.size() + addedSize);
183 const Length length = static_cast<Length>(string.size());
184 const LengthAsChars lengthAsChars = std::bit_cast<LengthAsChars>(PaddedLengthAsBytes{std::bit_cast<LengthAsBytes>(length)});
185 lengthAsChars.writeTo(buffer.data() + offset);
186 string.copy(buffer.data() + offset + sizeof(LengthAsChars), string.size());
187 buffer[offset + sizeof(LengthAsChars) + string.size()] = CharT();
188 const StringID newStringID = StringID::atExplicitOffset(static_cast<StringID::index_type>(offset));
189 slot = newStringID;
190 ++hashTableOccupancy;
191 return newStringID;
192 }
193
194 [[nodiscard]] constexpr StringID find(StringViewBase<CharT> string) const noexcept {
195 if (string.size() > MAX_STRING_LENGTH || hashTableSlots.empty()) {
196 return {};
197 }
198 const std::size_t hash = std::hash<StringViewBase<CharT>>{}(string);
199 std::size_t slotIndex = hash & (hashTableSlots.size() - 1);
200 while (hashTableSlots[slotIndex] != StringID::INVALID && (*this)[hashTableSlots[slotIndex]] != string) {
201 slotIndex = (slotIndex + 1) & (hashTableSlots.size() - 1);
202 }
203 return hashTableSlots[slotIndex];
204 }
205
206 [[nodiscard]] constexpr StringViewBase<CharT> operator[](StringID id) const {
207 GREM_ASSERT(std::size_t{id.getIndex()} < buffer.size());
208 LengthAsChars lengthAsChars{};
209 GREM_ASSERT(std::size_t{id.getIndex()} + sizeof(LengthAsChars) < buffer.size());
210 lengthAsChars.readFrom(buffer.data() + id.getIndex());
211 const Length length = std::bit_cast<Length>(static_cast<LengthAsBytes>(std::bit_cast<PaddedLengthAsBytes>(lengthAsChars)));
212 GREM_ASSERT(std::size_t{id.getIndex()} + sizeof(LengthAsChars) + std::size_t{length} < buffer.size());
213 return StringViewBase<CharT>{buffer.data() + std::size_t{id.getIndex()} + sizeof(LengthAsChars), std::size_t{length}};
214 }
215
216 [[nodiscard]] constexpr const CharT* c_str(StringID id) const {
217 GREM_ASSERT(std::size_t{id.getIndex()} < buffer.size());
218 GREM_ASSERT(std::size_t{id.getIndex()} + sizeof(LengthAsChars) < buffer.size());
219 return buffer.data() + std::size_t{id.getIndex()} + sizeof(LengthAsChars);
220 }
221
222 [[nodiscard]] constexpr allocator_type get_allocator() const noexcept {
223 return buffer.get_allocator();
224 }
225
226private:
227 using StringIDAllocator = typename std::allocator_traits<Allocator>::template rebind_alloc<StringID>;
228
230 std::size_t hashTableOccupancy = 0;
232};
233
235
236} // namespace grem
237
238template <>
239struct std::hash<grem::StringID> {
240 [[nodiscard]] std::size_t operator()(grem::StringID id) const {
241 return indexHasher(id.getIndex());
242 }
243
244private:
245 [[no_unique_address]] std::hash<grem::StringID::index_type> indexHasher;
246};
247
248#endif
#define GREM_ASSERT(expression)
Definition assertions.hpp:77
Definition Buffer.hpp:28
Definition StringPool.hpp:53
constexpr StringPoolBase(const StringPoolBase &other)
Definition StringPool.hpp:115
constexpr allocator_type get_allocator() const noexcept
Definition StringPool.hpp:222
constexpr StringViewBase< CharT > operator[](StringID id) const
Definition StringPool.hpp:206
constexpr void clear() noexcept
Definition StringPool.hpp:135
constexpr StringID find(StringViewBase< CharT > string) const noexcept
Definition StringPool.hpp:194
constexpr StringID insert(StringViewBase< CharT > string)
Definition StringPool.hpp:141
constexpr StringPoolBase & operator=(const StringPoolBase &other)=default
constexpr StringPoolBase(const StringPoolBase &other, const Allocator &allocator)
Definition StringPool.hpp:118
constexpr StringPoolBase(const Allocator &allocator)
Definition StringPool.hpp:112
constexpr ~StringPoolBase()=default
constexpr StringPoolBase() noexcept
Definition StringPool.hpp:105
constexpr StringPoolBase & operator=(StringPoolBase &&other) noexcept=default
Allocator allocator_type
Definition StringPool.hpp:101
constexpr StringPoolBase(std::size_t initialCapacity, const Allocator &allocator=Allocator())
Definition StringPool.hpp:108
constexpr const CharT * c_str(StringID id) const
Definition StringPool.hpp:216
static constexpr std::size_t MAX_STRING_LENGTH
Definition StringPool.hpp:103
constexpr StringPoolBase(StringPoolBase &&other) noexcept=default
constexpr StringPoolBase(StringPoolBase &&other, const Allocator &allocator) noexcept
Definition StringPool.hpp:125
Definition aliases.hpp:9
std::basic_string_view< CharT, Traits > StringViewBase
Definition StringView.hpp:14
StringPoolBase< char > StringPool
Definition StringPool.hpp:234
GREM_ALWAYS_INLINE constexpr T GREM_VECTORCALL length(T a)
Definition math.hpp:2001
Definition StringPool.hpp:23
static const StringID INVALID
Definition StringPool.hpp:27
StringID() noexcept=default
constexpr index_type getIndex() const noexcept
Definition StringPool.hpp:38
static constexpr StringID atExplicitOffset(index_type index) noexcept
Definition StringPool.hpp:29
std::uint32_t index_type
Definition StringPool.hpp:24
static const StringID EMPTY
Definition StringPool.hpp:26
std::size_t operator()(grem::StringID id) const
Definition StringPool.hpp:240