hash_map.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. /*************************************************************************/
  2. /* hash_map.h */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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 = nullptr;
  71. Element() {}
  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 = nullptr;
  86. uint8_t hash_table_power = 0;
  87. uint32_t elements = 0;
  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. void erase_hash_table() {
  97. ERR_FAIL_COND_MSG(elements, "Cannot erase hash table if there are still elements inside.");
  98. memdelete_arr(hash_table);
  99. hash_table = nullptr;
  100. hash_table_power = 0;
  101. elements = 0;
  102. }
  103. void check_hash_table() {
  104. int new_hash_table_power = -1;
  105. if ((int)elements > ((1 << hash_table_power) * RELATIONSHIP)) {
  106. /* rehash up */
  107. new_hash_table_power = hash_table_power + 1;
  108. while ((int)elements > ((1 << new_hash_table_power) * RELATIONSHIP)) {
  109. new_hash_table_power++;
  110. }
  111. } else if ((hash_table_power > (int)MIN_HASH_TABLE_POWER) && ((int)elements < ((1 << (hash_table_power - 1)) * RELATIONSHIP))) {
  112. /* rehash down */
  113. new_hash_table_power = hash_table_power - 1;
  114. while ((int)elements < ((1 << (new_hash_table_power - 1)) * RELATIONSHIP)) {
  115. new_hash_table_power--;
  116. }
  117. if (new_hash_table_power < (int)MIN_HASH_TABLE_POWER)
  118. new_hash_table_power = MIN_HASH_TABLE_POWER;
  119. }
  120. if (new_hash_table_power == -1)
  121. return;
  122. Element **new_hash_table = memnew_arr(Element *, ((uint64_t)1 << new_hash_table_power));
  123. ERR_FAIL_COND_MSG(!new_hash_table, "Out of memory.");
  124. for (int i = 0; i < (1 << new_hash_table_power); i++) {
  125. new_hash_table[i] = nullptr;
  126. }
  127. if (hash_table) {
  128. for (int i = 0; i < (1 << hash_table_power); i++) {
  129. while (hash_table[i]) {
  130. Element *se = hash_table[i];
  131. hash_table[i] = se->next;
  132. int new_pos = se->hash & ((1 << new_hash_table_power) - 1);
  133. se->next = new_hash_table[new_pos];
  134. new_hash_table[new_pos] = se;
  135. }
  136. }
  137. memdelete_arr(hash_table);
  138. }
  139. hash_table = new_hash_table;
  140. hash_table_power = new_hash_table_power;
  141. }
  142. /* I want to have only one function.. */
  143. _FORCE_INLINE_ const Element *get_element(const TKey &p_key) const {
  144. uint32_t hash = Hasher::hash(p_key);
  145. uint32_t index = hash & ((1 << hash_table_power) - 1);
  146. Element *e = hash_table[index];
  147. while (e) {
  148. /* checking hash first avoids comparing key, which may take longer */
  149. if (e->hash == hash && Comparator::compare(e->pair.key, p_key)) {
  150. /* the pair exists in this hashtable, so just update data */
  151. return e;
  152. }
  153. e = e->next;
  154. }
  155. return nullptr;
  156. }
  157. Element *create_element(const TKey &p_key) {
  158. /* if element doesn't exist, create it */
  159. Element *e = memnew(Element);
  160. ERR_FAIL_COND_V_MSG(!e, nullptr, "Out of memory.");
  161. uint32_t hash = Hasher::hash(p_key);
  162. uint32_t index = hash & ((1 << hash_table_power) - 1);
  163. e->next = hash_table[index];
  164. e->hash = hash;
  165. e->pair.key = p_key;
  166. e->pair.data = TData();
  167. hash_table[index] = e;
  168. elements++;
  169. return e;
  170. }
  171. void copy_from(const HashMap &p_t) {
  172. if (&p_t == this)
  173. return; /* much less bother with that */
  174. clear();
  175. if (!p_t.hash_table || p_t.hash_table_power == 0)
  176. return; /* not copying from empty table */
  177. hash_table = memnew_arr(Element *, (uint64_t)1 << p_t.hash_table_power);
  178. hash_table_power = p_t.hash_table_power;
  179. elements = p_t.elements;
  180. for (int i = 0; i < (1 << p_t.hash_table_power); i++) {
  181. hash_table[i] = nullptr;
  182. const Element *e = p_t.hash_table[i];
  183. while (e) {
  184. Element *le = memnew(Element); /* local element */
  185. *le = *e; /* copy data */
  186. /* add to list and reassign pointers */
  187. le->next = hash_table[i];
  188. hash_table[i] = le;
  189. e = e->next;
  190. }
  191. }
  192. }
  193. public:
  194. Element *set(const TKey &p_key, const TData &p_data) {
  195. return set(Pair(p_key, p_data));
  196. }
  197. Element *set(const Pair &p_pair) {
  198. Element *e = nullptr;
  199. if (!hash_table)
  200. make_hash_table(); // if no table, make one
  201. else
  202. e = const_cast<Element *>(get_element(p_pair.key));
  203. /* if we made it up to here, the pair doesn't exist, create and assign */
  204. if (!e) {
  205. e = create_element(p_pair.key);
  206. if (!e)
  207. return nullptr;
  208. check_hash_table(); // perform mantenience routine
  209. }
  210. e->pair.data = p_pair.data;
  211. return e;
  212. }
  213. bool has(const TKey &p_key) const {
  214. return getptr(p_key) != nullptr;
  215. }
  216. /**
  217. * Get a key from data, return a const reference.
  218. * WARNING: this doesn't check errors, use either getptr and check nullptr, or check
  219. * first with has(key)
  220. */
  221. const TData &get(const TKey &p_key) const {
  222. const TData *res = getptr(p_key);
  223. ERR_FAIL_COND_V(!res, *res);
  224. return *res;
  225. }
  226. TData &get(const TKey &p_key) {
  227. TData *res = getptr(p_key);
  228. ERR_FAIL_COND_V(!res, *res);
  229. return *res;
  230. }
  231. /**
  232. * Same as get, except it can return nullptr when item was not found.
  233. * This is mainly used for speed purposes.
  234. */
  235. _FORCE_INLINE_ TData *getptr(const TKey &p_key) {
  236. if (unlikely(!hash_table))
  237. return nullptr;
  238. Element *e = const_cast<Element *>(get_element(p_key));
  239. if (e)
  240. return &e->pair.data;
  241. return nullptr;
  242. }
  243. _FORCE_INLINE_ const TData *getptr(const TKey &p_key) const {
  244. if (unlikely(!hash_table))
  245. return nullptr;
  246. const Element *e = const_cast<Element *>(get_element(p_key));
  247. if (e)
  248. return &e->pair.data;
  249. return nullptr;
  250. }
  251. /**
  252. * Same as get, except it can return nullptr when item was not found.
  253. * This version is custom, will take a hash and a custom key (that should support operator==()
  254. */
  255. template <class C>
  256. _FORCE_INLINE_ TData *custom_getptr(C p_custom_key, uint32_t p_custom_hash) {
  257. if (unlikely(!hash_table))
  258. return nullptr;
  259. uint32_t hash = p_custom_hash;
  260. uint32_t index = hash & ((1 << hash_table_power) - 1);
  261. Element *e = hash_table[index];
  262. while (e) {
  263. /* checking hash first avoids comparing key, which may take longer */
  264. if (e->hash == hash && Comparator::compare(e->pair.key, p_custom_key)) {
  265. /* the pair exists in this hashtable, so just update data */
  266. return &e->pair.data;
  267. }
  268. e = e->next;
  269. }
  270. return nullptr;
  271. }
  272. template <class C>
  273. _FORCE_INLINE_ const TData *custom_getptr(C p_custom_key, uint32_t p_custom_hash) const {
  274. if (unlikely(!hash_table))
  275. return nullptr;
  276. uint32_t hash = p_custom_hash;
  277. uint32_t index = hash & ((1 << hash_table_power) - 1);
  278. const Element *e = hash_table[index];
  279. while (e) {
  280. /* checking hash first avoids comparing key, which may take longer */
  281. if (e->hash == hash && Comparator::compare(e->pair.key, p_custom_key)) {
  282. /* the pair exists in this hashtable, so just update data */
  283. return &e->pair.data;
  284. }
  285. e = e->next;
  286. }
  287. return nullptr;
  288. }
  289. /**
  290. * Erase an item, return true if erasing was successful
  291. */
  292. bool erase(const TKey &p_key) {
  293. if (unlikely(!hash_table))
  294. return false;
  295. uint32_t hash = Hasher::hash(p_key);
  296. uint32_t index = hash & ((1 << hash_table_power) - 1);
  297. Element *e = hash_table[index];
  298. Element *p = nullptr;
  299. while (e) {
  300. /* checking hash first avoids comparing key, which may take longer */
  301. if (e->hash == hash && Comparator::compare(e->pair.key, p_key)) {
  302. if (p) {
  303. p->next = e->next;
  304. } else {
  305. //begin of list
  306. hash_table[index] = e->next;
  307. }
  308. memdelete(e);
  309. elements--;
  310. if (elements == 0)
  311. erase_hash_table();
  312. else
  313. check_hash_table();
  314. return true;
  315. }
  316. p = e;
  317. e = e->next;
  318. }
  319. return false;
  320. }
  321. inline const TData &operator[](const TKey &p_key) const { //constref
  322. return get(p_key);
  323. }
  324. inline TData &operator[](const TKey &p_key) { //assignment
  325. Element *e = nullptr;
  326. if (!hash_table)
  327. make_hash_table(); // if no table, make one
  328. else
  329. e = const_cast<Element *>(get_element(p_key));
  330. /* if we made it up to here, the pair doesn't exist, create */
  331. if (!e) {
  332. e = create_element(p_key);
  333. CRASH_COND(!e);
  334. check_hash_table(); // perform mantenience routine
  335. }
  336. return e->pair.data;
  337. }
  338. /**
  339. * Get the next key to p_key, and the first key if p_key is null.
  340. * Returns a pointer to the next key if found, nullptr otherwise.
  341. * Adding/Removing elements while iterating will, of course, have unexpected results, don't do it.
  342. *
  343. * Example:
  344. *
  345. * const TKey *k=nullptr;
  346. *
  347. * while( (k=table.next(k)) ) {
  348. *
  349. * print( *k );
  350. * }
  351. *
  352. */
  353. const TKey *next(const TKey *p_key) const {
  354. if (unlikely(!hash_table))
  355. return nullptr;
  356. if (!p_key) { /* get the first key */
  357. for (int i = 0; i < (1 << hash_table_power); i++) {
  358. if (hash_table[i]) {
  359. return &hash_table[i]->pair.key;
  360. }
  361. }
  362. } else { /* get the next key */
  363. const Element *e = get_element(*p_key);
  364. ERR_FAIL_COND_V_MSG(!e, nullptr, "Invalid key supplied.");
  365. if (e->next) {
  366. /* if there is a "next" in the list, return that */
  367. return &e->next->pair.key;
  368. } else {
  369. /* go to next elements */
  370. uint32_t index = e->hash & ((1 << hash_table_power) - 1);
  371. index++;
  372. for (int i = index; i < (1 << hash_table_power); i++) {
  373. if (hash_table[i]) {
  374. return &hash_table[i]->pair.key;
  375. }
  376. }
  377. }
  378. /* nothing found, was at end */
  379. }
  380. return nullptr; /* nothing found */
  381. }
  382. inline unsigned int size() const {
  383. return elements;
  384. }
  385. inline bool empty() const {
  386. return elements == 0;
  387. }
  388. void clear() {
  389. /* clean up */
  390. if (hash_table) {
  391. for (int i = 0; i < (1 << hash_table_power); i++) {
  392. while (hash_table[i]) {
  393. Element *e = hash_table[i];
  394. hash_table[i] = e->next;
  395. memdelete(e);
  396. }
  397. }
  398. memdelete_arr(hash_table);
  399. }
  400. hash_table = nullptr;
  401. hash_table_power = 0;
  402. elements = 0;
  403. }
  404. void operator=(const HashMap &p_table) {
  405. copy_from(p_table);
  406. }
  407. void get_key_value_ptr_array(const Pair **p_pairs) const {
  408. if (unlikely(!hash_table))
  409. return;
  410. for (int i = 0; i < (1 << hash_table_power); i++) {
  411. Element *e = hash_table[i];
  412. while (e) {
  413. *p_pairs = &e->pair;
  414. p_pairs++;
  415. e = e->next;
  416. }
  417. }
  418. }
  419. void get_key_list(List<TKey> *p_keys) const {
  420. if (unlikely(!hash_table))
  421. return;
  422. for (int i = 0; i < (1 << hash_table_power); i++) {
  423. Element *e = hash_table[i];
  424. while (e) {
  425. p_keys->push_back(e->pair.key);
  426. e = e->next;
  427. }
  428. }
  429. }
  430. HashMap() {}
  431. HashMap(const HashMap &p_table) {
  432. copy_from(p_table);
  433. }
  434. ~HashMap() {
  435. clear();
  436. }
  437. };
  438. #endif // HASH_MAP_H