hash_map.h 15 KB

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