oa_hash_map.h 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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/hashfuncs.h"
  33. #include "core/math/math_funcs.h"
  34. #include "core/os/memory.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. template <class TKey, class TValue,
  49. class Hasher = HashMapHasherDefault,
  50. class Comparator = HashMapComparatorDefault<TKey>>
  51. class OAHashMap {
  52. private:
  53. TValue *values;
  54. TKey *keys;
  55. uint32_t *hashes;
  56. uint32_t capacity;
  57. uint32_t num_elements;
  58. static const uint32_t EMPTY_HASH = 0;
  59. _FORCE_INLINE_ uint32_t _hash(const TKey &p_key) const {
  60. uint32_t hash = Hasher::hash(p_key);
  61. if (hash == EMPTY_HASH) {
  62. hash = EMPTY_HASH + 1;
  63. }
  64. return hash;
  65. }
  66. _FORCE_INLINE_ uint32_t _get_probe_length(uint32_t p_pos, uint32_t p_hash) const {
  67. uint32_t original_pos = p_hash % capacity;
  68. return (p_pos - original_pos + capacity) % capacity;
  69. }
  70. _FORCE_INLINE_ void _construct(uint32_t p_pos, uint32_t p_hash, const TKey &p_key, const TValue &p_value) {
  71. memnew_placement(&keys[p_pos], TKey(p_key));
  72. memnew_placement(&values[p_pos], TValue(p_value));
  73. hashes[p_pos] = p_hash;
  74. num_elements++;
  75. }
  76. bool _lookup_pos(const TKey &p_key, uint32_t &r_pos) const {
  77. uint32_t hash = _hash(p_key);
  78. uint32_t pos = hash % capacity;
  79. uint32_t distance = 0;
  80. while (true) {
  81. if (hashes[pos] == EMPTY_HASH) {
  82. return false;
  83. }
  84. if (distance > _get_probe_length(pos, hashes[pos])) {
  85. return false;
  86. }
  87. if (hashes[pos] == hash && Comparator::compare(keys[pos], p_key)) {
  88. r_pos = pos;
  89. return true;
  90. }
  91. pos = (pos + 1) % capacity;
  92. distance++;
  93. }
  94. }
  95. void _insert_with_hash(uint32_t p_hash, const TKey &p_key, const TValue &p_value) {
  96. uint32_t hash = p_hash;
  97. uint32_t distance = 0;
  98. uint32_t pos = hash % capacity;
  99. TKey key = p_key;
  100. TValue value = p_value;
  101. while (true) {
  102. if (hashes[pos] == EMPTY_HASH) {
  103. _construct(pos, hash, key, value);
  104. return;
  105. }
  106. // not an empty slot, let's check the probing length of the existing one
  107. uint32_t existing_probe_len = _get_probe_length(pos, hashes[pos]);
  108. if (existing_probe_len < distance) {
  109. SWAP(hash, hashes[pos]);
  110. SWAP(key, keys[pos]);
  111. SWAP(value, values[pos]);
  112. distance = existing_probe_len;
  113. }
  114. pos = (pos + 1) % capacity;
  115. distance++;
  116. }
  117. }
  118. void _resize_and_rehash(uint32_t p_new_capacity) {
  119. uint32_t old_capacity = capacity;
  120. capacity = p_new_capacity;
  121. TKey *old_keys = keys;
  122. TValue *old_values = values;
  123. uint32_t *old_hashes = hashes;
  124. num_elements = 0;
  125. keys = static_cast<TKey *>(Memory::alloc_static(sizeof(TKey) * capacity));
  126. values = static_cast<TValue *>(Memory::alloc_static(sizeof(TValue) * capacity));
  127. hashes = static_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  128. for (uint32_t i = 0; i < capacity; i++) {
  129. hashes[i] = 0;
  130. }
  131. for (uint32_t i = 0; i < old_capacity; i++) {
  132. if (old_hashes[i] == EMPTY_HASH) {
  133. continue;
  134. }
  135. _insert_with_hash(old_hashes[i], old_keys[i], old_values[i]);
  136. old_keys[i].~TKey();
  137. old_values[i].~TValue();
  138. }
  139. Memory::free_static(old_keys);
  140. Memory::free_static(old_values);
  141. Memory::free_static(old_hashes);
  142. }
  143. void _resize_and_rehash() {
  144. _resize_and_rehash(capacity * 2);
  145. }
  146. public:
  147. _FORCE_INLINE_ uint32_t get_capacity() const { return capacity; }
  148. _FORCE_INLINE_ uint32_t get_num_elements() const { return num_elements; }
  149. bool empty() const {
  150. return num_elements == 0;
  151. }
  152. void clear() {
  153. for (uint32_t i = 0; i < capacity; i++) {
  154. if (hashes[i] == EMPTY_HASH) {
  155. continue;
  156. }
  157. hashes[i] = EMPTY_HASH;
  158. values[i].~TValue();
  159. keys[i].~TKey();
  160. }
  161. num_elements = 0;
  162. }
  163. void insert(const TKey &p_key, const TValue &p_value) {
  164. if (num_elements + 1 > 0.9 * capacity) {
  165. _resize_and_rehash();
  166. }
  167. uint32_t hash = _hash(p_key);
  168. _insert_with_hash(hash, p_key, p_value);
  169. }
  170. void set(const TKey &p_key, const TValue &p_data) {
  171. uint32_t pos = 0;
  172. bool exists = _lookup_pos(p_key, pos);
  173. if (exists) {
  174. values[pos] = p_data;
  175. } else {
  176. insert(p_key, p_data);
  177. }
  178. }
  179. /**
  180. * returns true if the value was found, false otherwise.
  181. *
  182. * if r_data is not NULL then the value will be written to the object
  183. * it points to.
  184. */
  185. bool lookup(const TKey &p_key, TValue &r_data) const {
  186. uint32_t pos = 0;
  187. bool exists = _lookup_pos(p_key, pos);
  188. if (exists) {
  189. r_data = values[pos];
  190. return true;
  191. }
  192. return false;
  193. }
  194. const TValue *lookup_ptr(const TKey &p_key) const {
  195. uint32_t pos = 0;
  196. bool exists = _lookup_pos(p_key, pos);
  197. if (exists) {
  198. return &values[pos];
  199. }
  200. return nullptr;
  201. }
  202. TValue *lookup_ptr(const TKey &p_key) {
  203. uint32_t pos = 0;
  204. bool exists = _lookup_pos(p_key, pos);
  205. if (exists) {
  206. return &values[pos];
  207. }
  208. return nullptr;
  209. }
  210. _FORCE_INLINE_ bool has(const TKey &p_key) const {
  211. uint32_t _pos = 0;
  212. return _lookup_pos(p_key, _pos);
  213. }
  214. void remove(const TKey &p_key) {
  215. uint32_t pos = 0;
  216. bool exists = _lookup_pos(p_key, pos);
  217. if (!exists) {
  218. return;
  219. }
  220. uint32_t next_pos = (pos + 1) % capacity;
  221. while (hashes[next_pos] != EMPTY_HASH &&
  222. _get_probe_length(next_pos, hashes[next_pos]) != 0) {
  223. SWAP(hashes[next_pos], hashes[pos]);
  224. SWAP(keys[next_pos], keys[pos]);
  225. SWAP(values[next_pos], values[pos]);
  226. pos = next_pos;
  227. next_pos = (pos + 1) % capacity;
  228. }
  229. hashes[pos] = EMPTY_HASH;
  230. values[pos].~TValue();
  231. keys[pos].~TKey();
  232. num_elements--;
  233. }
  234. /**
  235. * reserves space for a number of elements, useful to avoid many resizes and rehashes
  236. * if adding a known (possibly large) number of elements at once, must be larger than old
  237. * capacity.
  238. **/
  239. void reserve(uint32_t p_new_capacity) {
  240. ERR_FAIL_COND(p_new_capacity < capacity);
  241. _resize_and_rehash(p_new_capacity);
  242. }
  243. struct Iterator {
  244. bool valid;
  245. const TKey *key;
  246. TValue *value;
  247. private:
  248. uint32_t pos;
  249. friend class OAHashMap;
  250. };
  251. Iterator iter() const {
  252. Iterator it;
  253. it.valid = true;
  254. it.pos = 0;
  255. return next_iter(it);
  256. }
  257. Iterator next_iter(const Iterator &p_iter) const {
  258. if (!p_iter.valid) {
  259. return p_iter;
  260. }
  261. Iterator it;
  262. it.valid = false;
  263. it.pos = p_iter.pos;
  264. it.key = nullptr;
  265. it.value = nullptr;
  266. for (uint32_t i = it.pos; i < capacity; i++) {
  267. it.pos = i + 1;
  268. if (hashes[i] == EMPTY_HASH) {
  269. continue;
  270. }
  271. it.valid = true;
  272. it.key = &keys[i];
  273. it.value = &values[i];
  274. return it;
  275. }
  276. return it;
  277. }
  278. OAHashMap(const OAHashMap &) = delete; // Delete the copy constructor so we don't get unexpected copies and dangling pointers.
  279. OAHashMap &operator=(const OAHashMap &) = delete; // Same for assignment operator.
  280. OAHashMap(uint32_t p_initial_capacity = 64) {
  281. capacity = p_initial_capacity;
  282. num_elements = 0;
  283. keys = static_cast<TKey *>(Memory::alloc_static(sizeof(TKey) * capacity));
  284. values = static_cast<TValue *>(Memory::alloc_static(sizeof(TValue) * capacity));
  285. hashes = static_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  286. for (uint32_t i = 0; i < p_initial_capacity; i++) {
  287. hashes[i] = EMPTY_HASH;
  288. }
  289. }
  290. ~OAHashMap() {
  291. for (uint32_t i = 0; i < capacity; i++) {
  292. if (hashes[i] == EMPTY_HASH) {
  293. continue;
  294. }
  295. values[i].~TValue();
  296. keys[i].~TKey();
  297. }
  298. Memory::free_static(keys);
  299. Memory::free_static(values);
  300. Memory::free_static(hashes);
  301. }
  302. };
  303. #endif // OA_HASH_MAP_H