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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
|
/*
* libfud
* Copyright 2025 Dominick Allen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef FUD_HASH_MAP_HPP
#define FUD_HASH_MAP_HPP
#include "fud_allocator.hpp"
#include "fud_hash.hpp"
#include "fud_hash_map_impl.hpp"
#include "fud_option.hpp"
#include "fud_result.hpp"
#include "fud_status.hpp"
#include <algorithm>
namespace fud {
constexpr double hashMapMaxLoadFactor = 0.6;
/** \brief An open-address hash map using quadratic probing.
*
* Templates on a Hash object to facilitate a variety of hashing function implementations. */
template <typename Key, typename Value, typename Hash>
class HashMap {
static_assert(!std::is_same_v<Key, option_detail::NullOptionType>);
static_assert(!std::is_same_v<Value, option_detail::NullOptionType>);
public:
struct KeyValuePair {
Key m_key;
Value m_value;
};
using Entry = Option<KeyValuePair>;
using Node = detail::MapEntry<Key, Value>;
static constexpr size_t NodeSize = sizeof(Node);
static constexpr size_t Alignment = alignof(Node);
constexpr HashMap() noexcept = default;
/** \brief Construct a HashMap explicitly using the specified allocator. */
constexpr explicit HashMap(Allocator& allocator) noexcept : m_allocator{&allocator}
{
}
constexpr HashMap(const HashMap& rhs) = delete;
constexpr HashMap(HashMap&& rhs) noexcept :
m_allocator{rhs.m_allocator},
m_data{rhs.m_data},
m_count{rhs.m_count},
m_buckets{rhs.m_buckets},
m_seed{rhs.m_seed},
m_hasher{std::move(rhs.m_hasher)}
{
rhs.m_allocator = nullptr;
rhs.m_data = nullptr;
rhs.m_count = 0;
rhs.m_buckets = 0;
}
HashMap& operator=(const HashMap& rhs) = delete;
HashMap& operator=(HashMap&& rhs) noexcept
{
if (&rhs == this) {
return *this;
}
static_cast<void>(cleanup());
m_allocator = rhs.m_allocator;
m_data = rhs.m_data;
m_count = rhs.m_count;
m_buckets = rhs.m_buckets;
m_seed = rhs.m_seed;
m_hasher = std::move(rhs.m_hasher);
rhs.m_allocator = nullptr;
rhs.m_data = nullptr;
rhs.m_count = 0;
rhs.m_buckets = 0;
return *this;
}
constexpr ~HashMap() noexcept
{
static_cast<void>(cleanup());
}
[[nodiscard]] size_t size() noexcept
{
return m_count;
}
[[nodiscard]] size_t capacity()
{
return m_buckets;
}
[[nodiscard]] bool contains(const Key& key) const
{
return lookup(key).hasValue();
}
[[nodiscard]] bool contains(Key&& key) const
{
return lookup(std::move(key)).hasValue();
}
FudStatus insert(const Key& key, const Value& value)
{
auto growStatus = checkGrow();
if (growStatus != FudStatus::Success) {
return growStatus;
}
auto hashIndexResult = findEmptyBucket(key, m_buckets, m_data);
if (hashIndexResult.isError()) {
return hashIndexResult.takeError();
}
auto hashIndex{hashIndexResult.takeOkay()};
m_data[hashIndex].~Node();
auto* ptr = new (m_data + hashIndex) Node{key, value};
m_count++;
return FudStatus::Success;
}
FudStatus insert(const Key& key, Value&& value)
{
auto growStatus = checkGrow();
if (growStatus != FudStatus::Success) {
return growStatus;
}
auto hashIndexResult = findEmptyBucket(key, m_buckets, m_data);
if (hashIndexResult.isError()) {
return hashIndexResult.takeError();
}
auto hashIndex{hashIndexResult.takeOkay()};
m_data[hashIndex].~Node();
auto* ptr = new (m_data + hashIndex) Node{key, std::move(value)};
m_count++;
return FudStatus::Success;
}
FudStatus insert(Key&& key, const Value& value)
{
auto growStatus = checkGrow();
if (growStatus != FudStatus::Success) {
return growStatus;
}
auto hashIndexResult = findEmptyBucket(key, m_buckets, m_data);
if (hashIndexResult.isError()) {
return hashIndexResult.takeError();
}
auto hashIndex{hashIndexResult.takeOkay()};
m_data[hashIndex].~Node();
auto* ptr = new (m_data + hashIndex) Node{std::move(key), value};
m_count++;
return FudStatus::Success;
}
FudStatus insert(Key&& key, Value&& value)
{
auto growStatus = checkGrow();
if (growStatus != FudStatus::Success) {
return growStatus;
}
auto hashIndexResult = findEmptyBucket(key, m_buckets, m_data);
if (hashIndexResult.isError()) {
return hashIndexResult.takeError();
}
auto hashIndex{hashIndexResult.takeOkay()};
m_data[hashIndex].~Node();
auto* ptr = new (m_data + hashIndex) Node{std::move(key), std::move(value)};
m_count++;
return FudStatus::Success;
}
FudStatus update(const Key& key, const Value& value)
{
auto hashIndexOption = lookup(key);
if (hashIndexOption.isNone()) {
return insert(key, value);
}
auto hashIndex{hashIndexOption.take()};
m_data[hashIndex].value() = value;
return FudStatus::Success;
}
FudStatus update(const Key& key, Value&& value)
{
auto hashIndexOption = lookup(key);
if (hashIndexOption.isNone()) {
return insert(key, std::move(value));
}
auto hashIndex{hashIndexOption.take()};
m_data[hashIndex].value() = std::move(value);
return FudStatus::Success;
}
FudStatus update(Key&& key, const Value& value)
{
auto hashIndexOption = lookup(key);
if (hashIndexOption.isNone()) {
return insert(std::move(key), value);
}
auto hashIndex{hashIndexOption.take()};
m_data[hashIndex].value() = value;
return FudStatus::Success;
}
FudStatus update(Key&& key, Value&& value)
{
auto hashIndexOption = lookup(key);
if (hashIndexOption.isNone()) {
return insert(std::move(key), std::move(value));
}
auto hashIndex{hashIndexOption.take()};
m_data[hashIndex].value() = std::move(value);
return FudStatus::Success;
}
FudStatus remove(const Key& key)
{
auto hashIndexOption = lookup(key);
if (hashIndexOption.isNone()) {
return FudStatus::NotFound;
}
m_data[hashIndexOption.value()].tombstone();
return FudStatus::Success;
}
FudStatus remove(Key&& key)
{
auto hashIndexOption = lookup(std::move(key));
if (hashIndexOption.isNone()) {
return FudStatus::NotFound;
}
m_data[hashIndexOption.value()].tombstone();
return FudStatus::Success;
}
Option<Value> extract(const Key& key)
{
auto hashIndexOption = lookup(key);
if (hashIndexOption.isNone()) {
return NullOpt;
}
auto hashIndex{hashIndexOption.value()};
Option<Value> value{std::move(m_data[hashIndex].takeValue())};
m_data[hashIndex].tombstone();
return value;
}
Option<Value> extract(Key&& key)
{
auto hashIndexOption = lookup(std::move(key));
if (hashIndexOption.isNone()) {
return NullOpt;
}
auto hashIndex{hashIndexOption.value()};
Option<Value> value{std::move(m_data[hashIndex].takeValue())};
m_data[hashIndex].tombstone();
return value;
}
KeyValuePair extractPair(const Key& key)
{
auto hashIndexOption = lookup(key);
if (hashIndexOption.isNone()) {
return NullOpt;
}
auto hashIndex{hashIndexOption.value()};
KeyValuePair kvPair{key, m_data[hashIndex].takeValue()};
m_data[hashIndex].tombstone();
return kvPair;
}
KeyValuePair extractPair(Key&& key)
{
auto hashIndexOption = lookup(key);
if (hashIndexOption.isNone()) {
return NullOpt;
}
auto hashIndex{hashIndexOption.value()};
KeyValuePair kvPair{std::move(key), m_data[hashIndex].takeValue()};
m_data[hashIndex].tombstone();
return kvPair;
}
Option<Value> get(const Key& key)
{
auto hashIndexOption = lookup(key);
if (hashIndexOption.isNone()) {
return NullOpt;
}
return m_data[hashIndexOption.value()].value();
}
Option<Value&> getRef(const Key& key) const
{
auto hashIndexOption = lookup(key);
if (hashIndexOption.isNone()) {
return NullOpt;
}
return m_data[hashIndexOption.value()].value();
}
Option<const Value&> getConstRef(const Key& key) const
{
auto hashIndexOption = lookup(key);
if (hashIndexOption.isNone()) {
return NullOpt;
}
return m_data[hashIndexOption.value()].value();
}
[[nodiscard]] bool empty() const;
FudStatus clear()
{
if (m_allocator == nullptr || m_data == nullptr) {
if (m_buckets > 0 || m_count > 0) {
return FudStatus::ObjectInvalid;
}
return FudStatus::Success;
}
for (size_t index = 0; index < m_buckets; ++index) {
m_data[index].~Node();
}
m_count = 0;
return FudStatus::Success;
}
FudStatus reserve(size_t count)
{
if (count <= m_buckets) {
return FudStatus::Success;
}
if (m_allocator == nullptr) {
return FudStatus::ObjectInvalid;
}
if (count > SIZE_MAX / NodeSize) {
return FudStatus::ArgumentInvalid;
}
size_t requestedSize = count * NodeSize;
auto dataPtrResult = m_allocator->allocate(requestedSize, Alignment);
if (dataPtrResult.isError()) {
return dataPtrResult.takeError();
}
auto* dataPtr = std::bit_cast<Node*>(dataPtrResult.takeOkay());
for (size_t index = 0; index < count; ++index) {
const auto* ptr = new (dataPtr + index) Node();
fudAssert(ptr != nullptr);
}
for (size_t index = 0; index < m_buckets; ++index) {
if (m_data[index].hasValue()) {
const auto& key = m_data[index].key();
auto newHashIndexResult = findEmptyBucket(key, count, dataPtr);
if (newHashIndexResult.isError()) {
m_allocator->deallocate(std::bit_cast<std::byte*>(dataPtr), requestedSize);
return FudStatus::Failure;
}
const auto newHashIndex{newHashIndexResult.takeOkay()};
dataPtr[newHashIndex].~Node();
const auto* ptr = new (dataPtr + newHashIndex) Node(std::move(m_data[index]));
fudAssert(ptr != nullptr);
m_data[index].~Node();
}
}
auto status = FudStatus::Success;
if (m_buckets > 0) {
m_allocator->deallocate(std::bit_cast<std::byte*>(m_data), m_buckets * NodeSize);
}
m_data = dataPtr;
m_buckets = count;
return status;
}
Result<Option<Value>, FudStatus> exchange(const Key& key, const Value& value);
protected:
[[nodiscard]] double loadFactor() const
{
if (m_buckets == 0) {
return hashMapMaxLoadFactor + 1.0;
}
return static_cast<double>(m_count) / static_cast<double>(m_buckets);
}
FudStatus checkGrow()
{
if (loadFactor() > hashMapMaxLoadFactor) {
auto growStatus = grow();
if (growStatus != FudStatus::Success) {
return growStatus;
}
}
return FudStatus::Success;
}
FudStatus grow()
{
size_t additional = m_buckets < 3 ? 3 : m_buckets / 2;
constexpr auto maxSize = std::numeric_limits<size_t>::max();
if (maxSize - additional * NodeSize < m_buckets * NodeSize) {
additional = maxSize - m_buckets * NodeSize / 2;
}
while (additional > 0) {
auto reserveStatus = reserve(additional + m_buckets);
if (reserveStatus == FudStatus::Success) {
break;
}
if (reserveStatus == FudStatus::AllocFailure) {
additional /= 2;
} else {
return reserveStatus;
}
}
if (loadFactor() >= hashMapMaxLoadFactor) {
return FudStatus::AllocFailure;
}
return FudStatus::Success;
}
FudStatus cleanup() noexcept
{
auto status = clear();
if (m_data != nullptr && m_allocator != nullptr) {
m_allocator->deallocate(std::bit_cast<std::byte*>(m_data), m_buckets);
}
m_allocator = nullptr;
m_data = nullptr;
m_count = 0;
m_buckets = 0;
return status;
}
[[nodiscard]] static constexpr size_t calculateHashIndex(size_t hash, size_t probe)
{
return hash + ((probe + probe * probe) / 2);
}
Option<size_t> lookup(const Key& key) const
{
if (m_count == 0 || m_buckets == 0 || m_data == nullptr) {
return NullOpt;
}
const auto hash = m_hasher(key, m_seed);
const auto nearestPowerOf2 = detail::roundToNearest2(m_buckets);
size_t probe = 0;
size_t hashIndex{};
auto collision = true;
while (collision and probe < m_buckets) {
hashIndex = calculateHashIndex(hash, probe) % nearestPowerOf2;
probe++;
if (hashIndex >= m_buckets) {
continue;
}
collision = not m_data[hashIndex].isNone();
if (m_data[hashIndex].isTombstone()) {
continue;
}
if (collision and m_data[hashIndex].key() == key) {
break;
}
}
if (collision and hashIndex < m_buckets and m_data[hashIndex].key() == key) {
return hashIndex;
}
return NullOpt;
}
Result<size_t, FudStatus> findEmptyBucket(const Key& key, size_t buckets, Node* data)
{
const auto hash = m_hasher(key, m_seed);
const auto nearestPowerOf2 = detail::roundToNearest2(buckets);
size_t hashIndex{};
auto collision = true;
size_t probe = 0;
bool foundFirstSlot{false};
size_t firstHashIndex{};
while (collision and probe < buckets) {
hashIndex = calculateHashIndex(hash, probe) % nearestPowerOf2;
probe++;
if (hashIndex >= buckets) {
continue;
}
collision = not data[hashIndex].isNone();
if (not foundFirstSlot and data[hashIndex].isTombstone()) {
foundFirstSlot = true;
firstHashIndex = hashIndex;
}
if (collision and data[hashIndex].key() == key) {
break;
}
}
if (collision and data[hashIndex].key() == key) {
return Error{FudStatus::Exists};
}
if (foundFirstSlot) {
return Okay{firstHashIndex};
}
if (collision) {
return Error{FudStatus::Failure};
}
return Okay{hashIndex};
}
Allocator* m_allocator{&globalFudAllocator};
Node* m_data{nullptr};
size_t m_count{0};
size_t m_buckets{0};
size_t m_seed{0};
Hash m_hasher{};
};
} // namespace fud
#endif
|