SleakEngine 0.1.0
C++23 multi-backend game engine
Loading...
Searching...
No Matches
HashTable.hpp
Go to the documentation of this file.
1#ifndef _HASH_TABLE_H_
2#define _HASH_TABLE_H_
3
4#include <cstddef>
5#include <cstdint>
6#include <functional>
7#include <utility>
8
9namespace Sleak
10{
11/**
12 * @class HashTable
13 * @brief Implements a hash table (or map) for efficient key-value storage and
14 * retrieval.
15 *
16 * The HashTable class provides fast access to values based on their associated
17 * keys. It is suitable for scenarios where you need to quickly look up data
18 * using unique identifiers. Use this class when you need to store and retrieve
19 * data based on keys, such as symbol tables, dictionaries, or caching systems.
20 *
21 * Example Use Cases:
22 * - Implementing a symbol table in a compiler.
23 * - Creating a dictionary or vocabulary lookup system.
24 * - Caching frequently accessed data.
25 * - Storing user preferences or configuration settings.
26 *
27 * Implementation Details:
28 * - Uses a hash function to map keys to indices in an internal array.
29 * - Handles collisions with linear-probing open addressing and tombstones.
30 * - Provides methods for inserting, deleting, and retrieving key-value pairs.
31 * @ingroup utility
32 */
33template <typename Key, typename Value>
34class HashTable {
35 private:
36 /// One slot: key/value plus occupied and tombstone-deleted flags.
37 struct Entry {
38 Key key;
39 Value value;
40 bool occupied;
41 bool deleted; // To handle tombstones in deletion
42
43 Entry() : occupied(false), deleted(false) {}
44 };
45
46 Entry* table;
47 size_t capacity;
48 size_t size;
49 size_t tombstones;
50 float loadFactor;
51
52 static constexpr size_t DEFAULT_CAPACITY = 16;
53 static constexpr float DEFAULT_LOAD_FACTOR = 0.7f;
54 static constexpr float MAX_LOAD_FACTOR = 1.0f;
55 static constexpr size_t MIN_CAPACITY = 1;
56 static constexpr size_t GROWTH_FACTOR = 2;
57
58 /// Home slot of key in a table with tableCapacity slots.
59 static size_t slotFor(const Key& key, size_t tableCapacity) {
60 return std::hash<Key>{}(key) % tableCapacity;
61 }
62
63 /// Home slot of key in the current table.
64 size_t hash(const Key& key) const { return slotFor(key, capacity); }
65
66 /// Slot holding a live entry for key, or capacity if there is none.
67 size_t findSlot(const Key& key) const {
68 size_t index = hash(key);
69 for (size_t probes = 0; probes < capacity && table[index].occupied;
70 ++probes) {
71 if (!table[index].deleted && table[index].key == key) {
72 return index;
73 }
74 index = (index + 1) % capacity;
75 }
76 return capacity;
77 }
78
79 /// Moves live entries into a newCapacity table, dropping tombstones.
80 void rehash(size_t newCapacity) {
81 Entry* newTable = new Entry[newCapacity];
82
83 for (size_t i = 0; i < capacity; ++i) {
84 if (table[i].occupied && !table[i].deleted) {
85 size_t index = slotFor(table[i].key, newCapacity);
86 while (newTable[index].occupied) {
87 index = (index + 1) % newCapacity;
88 }
89 newTable[index] = std::move(table[i]);
90 }
91 }
92
93 delete[] table;
94 table = newTable;
95 capacity = newCapacity;
96 tombstones = 0;
97 }
98
99 /// Grows if live entries fill the table, else purges tombstones only.
100 void resize() {
101 const bool mostlyLive = size * GROWTH_FACTOR >= capacity * loadFactor;
102 rehash(mostlyLive ? capacity * GROWTH_FACTOR : capacity);
103 }
104
105 public:
106 HashTable(size_t initCapacity = DEFAULT_CAPACITY,
107 float loadFactor = DEFAULT_LOAD_FACTOR)
108 : capacity(initCapacity > MIN_CAPACITY ? initCapacity : MIN_CAPACITY),
109 size(0),
110 tombstones(0),
111 loadFactor(loadFactor > 0.0f && loadFactor <= MAX_LOAD_FACTOR
112 ? loadFactor
113 : DEFAULT_LOAD_FACTOR) {
114 table = new Entry[capacity];
115 }
116
117 /// Deep-copies other's slots, including its capacity and load factor.
118 HashTable(const HashTable& other)
119 : table(new Entry[other.capacity]),
120 capacity(other.capacity),
121 size(other.size),
122 tombstones(other.tombstones),
123 loadFactor(other.loadFactor) {
124 for (size_t i = 0; i < capacity; ++i) {
125 table[i] = other.table[i];
126 }
127 }
128
129 /// Replaces this table with a deep copy of other.
131 if (this != &other) {
132 HashTable copy(other);
133 std::swap(table, copy.table);
134 std::swap(capacity, copy.capacity);
135 std::swap(size, copy.size);
136 std::swap(tombstones, copy.tombstones);
137 std::swap(loadFactor, copy.loadFactor);
138 }
139 return *this;
140 }
141
142 ~HashTable() { delete[] table; }
143
144 /// Inserts or updates the value for key, resizing first if over the load
145 /// factor.
146 void insert(const Key& key, const Value& value) {
147 const size_t existing = findSlot(key);
148 if (existing != capacity) {
149 table[existing].value = value;
150 return;
151 }
152
153 if (size + tombstones >= capacity * loadFactor) {
154 resize();
155 }
156
157 size_t index = hash(key);
158 while (table[index].occupied && !table[index].deleted) {
159 index = (index + 1) % capacity;
160 }
161
162 if (table[index].deleted) {
163 --tombstones;
164 }
165 table[index].key = key;
166 table[index].value = value;
167 table[index].occupied = true;
168 table[index].deleted = false;
169 ++size;
170 }
171
172 /// Tombstones the entry for key; returns false if it wasn't present.
173 bool remove(const Key& key) {
174 const size_t index = findSlot(key);
175 if (index == capacity) {
176 return false;
177 }
178 table[index].key = Key();
179 table[index].value = Value();
180 table[index].deleted = true;
181 --size;
182 ++tombstones;
183 return true;
184 }
185
186 /// Looks up key and writes its value into outValue; returns false if not
187 /// found.
188 bool get(const Key& key, Value& outValue) const {
189 const size_t index = findSlot(key);
190 if (index == capacity) {
191 return false;
192 }
193 outValue = table[index].value;
194 return true;
195 }
196
197 /// True if key currently has a live entry.
198 bool contains(const Key& key) const { return findSlot(key) != capacity; }
199
200 /// Drops every entry and reallocates the table at its current capacity.
201 void clear() {
202 Entry* emptyTable = new Entry[capacity];
203 delete[] table;
204 table = emptyTable;
205 size = 0;
206 tombstones = 0;
207 }
208
209 size_t getSize() const { return size; }
210 size_t getCapacity() const { return capacity; }
211};
212}
213
214#endif // _HASH_TABLE_H_
size_t getSize() const
bool contains(const Key &key) const
True if key currently has a live entry.
void insert(const Key &key, const Value &value)
void clear()
Drops every entry and reallocates the table at its current capacity.
HashTable(const HashTable &other)
Deep-copies other's slots, including its capacity and load factor.
size_t getCapacity() const
bool remove(const Key &key)
Tombstones the entry for key; returns false if it wasn't present.
bool get(const Key &key, Value &outValue) const
HashTable(size_t initCapacity=DEFAULT_CAPACITY, float loadFactor=DEFAULT_LOAD_FACTOR)
HashTable & operator=(const HashTable &other)
Replaces this table with a deep copy of other.
Root namespace for everything the engine exposes.
Definition Camera.hpp:10