hash_map.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. /*************************************************************************/
  2. /* hash_map.h */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
  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. #ifndef HASH_MAP_H
  31. #define HASH_MAP_H
  32. #include "core/error_macros.h"
  33. #include "core/hashfuncs.h"
  34. #include "core/list.h"
  35. #include "core/math/math_funcs.h"
  36. #include "core/os/memory.h"
  37. #include "core/ustring.h"
  38. /**
  39. * @class HashMap
  40. * @author Juan Linietsky <[email protected]>
  41. *
  42. * Implementation of a standard Hashing HashMap, for quick lookups of Data associated with a Key.
  43. * The implementation provides hashers for the default types, if you need a special kind of hasher, provide
  44. * your own.
  45. * @param TKey Key, search is based on it, needs to be hasheable. It is unique in this container.
  46. * @param TData Data, data associated with the key
  47. * @param Hasher Hasher object, needs to provide a valid static hash function for TKey
  48. * @param Comparator comparator object, needs to be able to safely compare two TKey values. It needs to ensure that x == x for any items inserted in the map. Bear in mind that nan != nan when implementing an equality check.
  49. * @param MIN_HASH_TABLE_POWER Miminum size of the hash table, as a power of two. You rarely need to change this parameter.
  50. * @param RELATIONSHIP Relationship at which the hash table is resized. if amount of elements is RELATIONSHIP
  51. * times bigger than the hash table, table is resized to solve this condition. if RELATIONSHIP is zero, table is always MIN_HASH_TABLE_POWER.
  52. *
  53. */
  54. template <class TKey, class TData, class Hasher = HashMapHasherDefault, class Comparator = HashMapComparatorDefault<TKey>, uint8_t MIN_HASH_TABLE_POWER = 3, uint8_t RELATIONSHIP = 8>
  55. class HashMap {
  56. public:
  57. struct Pair {
  58. TKey key;
  59. TData data;
  60. Pair() {}
  61. Pair(const TKey &p_key, const TData &p_data) :
  62. key(p_key),
  63. data(p_data) {
  64. }
  65. };
  66. struct Element {
  67. private:
  68. friend class HashMap;
  69. uint32_t hash;
  70. Element *next;
  71. Element() { next = nullptr; }
  72. Pair pair;
  73. public:
  74. const TKey &key() const {
  75. return pair.key;
  76. }
  77. TData &value() {
  78. return pair.data;
  79. }
  80. const TData &value() const {
  81. return pair.value();
  82. }
  83. };
  84. private:
  85. Element **hash_table;
  86. uint8_t hash_table_power;
  87. uint32_t elements;
  88. void make_hash_table() {
  89. ERR_FAIL_COND(hash_table);
  90. hash_table = memnew_arr(Element *, (1 << MIN_HASH_TABLE_POWER));
  91. hash_table_power = MIN_HASH_TABLE_POWER;
  92. elements = 0;
  93. for (int i = 0; i < (1 << MIN_HASH_TABLE_POWER); i++) {
  94. hash_table[i] = nullptr;
  95. }
  96. }
  97. void erase_hash_table() {
  98. ERR_FAIL_COND_MSG(elements, "Cannot erase hash table if there are still elements inside.");
  99. memdelete_arr(hash_table);
  100. hash_table = nullptr;
  101. hash_table_power = 0;
  102. elements = 0;
  103. }
  104. void check_hash_table() {
  105. int new_hash_table_power = -1;
  106. if ((int)elements > ((1 << hash_table_power) * RELATIONSHIP)) {
  107. /* rehash up */
  108. new_hash_table_power = hash_table_power + 1;
  109. while ((int)elements > ((1 << new_hash_table_power) * RELATIONSHIP)) {
  110. new_hash_table_power++;
  111. }
  112. } else if ((hash_table_power > (int)MIN_HASH_TABLE_POWER) && ((int)elements < ((1 << (hash_table_power - 1)) * RELATIONSHIP))) {
  113. /* rehash down */
  114. new_hash_table_power = hash_table_power - 1;
  115. while ((int)elements < ((1 << (new_hash_table_power - 1)) * RELATIONSHIP)) {
  116. new_hash_table_power--;
  117. }
  118. if (new_hash_table_power < (int)MIN_HASH_TABLE_POWER) {
  119. new_hash_table_power = MIN_HASH_TABLE_POWER;
  120. }
  121. }
  122. if (new_hash_table_power == -1) {
  123. return;
  124. }
  125. Element **new_hash_table = memnew_arr(Element *, ((uint64_t)1 << new_hash_table_power));
  126. ERR_FAIL_COND_MSG(!new_hash_table, "Out of memory.");
  127. for (int i = 0; i < (1 << new_hash_table_power); i++) {
  128. new_hash_table[i] = nullptr;
  129. }
  130. if (hash_table) {
  131. for (int i = 0; i < (1 << hash_table_power); i++) {
  132. while (hash_table[i]) {
  133. Element *se = hash_table[i];
  134. hash_table[i] = se->next;
  135. int new_pos = se->hash & ((1 << new_hash_table_power) - 1);
  136. se->next = new_hash_table[new_pos];
  137. new_hash_table[new_pos] = se;
  138. }
  139. }
  140. memdelete_arr(hash_table);
  141. }
  142. hash_table = new_hash_table;
  143. hash_table_power = new_hash_table_power;
  144. }
  145. /* I want to have only one function.. */
  146. _FORCE_INLINE_ const Element *get_element(const TKey &p_key) const {
  147. uint32_t hash = Hasher::hash(p_key);
  148. uint32_t index = hash & ((1 << hash_table_power) - 1);
  149. Element *e = hash_table[index];
  150. while (e) {
  151. /* checking hash first avoids comparing key, which may take longer */
  152. if (e->hash == hash && Comparator::compare(e->pair.key, p_key)) {
  153. /* the pair exists in this hashtable, so just update data */
  154. return e;
  155. }
  156. e = e->next;
  157. }
  158. return nullptr;
  159. }
  160. Element *create_element(const TKey &p_key) {
  161. /* if element doesn't exist, create it */
  162. Element *e = memnew(Element);
  163. ERR_FAIL_COND_V_MSG(!e, nullptr, "Out of memory.");
  164. uint32_t hash = Hasher::hash(p_key);
  165. uint32_t index = hash & ((1 << hash_table_power) - 1);
  166. e->next = hash_table[index];
  167. e->hash = hash;
  168. e->pair.key = p_key;
  169. e->pair.data = TData();
  170. hash_table[index] = e;
  171. elements++;
  172. return e;
  173. }
  174. void copy_from(const HashMap &p_t) {
  175. if (&p_t == this) {
  176. return; /* much less bother with that */
  177. }
  178. clear();
  179. if (!p_t.hash_table || p_t.hash_table_power == 0) {
  180. return; /* not copying from empty table */
  181. }
  182. hash_table = memnew_arr(Element *, (uint64_t)1 << p_t.hash_table_power);
  183. hash_table_power = p_t.hash_table_power;
  184. elements = p_t.elements;
  185. for (int i = 0; i < (1 << p_t.hash_table_power); i++) {
  186. hash_table[i] = nullptr;
  187. const Element *e = p_t.hash_table[i];
  188. while (e) {
  189. Element *le = memnew(Element); /* local element */
  190. *le = *e; /* copy data */
  191. /* add to list and reassign pointers */
  192. le->next = hash_table[i];
  193. hash_table[i] = le;
  194. e = e->next;
  195. }
  196. }
  197. }
  198. public:
  199. Element *set(const TKey &p_key, const TData &p_data) {
  200. return set(Pair(p_key, p_data));
  201. }
  202. Element *set(const Pair &p_pair) {
  203. Element *e = nullptr;
  204. if (!hash_table) {
  205. make_hash_table(); // if no table, make one
  206. } else {
  207. e = const_cast<Element *>(get_element(p_pair.key));
  208. }
  209. /* if we made it up to here, the pair doesn't exist, create and assign */
  210. if (!e) {
  211. e = create_element(p_pair.key);
  212. if (!e) {
  213. return nullptr;
  214. }
  215. check_hash_table(); // perform mantenience routine
  216. }
  217. e->pair.data = p_pair.data;
  218. return e;
  219. }
  220. bool has(const TKey &p_key) const {
  221. return getptr(p_key) != nullptr;
  222. }
  223. /**
  224. * Get a key from data, return a const reference.
  225. * WARNING: this doesn't check errors, use either getptr and check NULL, or check
  226. * first with has(key)
  227. */
  228. const TData &get(const TKey &p_key) const {
  229. const TData *res = getptr(p_key);
  230. CRASH_COND_MSG(!res, "Map key not found.");
  231. return *res;
  232. }
  233. TData &get(const TKey &p_key) {
  234. TData *res = getptr(p_key);
  235. CRASH_COND_MSG(!res, "Map key not found.");
  236. return *res;
  237. }
  238. /**
  239. * Same as get, except it can return NULL when item was not found.
  240. * This is mainly used for speed purposes.
  241. */
  242. _FORCE_INLINE_ TData *getptr(const TKey &p_key) {
  243. if (unlikely(!hash_table)) {
  244. return nullptr;
  245. }
  246. Element *e = const_cast<Element *>(get_element(p_key));
  247. if (e) {
  248. return &e->pair.data;
  249. }
  250. return nullptr;
  251. }
  252. _FORCE_INLINE_ const TData *getptr(const TKey &p_key) const {
  253. if (unlikely(!hash_table)) {
  254. return nullptr;
  255. }
  256. const Element *e = const_cast<Element *>(get_element(p_key));
  257. if (e) {
  258. return &e->pair.data;
  259. }
  260. return nullptr;
  261. }
  262. /**
  263. * Same as get, except it can return NULL when item was not found.
  264. * This version is custom, will take a hash and a custom key (that should support operator==()
  265. */
  266. template <class C>
  267. _FORCE_INLINE_ TData *custom_getptr(C p_custom_key, uint32_t p_custom_hash) {
  268. if (unlikely(!hash_table)) {
  269. return nullptr;
  270. }
  271. uint32_t hash = p_custom_hash;
  272. uint32_t index = hash & ((1 << hash_table_power) - 1);
  273. Element *e = hash_table[index];
  274. while (e) {
  275. /* checking hash first avoids comparing key, which may take longer */
  276. if (e->hash == hash && Comparator::compare(e->pair.key, p_custom_key)) {
  277. /* the pair exists in this hashtable, so just update data */
  278. return &e->pair.data;
  279. }
  280. e = e->next;
  281. }
  282. return nullptr;
  283. }
  284. template <class C>
  285. _FORCE_INLINE_ const TData *custom_getptr(C p_custom_key, uint32_t p_custom_hash) const {
  286. if (unlikely(!hash_table)) {
  287. return NULL;
  288. }
  289. uint32_t hash = p_custom_hash;
  290. uint32_t index = hash & ((1 << hash_table_power) - 1);
  291. const Element *e = hash_table[index];
  292. while (e) {
  293. /* checking hash first avoids comparing key, which may take longer */
  294. if (e->hash == hash && Comparator::compare(e->pair.key, p_custom_key)) {
  295. /* the pair exists in this hashtable, so just update data */
  296. return &e->pair.data;
  297. }
  298. e = e->next;
  299. }
  300. return NULL;
  301. }
  302. /**
  303. * Erase an item, return true if erasing was successful
  304. */
  305. bool erase(const TKey &p_key) {
  306. if (unlikely(!hash_table)) {
  307. return false;
  308. }
  309. uint32_t hash = Hasher::hash(p_key);
  310. uint32_t index = hash & ((1 << hash_table_power) - 1);
  311. Element *e = hash_table[index];
  312. Element *p = nullptr;
  313. while (e) {
  314. /* checking hash first avoids comparing key, which may take longer */
  315. if (e->hash == hash && Comparator::compare(e->pair.key, p_key)) {
  316. if (p) {
  317. p->next = e->next;
  318. } else {
  319. //begin of list
  320. hash_table[index] = e->next;
  321. }
  322. memdelete(e);
  323. elements--;
  324. if (elements == 0) {
  325. erase_hash_table();
  326. } else {
  327. check_hash_table();
  328. }
  329. return true;
  330. }
  331. p = e;
  332. e = e->next;
  333. }
  334. return false;
  335. }
  336. inline const TData &operator[](const TKey &p_key) const { //constref
  337. return get(p_key);
  338. }
  339. inline TData &operator[](const TKey &p_key) { //assignment
  340. Element *e = nullptr;
  341. if (!hash_table) {
  342. make_hash_table(); // if no table, make one
  343. } else {
  344. e = const_cast<Element *>(get_element(p_key));
  345. }
  346. /* if we made it up to here, the pair doesn't exist, create */
  347. if (!e) {
  348. e = create_element(p_key);
  349. CRASH_COND(!e);
  350. check_hash_table(); // perform mantenience routine
  351. }
  352. return e->pair.data;
  353. }
  354. /**
  355. * Get the next key to p_key, and the first key if p_key is null.
  356. * Returns a pointer to the next key if found, NULL otherwise.
  357. * Adding/Removing elements while iterating will, of course, have unexpected results, don't do it.
  358. *
  359. * Example:
  360. *
  361. * const TKey *k=NULL;
  362. *
  363. * while( (k=table.next(k)) ) {
  364. *
  365. * print( *k );
  366. * }
  367. *
  368. */
  369. const TKey *next(const TKey *p_key) const {
  370. if (unlikely(!hash_table)) {
  371. return nullptr;
  372. }
  373. if (!p_key) { /* get the first key */
  374. for (int i = 0; i < (1 << hash_table_power); i++) {
  375. if (hash_table[i]) {
  376. return &hash_table[i]->pair.key;
  377. }
  378. }
  379. } else { /* get the next key */
  380. const Element *e = get_element(*p_key);
  381. ERR_FAIL_COND_V_MSG(!e, nullptr, "Invalid key supplied.");
  382. if (e->next) {
  383. /* if there is a "next" in the list, return that */
  384. return &e->next->pair.key;
  385. } else {
  386. /* go to next elements */
  387. uint32_t index = e->hash & ((1 << hash_table_power) - 1);
  388. index++;
  389. for (int i = index; i < (1 << hash_table_power); i++) {
  390. if (hash_table[i]) {
  391. return &hash_table[i]->pair.key;
  392. }
  393. }
  394. }
  395. /* nothing found, was at end */
  396. }
  397. return nullptr; /* nothing found */
  398. }
  399. inline unsigned int size() const {
  400. return elements;
  401. }
  402. inline bool empty() const {
  403. return elements == 0;
  404. }
  405. void clear() {
  406. /* clean up */
  407. if (hash_table) {
  408. for (int i = 0; i < (1 << hash_table_power); i++) {
  409. while (hash_table[i]) {
  410. Element *e = hash_table[i];
  411. hash_table[i] = e->next;
  412. memdelete(e);
  413. }
  414. }
  415. memdelete_arr(hash_table);
  416. }
  417. hash_table = nullptr;
  418. hash_table_power = 0;
  419. elements = 0;
  420. }
  421. void operator=(const HashMap &p_table) {
  422. copy_from(p_table);
  423. }
  424. HashMap() {
  425. hash_table = nullptr;
  426. elements = 0;
  427. hash_table_power = 0;
  428. }
  429. void get_key_value_ptr_array(const Pair **p_pairs) const {
  430. if (unlikely(!hash_table)) {
  431. return;
  432. }
  433. for (int i = 0; i < (1 << hash_table_power); i++) {
  434. Element *e = hash_table[i];
  435. while (e) {
  436. *p_pairs = &e->pair;
  437. p_pairs++;
  438. e = e->next;
  439. }
  440. }
  441. }
  442. void get_key_list(List<TKey> *p_keys) const {
  443. if (unlikely(!hash_table)) {
  444. return;
  445. }
  446. for (int i = 0; i < (1 << hash_table_power); i++) {
  447. Element *e = hash_table[i];
  448. while (e) {
  449. p_keys->push_back(e->pair.key);
  450. e = e->next;
  451. }
  452. }
  453. }
  454. HashMap(const HashMap &p_table) {
  455. hash_table = nullptr;
  456. elements = 0;
  457. hash_table_power = 0;
  458. copy_from(p_table);
  459. }
  460. ~HashMap() {
  461. clear();
  462. }
  463. };
  464. #endif