hash_map.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. /**************************************************************************/
  2. /* hash_map.h */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #pragma once
  31. #include "core/os/memory.h"
  32. #include "core/templates/hashfuncs.h"
  33. #include "core/templates/pair.h"
  34. #include <initializer_list>
  35. /**
  36. * A HashMap implementation that uses open addressing with Robin Hood hashing.
  37. * Robin Hood hashing swaps out entries that have a smaller probing distance
  38. * than the to-be-inserted entry, that evens out the average probing distance
  39. * and enables faster lookups. Backward shift deletion is employed to further
  40. * improve the performance and to avoid infinite loops in rare cases.
  41. *
  42. * Keys and values are stored in a double linked list by insertion order. This
  43. * has a slight performance overhead on lookup, which can be mostly compensated
  44. * using a paged allocator if required.
  45. *
  46. * The assignment operator copy the pairs from one map to the other.
  47. */
  48. template <typename TKey, typename TValue>
  49. struct HashMapElement {
  50. HashMapElement *next = nullptr;
  51. HashMapElement *prev = nullptr;
  52. KeyValue<TKey, TValue> data;
  53. HashMapElement() {}
  54. HashMapElement(const TKey &p_key, const TValue &p_value) :
  55. data(p_key, p_value) {}
  56. };
  57. bool _hashmap_variant_less_than(const Variant &p_left, const Variant &p_right);
  58. template <typename TKey, typename TValue,
  59. typename Hasher = HashMapHasherDefault,
  60. typename Comparator = HashMapComparatorDefault<TKey>,
  61. typename Allocator = DefaultTypedAllocator<HashMapElement<TKey, TValue>>>
  62. class HashMap : private Allocator {
  63. public:
  64. static constexpr uint32_t MIN_CAPACITY_INDEX = 2; // Use a prime.
  65. static constexpr float MAX_OCCUPANCY = 0.75;
  66. static constexpr uint32_t EMPTY_HASH = 0;
  67. private:
  68. HashMapElement<TKey, TValue> **elements = nullptr;
  69. uint32_t *hashes = nullptr;
  70. HashMapElement<TKey, TValue> *head_element = nullptr;
  71. HashMapElement<TKey, TValue> *tail_element = nullptr;
  72. uint32_t capacity_index = 0;
  73. uint32_t num_elements = 0;
  74. _FORCE_INLINE_ static uint32_t _hash(const TKey &p_key) {
  75. uint32_t hash = Hasher::hash(p_key);
  76. if (unlikely(hash == EMPTY_HASH)) {
  77. hash = EMPTY_HASH + 1;
  78. }
  79. return hash;
  80. }
  81. _FORCE_INLINE_ static constexpr void _increment_mod(uint32_t &r_pos, const uint32_t p_capacity) {
  82. r_pos++;
  83. // `if` is faster than both fastmod and mod.
  84. if (unlikely(r_pos == p_capacity)) {
  85. r_pos = 0;
  86. }
  87. }
  88. static _FORCE_INLINE_ uint32_t _get_probe_length(const uint32_t p_pos, const uint32_t p_hash, const uint32_t p_capacity, const uint64_t p_capacity_inv) {
  89. const uint32_t original_pos = fastmod(p_hash, p_capacity_inv, p_capacity);
  90. const uint32_t distance_pos = p_pos - original_pos + p_capacity;
  91. // At most p_capacity over 0, so we can use an if (faster than fastmod).
  92. return distance_pos >= p_capacity ? distance_pos - p_capacity : distance_pos;
  93. }
  94. bool _lookup_pos(const TKey &p_key, uint32_t &r_pos) const {
  95. return elements != nullptr && num_elements > 0 && _lookup_pos_unchecked(p_key, _hash(p_key), r_pos);
  96. }
  97. /// Note: Assumes that elements != nullptr
  98. bool _lookup_pos_unchecked(const TKey &p_key, uint32_t p_hash, uint32_t &r_pos) const {
  99. const uint32_t capacity = hash_table_size_primes[capacity_index];
  100. const uint64_t capacity_inv = hash_table_size_primes_inv[capacity_index];
  101. uint32_t pos = fastmod(p_hash, capacity_inv, capacity);
  102. uint32_t distance = 0;
  103. while (true) {
  104. if (hashes[pos] == EMPTY_HASH) {
  105. return false;
  106. }
  107. if (distance > _get_probe_length(pos, hashes[pos], capacity, capacity_inv)) {
  108. return false;
  109. }
  110. if (hashes[pos] == p_hash && Comparator::compare(elements[pos]->data.key, p_key)) {
  111. r_pos = pos;
  112. return true;
  113. }
  114. _increment_mod(pos, capacity);
  115. distance++;
  116. }
  117. }
  118. void _insert_element(uint32_t p_hash, HashMapElement<TKey, TValue> *p_value) {
  119. const uint32_t capacity = hash_table_size_primes[capacity_index];
  120. const uint64_t capacity_inv = hash_table_size_primes_inv[capacity_index];
  121. uint32_t hash = p_hash;
  122. HashMapElement<TKey, TValue> *value = p_value;
  123. uint32_t distance = 0;
  124. uint32_t pos = fastmod(hash, capacity_inv, capacity);
  125. while (true) {
  126. if (hashes[pos] == EMPTY_HASH) {
  127. elements[pos] = value;
  128. hashes[pos] = hash;
  129. num_elements++;
  130. return;
  131. }
  132. // Not an empty slot, let's check the probing length of the existing one.
  133. uint32_t existing_probe_len = _get_probe_length(pos, hashes[pos], capacity, capacity_inv);
  134. if (existing_probe_len < distance) {
  135. SWAP(hash, hashes[pos]);
  136. SWAP(value, elements[pos]);
  137. distance = existing_probe_len;
  138. }
  139. _increment_mod(pos, capacity);
  140. distance++;
  141. }
  142. }
  143. void _resize_and_rehash(uint32_t p_new_capacity_index) {
  144. uint32_t old_capacity = hash_table_size_primes[capacity_index];
  145. // Capacity can't be 0.
  146. capacity_index = MAX((uint32_t)MIN_CAPACITY_INDEX, p_new_capacity_index);
  147. uint32_t capacity = hash_table_size_primes[capacity_index];
  148. HashMapElement<TKey, TValue> **old_elements = elements;
  149. uint32_t *old_hashes = hashes;
  150. num_elements = 0;
  151. static_assert(EMPTY_HASH == 0, "Assuming EMPTY_HASH = 0 for alloc_static_zeroed call");
  152. hashes = reinterpret_cast<uint32_t *>(Memory::alloc_static_zeroed(sizeof(uint32_t) * capacity));
  153. elements = reinterpret_cast<HashMapElement<TKey, TValue> **>(Memory::alloc_static_zeroed(sizeof(HashMapElement<TKey, TValue> *) * capacity));
  154. if (old_capacity == 0) {
  155. // Nothing to do.
  156. return;
  157. }
  158. for (uint32_t i = 0; i < old_capacity; i++) {
  159. if (old_hashes[i] == EMPTY_HASH) {
  160. continue;
  161. }
  162. _insert_element(old_hashes[i], old_elements[i]);
  163. }
  164. Memory::free_static(old_elements);
  165. Memory::free_static(old_hashes);
  166. }
  167. _FORCE_INLINE_ HashMapElement<TKey, TValue> *_insert(const TKey &p_key, const TValue &p_value, uint32_t p_hash, bool p_front_insert = false) {
  168. uint32_t capacity = hash_table_size_primes[capacity_index];
  169. if (unlikely(elements == nullptr)) {
  170. // Allocate on demand to save memory.
  171. static_assert(EMPTY_HASH == 0, "Assuming EMPTY_HASH = 0 for alloc_static_zeroed call");
  172. hashes = reinterpret_cast<uint32_t *>(Memory::alloc_static_zeroed(sizeof(uint32_t) * capacity));
  173. elements = reinterpret_cast<HashMapElement<TKey, TValue> **>(Memory::alloc_static_zeroed(sizeof(HashMapElement<TKey, TValue> *) * capacity));
  174. }
  175. if (num_elements + 1 > MAX_OCCUPANCY * capacity) {
  176. ERR_FAIL_COND_V_MSG(capacity_index + 1 == HASH_TABLE_SIZE_MAX, nullptr, "Hash table maximum capacity reached, aborting insertion.");
  177. _resize_and_rehash(capacity_index + 1);
  178. }
  179. HashMapElement<TKey, TValue> *elem = Allocator::new_allocation(HashMapElement<TKey, TValue>(p_key, p_value));
  180. if (tail_element == nullptr) {
  181. head_element = elem;
  182. tail_element = elem;
  183. } else if (p_front_insert) {
  184. head_element->prev = elem;
  185. elem->next = head_element;
  186. head_element = elem;
  187. } else {
  188. tail_element->next = elem;
  189. elem->prev = tail_element;
  190. tail_element = elem;
  191. }
  192. _insert_element(p_hash, elem);
  193. return elem;
  194. }
  195. public:
  196. _FORCE_INLINE_ uint32_t get_capacity() const { return hash_table_size_primes[capacity_index]; }
  197. _FORCE_INLINE_ uint32_t size() const { return num_elements; }
  198. /* Standard Godot Container API */
  199. bool is_empty() const {
  200. return num_elements == 0;
  201. }
  202. void clear() {
  203. if (elements == nullptr || num_elements == 0) {
  204. return;
  205. }
  206. uint32_t capacity = hash_table_size_primes[capacity_index];
  207. for (uint32_t i = 0; i < capacity; i++) {
  208. if (hashes[i] == EMPTY_HASH) {
  209. continue;
  210. }
  211. hashes[i] = EMPTY_HASH;
  212. Allocator::delete_allocation(elements[i]);
  213. elements[i] = nullptr;
  214. }
  215. tail_element = nullptr;
  216. head_element = nullptr;
  217. num_elements = 0;
  218. }
  219. void sort() {
  220. if (elements == nullptr || num_elements < 2) {
  221. return; // An empty or single element HashMap is already sorted.
  222. }
  223. // Use insertion sort because we want this operation to be fast for the
  224. // common case where the input is already sorted or nearly sorted.
  225. HashMapElement<TKey, TValue> *inserting = head_element->next;
  226. while (inserting != nullptr) {
  227. HashMapElement<TKey, TValue> *after = nullptr;
  228. for (HashMapElement<TKey, TValue> *current = inserting->prev; current != nullptr; current = current->prev) {
  229. if (_hashmap_variant_less_than(inserting->data.key, current->data.key)) {
  230. after = current;
  231. } else {
  232. break;
  233. }
  234. }
  235. HashMapElement<TKey, TValue> *next = inserting->next;
  236. if (after != nullptr) {
  237. // Modify the elements around `inserting` to remove it from its current position.
  238. inserting->prev->next = next;
  239. if (next == nullptr) {
  240. tail_element = inserting->prev;
  241. } else {
  242. next->prev = inserting->prev;
  243. }
  244. // Modify `before` and `after` to insert `inserting` between them.
  245. HashMapElement<TKey, TValue> *before = after->prev;
  246. if (before == nullptr) {
  247. head_element = inserting;
  248. } else {
  249. before->next = inserting;
  250. }
  251. after->prev = inserting;
  252. // Point `inserting` to its new surroundings.
  253. inserting->prev = before;
  254. inserting->next = after;
  255. }
  256. inserting = next;
  257. }
  258. }
  259. TValue &get(const TKey &p_key) {
  260. uint32_t pos = 0;
  261. bool exists = _lookup_pos(p_key, pos);
  262. CRASH_COND_MSG(!exists, "HashMap key not found.");
  263. return elements[pos]->data.value;
  264. }
  265. const TValue &get(const TKey &p_key) const {
  266. uint32_t pos = 0;
  267. bool exists = _lookup_pos(p_key, pos);
  268. CRASH_COND_MSG(!exists, "HashMap key not found.");
  269. return elements[pos]->data.value;
  270. }
  271. const TValue *getptr(const TKey &p_key) const {
  272. uint32_t pos = 0;
  273. bool exists = _lookup_pos(p_key, pos);
  274. if (exists) {
  275. return &elements[pos]->data.value;
  276. }
  277. return nullptr;
  278. }
  279. TValue *getptr(const TKey &p_key) {
  280. uint32_t pos = 0;
  281. bool exists = _lookup_pos(p_key, pos);
  282. if (exists) {
  283. return &elements[pos]->data.value;
  284. }
  285. return nullptr;
  286. }
  287. _FORCE_INLINE_ bool has(const TKey &p_key) const {
  288. uint32_t _pos = 0;
  289. return _lookup_pos(p_key, _pos);
  290. }
  291. bool erase(const TKey &p_key) {
  292. uint32_t pos = 0;
  293. bool exists = _lookup_pos(p_key, pos);
  294. if (!exists) {
  295. return false;
  296. }
  297. const uint32_t capacity = hash_table_size_primes[capacity_index];
  298. const uint64_t capacity_inv = hash_table_size_primes_inv[capacity_index];
  299. uint32_t next_pos = fastmod((pos + 1), capacity_inv, capacity);
  300. while (hashes[next_pos] != EMPTY_HASH && _get_probe_length(next_pos, hashes[next_pos], capacity, capacity_inv) != 0) {
  301. SWAP(hashes[next_pos], hashes[pos]);
  302. SWAP(elements[next_pos], elements[pos]);
  303. pos = next_pos;
  304. _increment_mod(next_pos, capacity);
  305. }
  306. hashes[pos] = EMPTY_HASH;
  307. if (head_element == elements[pos]) {
  308. head_element = elements[pos]->next;
  309. }
  310. if (tail_element == elements[pos]) {
  311. tail_element = elements[pos]->prev;
  312. }
  313. if (elements[pos]->prev) {
  314. elements[pos]->prev->next = elements[pos]->next;
  315. }
  316. if (elements[pos]->next) {
  317. elements[pos]->next->prev = elements[pos]->prev;
  318. }
  319. Allocator::delete_allocation(elements[pos]);
  320. elements[pos] = nullptr;
  321. num_elements--;
  322. return true;
  323. }
  324. // Replace the key of an entry in-place, without invalidating iterators or changing the entries position during iteration.
  325. // p_old_key must exist in the map and p_new_key must not, unless it is equal to p_old_key.
  326. bool replace_key(const TKey &p_old_key, const TKey &p_new_key) {
  327. ERR_FAIL_COND_V(elements == nullptr || num_elements == 0, false);
  328. if (p_old_key == p_new_key) {
  329. return true;
  330. }
  331. const uint32_t new_hash = _hash(p_new_key);
  332. uint32_t pos = 0;
  333. ERR_FAIL_COND_V(_lookup_pos_unchecked(p_new_key, new_hash, pos), false);
  334. ERR_FAIL_COND_V(!_lookup_pos(p_old_key, pos), false);
  335. HashMapElement<TKey, TValue> *element = elements[pos];
  336. // Delete the old entries in hashes and elements.
  337. const uint32_t capacity = hash_table_size_primes[capacity_index];
  338. const uint64_t capacity_inv = hash_table_size_primes_inv[capacity_index];
  339. uint32_t next_pos = fastmod((pos + 1), capacity_inv, capacity);
  340. while (hashes[next_pos] != EMPTY_HASH && _get_probe_length(next_pos, hashes[next_pos], capacity, capacity_inv) != 0) {
  341. SWAP(hashes[next_pos], hashes[pos]);
  342. SWAP(elements[next_pos], elements[pos]);
  343. pos = next_pos;
  344. _increment_mod(next_pos, capacity);
  345. }
  346. hashes[pos] = EMPTY_HASH;
  347. elements[pos] = nullptr;
  348. // _insert_element will increment this again.
  349. num_elements--;
  350. // Update the HashMapElement with the new key and reinsert it.
  351. const_cast<TKey &>(element->data.key) = p_new_key;
  352. _insert_element(new_hash, element);
  353. return true;
  354. }
  355. // Reserves space for a number of elements, useful to avoid many resizes and rehashes.
  356. // If adding a known (possibly large) number of elements at once, must be larger than old capacity.
  357. void reserve(uint32_t p_new_capacity) {
  358. ERR_FAIL_COND_MSG(p_new_capacity < size(), "reserve() called with a capacity smaller than the current size. This is likely a mistake.");
  359. uint32_t new_index = capacity_index;
  360. while (hash_table_size_primes[new_index] < p_new_capacity) {
  361. ERR_FAIL_COND_MSG(new_index + 1 == (uint32_t)HASH_TABLE_SIZE_MAX, nullptr);
  362. new_index++;
  363. }
  364. if (new_index == capacity_index) {
  365. return;
  366. }
  367. if (elements == nullptr) {
  368. capacity_index = new_index;
  369. return; // Unallocated yet.
  370. }
  371. _resize_and_rehash(new_index);
  372. }
  373. /** Iterator API **/
  374. struct ConstIterator {
  375. _FORCE_INLINE_ const KeyValue<TKey, TValue> &operator*() const {
  376. return E->data;
  377. }
  378. _FORCE_INLINE_ const KeyValue<TKey, TValue> *operator->() const { return &E->data; }
  379. _FORCE_INLINE_ ConstIterator &operator++() {
  380. if (E) {
  381. E = E->next;
  382. }
  383. return *this;
  384. }
  385. _FORCE_INLINE_ ConstIterator &operator--() {
  386. if (E) {
  387. E = E->prev;
  388. }
  389. return *this;
  390. }
  391. _FORCE_INLINE_ bool operator==(const ConstIterator &b) const { return E == b.E; }
  392. _FORCE_INLINE_ bool operator!=(const ConstIterator &b) const { return E != b.E; }
  393. _FORCE_INLINE_ explicit operator bool() const {
  394. return E != nullptr;
  395. }
  396. _FORCE_INLINE_ ConstIterator(const HashMapElement<TKey, TValue> *p_E) { E = p_E; }
  397. _FORCE_INLINE_ ConstIterator() {}
  398. _FORCE_INLINE_ ConstIterator(const ConstIterator &p_it) { E = p_it.E; }
  399. _FORCE_INLINE_ void operator=(const ConstIterator &p_it) {
  400. E = p_it.E;
  401. }
  402. private:
  403. const HashMapElement<TKey, TValue> *E = nullptr;
  404. };
  405. struct Iterator {
  406. _FORCE_INLINE_ KeyValue<TKey, TValue> &operator*() const {
  407. return E->data;
  408. }
  409. _FORCE_INLINE_ KeyValue<TKey, TValue> *operator->() const { return &E->data; }
  410. _FORCE_INLINE_ Iterator &operator++() {
  411. if (E) {
  412. E = E->next;
  413. }
  414. return *this;
  415. }
  416. _FORCE_INLINE_ Iterator &operator--() {
  417. if (E) {
  418. E = E->prev;
  419. }
  420. return *this;
  421. }
  422. _FORCE_INLINE_ bool operator==(const Iterator &b) const { return E == b.E; }
  423. _FORCE_INLINE_ bool operator!=(const Iterator &b) const { return E != b.E; }
  424. _FORCE_INLINE_ explicit operator bool() const {
  425. return E != nullptr;
  426. }
  427. _FORCE_INLINE_ Iterator(HashMapElement<TKey, TValue> *p_E) { E = p_E; }
  428. _FORCE_INLINE_ Iterator() {}
  429. _FORCE_INLINE_ Iterator(const Iterator &p_it) { E = p_it.E; }
  430. _FORCE_INLINE_ void operator=(const Iterator &p_it) {
  431. E = p_it.E;
  432. }
  433. operator ConstIterator() const {
  434. return ConstIterator(E);
  435. }
  436. private:
  437. HashMapElement<TKey, TValue> *E = nullptr;
  438. };
  439. _FORCE_INLINE_ Iterator begin() {
  440. return Iterator(head_element);
  441. }
  442. _FORCE_INLINE_ Iterator end() {
  443. return Iterator(nullptr);
  444. }
  445. _FORCE_INLINE_ Iterator last() {
  446. return Iterator(tail_element);
  447. }
  448. _FORCE_INLINE_ Iterator find(const TKey &p_key) {
  449. uint32_t pos = 0;
  450. bool exists = _lookup_pos(p_key, pos);
  451. if (!exists) {
  452. return end();
  453. }
  454. return Iterator(elements[pos]);
  455. }
  456. _FORCE_INLINE_ void remove(const Iterator &p_iter) {
  457. if (p_iter) {
  458. erase(p_iter->key);
  459. }
  460. }
  461. _FORCE_INLINE_ ConstIterator begin() const {
  462. return ConstIterator(head_element);
  463. }
  464. _FORCE_INLINE_ ConstIterator end() const {
  465. return ConstIterator(nullptr);
  466. }
  467. _FORCE_INLINE_ ConstIterator last() const {
  468. return ConstIterator(tail_element);
  469. }
  470. _FORCE_INLINE_ ConstIterator find(const TKey &p_key) const {
  471. uint32_t pos = 0;
  472. bool exists = _lookup_pos(p_key, pos);
  473. if (!exists) {
  474. return end();
  475. }
  476. return ConstIterator(elements[pos]);
  477. }
  478. /* Indexing */
  479. const TValue &operator[](const TKey &p_key) const {
  480. uint32_t pos = 0;
  481. bool exists = _lookup_pos(p_key, pos);
  482. CRASH_COND(!exists);
  483. return elements[pos]->data.value;
  484. }
  485. TValue &operator[](const TKey &p_key) {
  486. const uint32_t hash = _hash(p_key);
  487. uint32_t pos = 0;
  488. bool exists = elements && num_elements > 0 && _lookup_pos_unchecked(p_key, hash, pos);
  489. if (!exists) {
  490. return _insert(p_key, TValue(), hash)->data.value;
  491. } else {
  492. return elements[pos]->data.value;
  493. }
  494. }
  495. /* Insert */
  496. Iterator insert(const TKey &p_key, const TValue &p_value, bool p_front_insert = false) {
  497. const uint32_t hash = _hash(p_key);
  498. uint32_t pos = 0;
  499. bool exists = elements && num_elements > 0 && _lookup_pos_unchecked(p_key, hash, pos);
  500. if (!exists) {
  501. return Iterator(_insert(p_key, p_value, hash, p_front_insert));
  502. } else {
  503. elements[pos]->data.value = p_value;
  504. return Iterator(elements[pos]);
  505. }
  506. }
  507. /* Constructors */
  508. HashMap(const HashMap &p_other) {
  509. reserve(hash_table_size_primes[p_other.capacity_index]);
  510. if (p_other.num_elements == 0) {
  511. return;
  512. }
  513. for (const KeyValue<TKey, TValue> &E : p_other) {
  514. insert(E.key, E.value);
  515. }
  516. }
  517. void operator=(const HashMap &p_other) {
  518. if (this == &p_other) {
  519. return; // Ignore self assignment.
  520. }
  521. if (num_elements != 0) {
  522. clear();
  523. }
  524. reserve(hash_table_size_primes[p_other.capacity_index]);
  525. if (p_other.elements == nullptr) {
  526. return; // Nothing to copy.
  527. }
  528. for (const KeyValue<TKey, TValue> &E : p_other) {
  529. insert(E.key, E.value);
  530. }
  531. }
  532. HashMap(uint32_t p_initial_capacity) {
  533. // Capacity can't be 0.
  534. capacity_index = 0;
  535. reserve(p_initial_capacity);
  536. }
  537. HashMap() {
  538. capacity_index = MIN_CAPACITY_INDEX;
  539. }
  540. HashMap(std::initializer_list<KeyValue<TKey, TValue>> p_init) {
  541. reserve(p_init.size());
  542. for (const KeyValue<TKey, TValue> &E : p_init) {
  543. insert(E.key, E.value);
  544. }
  545. }
  546. uint32_t debug_get_hash(uint32_t p_index) {
  547. if (num_elements == 0) {
  548. return 0;
  549. }
  550. ERR_FAIL_INDEX_V(p_index, get_capacity(), 0);
  551. return hashes[p_index];
  552. }
  553. Iterator debug_get_element(uint32_t p_index) {
  554. if (num_elements == 0) {
  555. return Iterator();
  556. }
  557. ERR_FAIL_INDEX_V(p_index, get_capacity(), Iterator());
  558. return Iterator(elements[p_index]);
  559. }
  560. ~HashMap() {
  561. clear();
  562. if (elements != nullptr) {
  563. Memory::free_static(elements);
  564. Memory::free_static(hashes);
  565. }
  566. }
  567. };