hash_map.h 14 KB

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