30 template <
typename Key,
typename Value>
42 Entry() : occupied(
false), deleted(
false) {}
50 static constexpr size_t DEFAULT_CAPACITY = 16;
51 static constexpr float DEFAULT_LOAD_FACTOR = 0.7f;
54 size_t hash(
const Key& key)
const
56 return reinterpret_cast<uintptr_t
>(&key) % capacity;
62 size_t newCapacity = capacity * 2;
63 Entry* newTable =
new Entry[newCapacity];
65 for (
size_t i = 0; i < capacity; ++i)
67 if (table[i].occupied && !table[i].deleted)
69 size_t index = hash(table[i].key) % newCapacity;
70 while (newTable[index].occupied)
72 index = (index + 1) % newCapacity;
74 newTable[index] = std::move(table[i]);
80 capacity = newCapacity;
84 HashTable(
size_t initCapacity = DEFAULT_CAPACITY,
float loadFactor = DEFAULT_LOAD_FACTOR)
85 : capacity(initCapacity), size(0), loadFactor(loadFactor)
87 table =
new Entry[capacity];
96 void insert(
const Key& key,
const Value& value)
98 if (size >= capacity * loadFactor)
103 size_t index = hash(key) % capacity;
104 while (table[index].occupied && !table[index].deleted && table[index].key != key)
106 index = (index + 1) % capacity;
109 if (!table[index].occupied || table[index].deleted)
111 table[index].key = key;
112 table[index].value = value;
113 table[index].occupied =
true;
114 table[index].deleted =
false;
119 table[index].value = value;
126 size_t index = hash(key) % capacity;
127 while (table[index].occupied)
129 if (!table[index].deleted && table[index].key == key)
131 table[index].deleted =
true;
135 index = (index + 1) % capacity;
141 bool get(
const Key& key, Value& outValue)
const
143 size_t index = hash(key) % capacity;
144 while (table[index].occupied)
146 if (!table[index].deleted && table[index].key == key)
148 outValue = table[index].value;
151 index = (index + 1) % capacity;
159 size_t index = hash(key) % capacity;
160 while (table[index].occupied)
162 if (!table[index].deleted && table[index].key == key)
166 index = (index + 1) % capacity;
175 table =
new Entry[capacity];
bool contains(const Key &key) const
True if key currently has a live entry.
void insert(const Key &key, const Value &value)
Inserts or updates the value for key, resizing first if over the load factor.
void clear()
Drops every entry and reallocates the table at its current capacity.
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
Looks up key and writes its value into outValue; returns false if not found.
HashTable(size_t initCapacity=DEFAULT_CAPACITY, float loadFactor=DEFAULT_LOAD_FACTOR)
Root namespace for everything the engine exposes.