hash_map.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  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 "hashfuncs.h"
  33. #include "list.h"
  34. #include "math_funcs.h"
  35. #include "os/memory.h"
  36. #include "ustring.h"
  37. struct HashMapHasherDefault {
  38. static _FORCE_INLINE_ uint32_t hash(const String &p_string) { return p_string.hash(); }
  39. static _FORCE_INLINE_ uint32_t hash(const char *p_cstr) { return hash_djb2(p_cstr); }
  40. static _FORCE_INLINE_ uint32_t hash(const uint64_t p_int) { return hash_one_uint64(p_int); }
  41. static _FORCE_INLINE_ uint32_t hash(const int64_t p_int) { return hash(uint64_t(p_int)); }
  42. static _FORCE_INLINE_ uint32_t hash(const float p_float) { return hash_djb2_one_float(p_float); }
  43. static _FORCE_INLINE_ uint32_t hash(const double p_double) { return hash_djb2_one_float(p_double); }
  44. static _FORCE_INLINE_ uint32_t hash(const uint32_t p_int) { return p_int; }
  45. static _FORCE_INLINE_ uint32_t hash(const int32_t p_int) { return (uint32_t)p_int; }
  46. static _FORCE_INLINE_ uint32_t hash(const uint16_t p_int) { return p_int; }
  47. static _FORCE_INLINE_ uint32_t hash(const int16_t p_int) { return (uint32_t)p_int; }
  48. static _FORCE_INLINE_ uint32_t hash(const uint8_t p_int) { return p_int; }
  49. static _FORCE_INLINE_ uint32_t hash(const int8_t p_int) { return (uint32_t)p_int; }
  50. static _FORCE_INLINE_ uint32_t hash(const wchar_t p_wchar) { return (uint32_t)p_wchar; }
  51. //static _FORCE_INLINE_ uint32_t hash(const void* p_ptr) { return uint32_t(uint64_t(p_ptr))*(0x9e3779b1L); }
  52. };
  53. template <typename T>
  54. struct HashMapComparatorDefault {
  55. static bool compare(const T &p_lhs, const T &p_rhs) {
  56. return p_lhs == p_rhs;
  57. }
  58. bool compare(const float &p_lhs, const float &p_rhs) {
  59. return (p_lhs == p_rhs) || (Math::is_nan(p_lhs) && Math::is_nan(p_rhs));
  60. }
  61. bool compare(const double &p_lhs, const double &p_rhs) {
  62. return (p_lhs == p_rhs) || (Math::is_nan(p_lhs) && Math::is_nan(p_rhs));
  63. }
  64. };
  65. /**
  66. * @class HashMap
  67. * @author Juan Linietsky <reduzio@gmail.com>
  68. *
  69. * Implementation of a standard Hashing HashMap, for quick lookups of Data associated with a Key.
  70. * The implementation provides hashers for the default types, if you need a special kind of hasher, provide
  71. * your own.
  72. * @param TKey Key, search is based on it, needs to be hasheable. It is unique in this container.
  73. * @param TData Data, data associated with the key
  74. * @param Hasher Hasher object, needs to provide a valid static hash function for TKey
  75. * @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.
  76. * @param MIN_HASH_TABLE_POWER Miminum size of the hash table, as a power of two. You rarely need to change this parameter.
  77. * @param RELATIONSHIP Relationship at which the hash table is resized. if amount of elements is RELATIONSHIP
  78. * times bigger than the hash table, table is resized to solve this condition. if RELATIONSHIP is zero, table is always MIN_HASH_TABLE_POWER.
  79. *
  80. */
  81. template <class TKey, class TData, class Hasher = HashMapHasherDefault, class Comparator = HashMapComparatorDefault<TKey>, uint8_t MIN_HASH_TABLE_POWER = 3, uint8_t RELATIONSHIP = 8>
  82. class HashMap {
  83. public:
  84. struct Pair {
  85. TKey key;
  86. TData data;
  87. Pair() {}
  88. Pair(const TKey &p_key, const TData &p_data) {
  89. key = p_key;
  90. data = p_data;
  91. }
  92. };
  93. private:
  94. struct Entry {
  95. uint32_t hash;
  96. Entry *next;
  97. Pair pair;
  98. Entry() { next = 0; }
  99. };
  100. Entry **hash_table;
  101. uint8_t hash_table_power;
  102. uint32_t elements;
  103. void make_hash_table() {
  104. ERR_FAIL_COND(hash_table);
  105. hash_table = memnew_arr(Entry *, (1 << MIN_HASH_TABLE_POWER));
  106. hash_table_power = MIN_HASH_TABLE_POWER;
  107. elements = 0;
  108. for (int i = 0; i < (1 << MIN_HASH_TABLE_POWER); i++)
  109. hash_table[i] = 0;
  110. }
  111. void erase_hash_table() {
  112. ERR_FAIL_COND(elements);
  113. memdelete_arr(hash_table);
  114. hash_table = 0;
  115. hash_table_power = 0;
  116. elements = 0;
  117. }
  118. void check_hash_table() {
  119. int new_hash_table_power = -1;
  120. if ((int)elements > ((1 << hash_table_power) * RELATIONSHIP)) {
  121. /* rehash up */
  122. new_hash_table_power = hash_table_power + 1;
  123. while ((int)elements > ((1 << new_hash_table_power) * RELATIONSHIP)) {
  124. new_hash_table_power++;
  125. }
  126. } else if ((hash_table_power > (int)MIN_HASH_TABLE_POWER) && ((int)elements < ((1 << (hash_table_power - 1)) * RELATIONSHIP))) {
  127. /* rehash down */
  128. new_hash_table_power = hash_table_power - 1;
  129. while ((int)elements < ((1 << (new_hash_table_power - 1)) * RELATIONSHIP)) {
  130. new_hash_table_power--;
  131. }
  132. if (new_hash_table_power < (int)MIN_HASH_TABLE_POWER)
  133. new_hash_table_power = MIN_HASH_TABLE_POWER;
  134. }
  135. if (new_hash_table_power == -1)
  136. return;
  137. Entry **new_hash_table = memnew_arr(Entry *, (1 << new_hash_table_power));
  138. if (!new_hash_table) {
  139. ERR_PRINT("Out of Memory");
  140. return;
  141. }
  142. for (int i = 0; i < (1 << new_hash_table_power); i++) {
  143. new_hash_table[i] = 0;
  144. }
  145. for (int i = 0; i < (1 << hash_table_power); i++) {
  146. while (hash_table[i]) {
  147. Entry *se = hash_table[i];
  148. hash_table[i] = se->next;
  149. int new_pos = se->hash & ((1 << new_hash_table_power) - 1);
  150. se->next = new_hash_table[new_pos];
  151. new_hash_table[new_pos] = se;
  152. }
  153. }
  154. if (hash_table)
  155. memdelete_arr(hash_table);
  156. hash_table = new_hash_table;
  157. hash_table_power = new_hash_table_power;
  158. }
  159. /* I want to have only one function.. */
  160. _FORCE_INLINE_ const Entry *get_entry(const TKey &p_key) const {
  161. uint32_t hash = Hasher::hash(p_key);
  162. uint32_t index = hash & ((1 << hash_table_power) - 1);
  163. Entry *e = hash_table[index];
  164. while (e) {
  165. /* checking hash first avoids comparing key, which may take longer */
  166. if (e->hash == hash && Comparator::compare(e->pair.key, p_key)) {
  167. /* the pair exists in this hashtable, so just update data */
  168. return e;
  169. }
  170. e = e->next;
  171. }
  172. return NULL;
  173. }
  174. Entry *create_entry(const TKey &p_key) {
  175. /* if entry doesn't exist, create it */
  176. Entry *e = memnew(Entry);
  177. ERR_FAIL_COND_V(!e, NULL); /* out of memory */
  178. uint32_t hash = Hasher::hash(p_key);
  179. uint32_t index = hash & ((1 << hash_table_power) - 1);
  180. e->next = hash_table[index];
  181. e->hash = hash;
  182. e->pair.key = p_key;
  183. hash_table[index] = e;
  184. elements++;
  185. return e;
  186. }
  187. void copy_from(const HashMap &p_t) {
  188. if (&p_t == this)
  189. return; /* much less bother with that */
  190. clear();
  191. if (!p_t.hash_table || p_t.hash_table_power == 0)
  192. return; /* not copying from empty table */
  193. hash_table = memnew_arr(Entry *, 1 << p_t.hash_table_power);
  194. hash_table_power = p_t.hash_table_power;
  195. elements = p_t.elements;
  196. for (int i = 0; i < (1 << p_t.hash_table_power); i++) {
  197. hash_table[i] = NULL;
  198. /* elements will be in the reverse order, but it doesn't matter */
  199. const Entry *e = p_t.hash_table[i];
  200. while (e) {
  201. Entry *le = memnew(Entry); /* local entry */
  202. *le = *e; /* copy data */
  203. /* add to list and reassign pointers */
  204. le->next = hash_table[i];
  205. hash_table[i] = le;
  206. e = e->next;
  207. }
  208. }
  209. }
  210. public:
  211. void set(const TKey &p_key, const TData &p_data) {
  212. set(Pair(p_key, p_data));
  213. }
  214. void set(const Pair &p_pair) {
  215. Entry *e = NULL;
  216. if (!hash_table)
  217. make_hash_table(); // if no table, make one
  218. else
  219. e = const_cast<Entry *>(get_entry(p_pair.key));
  220. /* if we made it up to here, the pair doesn't exist, create and assign */
  221. if (!e) {
  222. e = create_entry(p_pair.key);
  223. if (!e)
  224. return;
  225. check_hash_table(); // perform mantenience routine
  226. }
  227. e->pair.data = p_pair.data;
  228. }
  229. bool has(const TKey &p_key) const {
  230. return getptr(p_key) != NULL;
  231. }
  232. /**
  233. * Get a key from data, return a const reference.
  234. * WARNING: this doesn't check errors, use either getptr and check NULL, or check
  235. * first with has(key)
  236. */
  237. const TData &get(const TKey &p_key) const {
  238. const TData *res = getptr(p_key);
  239. ERR_FAIL_COND_V(!res, *res);
  240. return *res;
  241. }
  242. TData &get(const TKey &p_key) {
  243. TData *res = getptr(p_key);
  244. ERR_FAIL_COND_V(!res, *res);
  245. return *res;
  246. }
  247. /**
  248. * Same as get, except it can return NULL when item was not found.
  249. * This is mainly used for speed purposes.
  250. */
  251. _FORCE_INLINE_ TData *getptr(const TKey &p_key) {
  252. if (!hash_table)
  253. return NULL;
  254. Entry *e = const_cast<Entry *>(get_entry(p_key));
  255. if (e)
  256. return &e->pair.data;
  257. return NULL;
  258. }
  259. _FORCE_INLINE_ const TData *getptr(const TKey &p_key) const {
  260. if (!hash_table)
  261. return NULL;
  262. const Entry *e = const_cast<Entry *>(get_entry(p_key));
  263. if (e)
  264. return &e->pair.data;
  265. return NULL;
  266. }
  267. /**
  268. * Same as get, except it can return NULL when item was not found.
  269. * This version is custom, will take a hash and a custom key (that should support operator==()
  270. */
  271. template <class C>
  272. _FORCE_INLINE_ TData *custom_getptr(C p_custom_key, uint32_t p_custom_hash) {
  273. if (!hash_table)
  274. return NULL;
  275. uint32_t hash = p_custom_hash;
  276. uint32_t index = hash & ((1 << hash_table_power) - 1);
  277. Entry *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 NULL;
  287. }
  288. template <class C>
  289. _FORCE_INLINE_ const TData *custom_getptr(C p_custom_key, uint32_t p_custom_hash) const {
  290. if (!hash_table)
  291. return NULL;
  292. uint32_t hash = p_custom_hash;
  293. uint32_t index = hash & ((1 << hash_table_power) - 1);
  294. const Entry *e = hash_table[index];
  295. while (e) {
  296. /* checking hash first avoids comparing key, which may take longer */
  297. if (e->hash == hash && Comparator::compare(e->pair.key, p_custom_key)) {
  298. /* the pair exists in this hashtable, so just update data */
  299. return &e->pair.data;
  300. }
  301. e = e->next;
  302. }
  303. return NULL;
  304. }
  305. /**
  306. * Erase an item, return true if erasing was succesful
  307. */
  308. bool erase(const TKey &p_key) {
  309. if (!hash_table)
  310. return false;
  311. uint32_t hash = Hasher::hash(p_key);
  312. uint32_t index = hash & ((1 << hash_table_power) - 1);
  313. Entry *e = hash_table[index];
  314. Entry *p = NULL;
  315. while (e) {
  316. /* checking hash first avoids comparing key, which may take longer */
  317. if (e->hash == hash && Comparator::compare(e->pair.key, p_key)) {
  318. if (p) {
  319. p->next = e->next;
  320. } else {
  321. //begin of list
  322. hash_table[index] = e->next;
  323. }
  324. memdelete(e);
  325. elements--;
  326. if (elements == 0)
  327. erase_hash_table();
  328. else
  329. check_hash_table();
  330. return true;
  331. }
  332. p = e;
  333. e = e->next;
  334. }
  335. return false;
  336. }
  337. inline const TData &operator[](const TKey &p_key) const { //constref
  338. return get(p_key);
  339. }
  340. inline TData &operator[](const TKey &p_key) { //assignment
  341. Entry *e = NULL;
  342. if (!hash_table)
  343. make_hash_table(); // if no table, make one
  344. else
  345. e = const_cast<Entry *>(get_entry(p_key));
  346. /* if we made it up to here, the pair doesn't exist, create */
  347. if (!e) {
  348. e = create_entry(p_key);
  349. PRAY_COND(!e, TData);
  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 (!hash_table) return NULL;
  371. if (!p_key) { /* get the first key */
  372. for (int i = 0; i < (1 << hash_table_power); i++) {
  373. if (hash_table[i]) {
  374. return &hash_table[i]->pair.key;
  375. }
  376. }
  377. } else { /* get the next key */
  378. const Entry *e = get_entry(*p_key);
  379. ERR_FAIL_COND_V(!e, NULL); /* invalid key supplied */
  380. if (e->next) {
  381. /* if there is a "next" in the list, return that */
  382. return &e->next->pair.key;
  383. } else {
  384. /* go to next entries */
  385. uint32_t index = e->hash & ((1 << hash_table_power) - 1);
  386. index++;
  387. for (int i = index; i < (1 << hash_table_power); i++) {
  388. if (hash_table[i]) {
  389. return &hash_table[i]->pair.key;
  390. }
  391. }
  392. }
  393. /* nothing found, was at end */
  394. }
  395. return NULL; /* nothing found */
  396. }
  397. inline unsigned int size() const {
  398. return elements;
  399. }
  400. inline bool empty() const {
  401. return elements == 0;
  402. }
  403. void clear() {
  404. /* clean up */
  405. if (hash_table) {
  406. for (int i = 0; i < (1 << hash_table_power); i++) {
  407. while (hash_table[i]) {
  408. Entry *e = hash_table[i];
  409. hash_table[i] = e->next;
  410. memdelete(e);
  411. }
  412. }
  413. memdelete_arr(hash_table);
  414. }
  415. hash_table = 0;
  416. hash_table_power = 0;
  417. elements = 0;
  418. }
  419. void operator=(const HashMap &p_table) {
  420. copy_from(p_table);
  421. }
  422. HashMap() {
  423. hash_table = NULL;
  424. elements = 0;
  425. hash_table_power = 0;
  426. }
  427. void get_key_list(List<TKey> *p_keys) const {
  428. if (!hash_table)
  429. return;
  430. for (int i = 0; i < (1 << hash_table_power); i++) {
  431. Entry *e = hash_table[i];
  432. while (e) {
  433. p_keys->push_back(e->pair.key);
  434. e = e->next;
  435. }
  436. }
  437. }
  438. HashMap(const HashMap &p_table) {
  439. hash_table = NULL;
  440. elements = 0;
  441. hash_table_power = 0;
  442. copy_from(p_table);
  443. }
  444. ~HashMap() {
  445. clear();
  446. }
  447. };
  448. #endif