oa_hash_map.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. /**************************************************************************/
  2. /* oa_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 OA_HASH_MAP_H
  31. #define OA_HASH_MAP_H
  32. #include "core/math/math_funcs.h"
  33. #include "core/os/memory.h"
  34. #include "core/templates/hashfuncs.h"
  35. /**
  36. * A HashMap implementation that uses open addressing with Robin Hood hashing.
  37. * Robin Hood hashing swaps out entries that have a smaller probing distance
  38. * than the to-be-inserted entry, that evens out the average probing distance
  39. * and enables faster lookups. Backward shift deletion is employed to further
  40. * improve the performance and to avoid infinite loops in rare cases.
  41. *
  42. * The entries are stored inplace, so huge keys or values might fill cache lines
  43. * a lot faster.
  44. *
  45. * Only used keys and values are constructed. For free positions there's space
  46. * in the arrays for each, but that memory is kept uninitialized.
  47. *
  48. * The assignment operator copy the pairs from one map to the other.
  49. */
  50. template <typename TKey, typename TValue,
  51. typename Hasher = HashMapHasherDefault,
  52. typename Comparator = HashMapComparatorDefault<TKey>>
  53. class OAHashMap {
  54. private:
  55. TValue *values = nullptr;
  56. TKey *keys = nullptr;
  57. uint32_t *hashes = nullptr;
  58. uint32_t capacity = 0;
  59. uint32_t num_elements = 0;
  60. static const uint32_t EMPTY_HASH = 0;
  61. _FORCE_INLINE_ uint32_t _hash(const TKey &p_key) const {
  62. uint32_t hash = Hasher::hash(p_key);
  63. if (hash == EMPTY_HASH) {
  64. hash = EMPTY_HASH + 1;
  65. }
  66. return hash;
  67. }
  68. _FORCE_INLINE_ uint32_t _get_probe_length(uint32_t p_pos, uint32_t p_hash) const {
  69. uint32_t original_pos = p_hash % capacity;
  70. return (p_pos - original_pos + capacity) % capacity;
  71. }
  72. _FORCE_INLINE_ void _construct(uint32_t p_pos, uint32_t p_hash, const TKey &p_key, const TValue &p_value) {
  73. memnew_placement(&keys[p_pos], TKey(p_key));
  74. memnew_placement(&values[p_pos], TValue(p_value));
  75. hashes[p_pos] = p_hash;
  76. num_elements++;
  77. }
  78. bool _lookup_pos(const TKey &p_key, uint32_t &r_pos) const {
  79. uint32_t hash = _hash(p_key);
  80. uint32_t pos = hash % capacity;
  81. uint32_t distance = 0;
  82. while (true) {
  83. if (hashes[pos] == EMPTY_HASH) {
  84. return false;
  85. }
  86. if (distance > _get_probe_length(pos, hashes[pos])) {
  87. return false;
  88. }
  89. if (hashes[pos] == hash && Comparator::compare(keys[pos], p_key)) {
  90. r_pos = pos;
  91. return true;
  92. }
  93. pos = (pos + 1) % capacity;
  94. distance++;
  95. }
  96. }
  97. void _insert_with_hash(uint32_t p_hash, const TKey &p_key, const TValue &p_value) {
  98. uint32_t hash = p_hash;
  99. uint32_t distance = 0;
  100. uint32_t pos = hash % capacity;
  101. TKey key = p_key;
  102. TValue value = p_value;
  103. while (true) {
  104. if (hashes[pos] == EMPTY_HASH) {
  105. _construct(pos, hash, key, value);
  106. return;
  107. }
  108. // not an empty slot, let's check the probing length of the existing one
  109. uint32_t existing_probe_len = _get_probe_length(pos, hashes[pos]);
  110. if (existing_probe_len < distance) {
  111. SWAP(hash, hashes[pos]);
  112. SWAP(key, keys[pos]);
  113. SWAP(value, values[pos]);
  114. distance = existing_probe_len;
  115. }
  116. pos = (pos + 1) % capacity;
  117. distance++;
  118. }
  119. }
  120. void _resize_and_rehash(uint32_t p_new_capacity) {
  121. uint32_t old_capacity = capacity;
  122. // Capacity can't be 0.
  123. capacity = MAX(1u, p_new_capacity);
  124. TKey *old_keys = keys;
  125. TValue *old_values = values;
  126. uint32_t *old_hashes = hashes;
  127. num_elements = 0;
  128. keys = static_cast<TKey *>(Memory::alloc_static(sizeof(TKey) * capacity));
  129. values = static_cast<TValue *>(Memory::alloc_static(sizeof(TValue) * capacity));
  130. hashes = static_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  131. for (uint32_t i = 0; i < capacity; i++) {
  132. hashes[i] = 0;
  133. }
  134. if (old_capacity == 0) {
  135. // Nothing to do.
  136. return;
  137. }
  138. for (uint32_t i = 0; i < old_capacity; i++) {
  139. if (old_hashes[i] == EMPTY_HASH) {
  140. continue;
  141. }
  142. _insert_with_hash(old_hashes[i], old_keys[i], old_values[i]);
  143. old_keys[i].~TKey();
  144. old_values[i].~TValue();
  145. }
  146. Memory::free_static(old_keys);
  147. Memory::free_static(old_values);
  148. Memory::free_static(old_hashes);
  149. }
  150. void _resize_and_rehash() {
  151. _resize_and_rehash(capacity * 2);
  152. }
  153. public:
  154. _FORCE_INLINE_ uint32_t get_capacity() const { return capacity; }
  155. _FORCE_INLINE_ uint32_t get_num_elements() const { return num_elements; }
  156. bool is_empty() const {
  157. return num_elements == 0;
  158. }
  159. void clear() {
  160. for (uint32_t i = 0; i < capacity; i++) {
  161. if (hashes[i] == EMPTY_HASH) {
  162. continue;
  163. }
  164. hashes[i] = EMPTY_HASH;
  165. values[i].~TValue();
  166. keys[i].~TKey();
  167. }
  168. num_elements = 0;
  169. }
  170. void insert(const TKey &p_key, const TValue &p_value) {
  171. if (num_elements + 1 > 0.9 * capacity) {
  172. _resize_and_rehash();
  173. }
  174. uint32_t hash = _hash(p_key);
  175. _insert_with_hash(hash, p_key, p_value);
  176. }
  177. void set(const TKey &p_key, const TValue &p_data) {
  178. uint32_t pos = 0;
  179. bool exists = _lookup_pos(p_key, pos);
  180. if (exists) {
  181. values[pos] = p_data;
  182. } else {
  183. insert(p_key, p_data);
  184. }
  185. }
  186. /**
  187. * returns true if the value was found, false otherwise.
  188. *
  189. * if r_data is not nullptr then the value will be written to the object
  190. * it points to.
  191. */
  192. bool lookup(const TKey &p_key, TValue &r_data) const {
  193. uint32_t pos = 0;
  194. bool exists = _lookup_pos(p_key, pos);
  195. if (exists) {
  196. r_data = values[pos];
  197. return true;
  198. }
  199. return false;
  200. }
  201. const TValue *lookup_ptr(const TKey &p_key) const {
  202. uint32_t pos = 0;
  203. bool exists = _lookup_pos(p_key, pos);
  204. if (exists) {
  205. return &values[pos];
  206. }
  207. return nullptr;
  208. }
  209. TValue *lookup_ptr(const TKey &p_key) {
  210. uint32_t pos = 0;
  211. bool exists = _lookup_pos(p_key, pos);
  212. if (exists) {
  213. return &values[pos];
  214. }
  215. return nullptr;
  216. }
  217. _FORCE_INLINE_ bool has(const TKey &p_key) const {
  218. uint32_t _pos = 0;
  219. return _lookup_pos(p_key, _pos);
  220. }
  221. void remove(const TKey &p_key) {
  222. uint32_t pos = 0;
  223. bool exists = _lookup_pos(p_key, pos);
  224. if (!exists) {
  225. return;
  226. }
  227. uint32_t next_pos = (pos + 1) % capacity;
  228. while (hashes[next_pos] != EMPTY_HASH &&
  229. _get_probe_length(next_pos, hashes[next_pos]) != 0) {
  230. SWAP(hashes[next_pos], hashes[pos]);
  231. SWAP(keys[next_pos], keys[pos]);
  232. SWAP(values[next_pos], values[pos]);
  233. pos = next_pos;
  234. next_pos = (pos + 1) % capacity;
  235. }
  236. hashes[pos] = EMPTY_HASH;
  237. values[pos].~TValue();
  238. keys[pos].~TKey();
  239. num_elements--;
  240. }
  241. /**
  242. * reserves space for a number of elements, useful to avoid many resizes and rehashes
  243. * if adding a known (possibly large) number of elements at once, must be larger than old
  244. * capacity.
  245. **/
  246. void reserve(uint32_t p_new_capacity) {
  247. ERR_FAIL_COND(p_new_capacity < capacity);
  248. _resize_and_rehash(p_new_capacity);
  249. }
  250. struct Iterator {
  251. bool valid;
  252. const TKey *key;
  253. TValue *value = nullptr;
  254. private:
  255. uint32_t pos;
  256. friend class OAHashMap;
  257. };
  258. Iterator iter() const {
  259. Iterator it;
  260. it.valid = true;
  261. it.pos = 0;
  262. return next_iter(it);
  263. }
  264. Iterator next_iter(const Iterator &p_iter) const {
  265. if (!p_iter.valid) {
  266. return p_iter;
  267. }
  268. Iterator it;
  269. it.valid = false;
  270. it.pos = p_iter.pos;
  271. it.key = nullptr;
  272. it.value = nullptr;
  273. for (uint32_t i = it.pos; i < capacity; i++) {
  274. it.pos = i + 1;
  275. if (hashes[i] == EMPTY_HASH) {
  276. continue;
  277. }
  278. it.valid = true;
  279. it.key = &keys[i];
  280. it.value = &values[i];
  281. return it;
  282. }
  283. return it;
  284. }
  285. OAHashMap(const OAHashMap &p_other) {
  286. (*this) = p_other;
  287. }
  288. void operator=(const OAHashMap &p_other) {
  289. if (capacity != 0) {
  290. clear();
  291. }
  292. _resize_and_rehash(p_other.capacity);
  293. for (Iterator it = p_other.iter(); it.valid; it = p_other.next_iter(it)) {
  294. set(*it.key, *it.value);
  295. }
  296. }
  297. OAHashMap(uint32_t p_initial_capacity = 64) {
  298. // Capacity can't be 0.
  299. capacity = MAX(1u, p_initial_capacity);
  300. keys = static_cast<TKey *>(Memory::alloc_static(sizeof(TKey) * capacity));
  301. values = static_cast<TValue *>(Memory::alloc_static(sizeof(TValue) * capacity));
  302. hashes = static_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  303. for (uint32_t i = 0; i < capacity; i++) {
  304. hashes[i] = EMPTY_HASH;
  305. }
  306. }
  307. ~OAHashMap() {
  308. for (uint32_t i = 0; i < capacity; i++) {
  309. if (hashes[i] == EMPTY_HASH) {
  310. continue;
  311. }
  312. values[i].~TValue();
  313. keys[i].~TKey();
  314. }
  315. Memory::free_static(keys);
  316. Memory::free_static(values);
  317. Memory::free_static(hashes);
  318. }
  319. };
  320. #endif // OA_HASH_MAP_H