oa_hash_map.h 10 KB

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