hash_set.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. /**************************************************************************/
  2. /* hash_set.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_SET_H
  31. #define HASH_SET_H
  32. #include "core/math/math_funcs.h"
  33. #include "core/os/memory.h"
  34. #include "core/templates/hash_map.h"
  35. #include "core/templates/hashfuncs.h"
  36. #include "core/templates/paged_allocator.h"
  37. /**
  38. * Implementation of Set using a bidi indexed hash map.
  39. * Use RBSet instead of this only if the following conditions are met:
  40. *
  41. * - You need to keep an iterator or const pointer to Key and you intend to add/remove elements in the meantime.
  42. * - Iteration order does matter (via operator<)
  43. *
  44. */
  45. template <class TKey,
  46. class Hasher = HashMapHasherDefault,
  47. class Comparator = HashMapComparatorDefault<TKey>>
  48. class HashSet {
  49. public:
  50. static constexpr uint32_t MIN_CAPACITY_INDEX = 2; // Use a prime.
  51. static constexpr float MAX_OCCUPANCY = 0.75;
  52. static constexpr uint32_t EMPTY_HASH = 0;
  53. private:
  54. TKey *keys = nullptr;
  55. uint32_t *hash_to_key = nullptr;
  56. uint32_t *key_to_hash = nullptr;
  57. uint32_t *hashes = nullptr;
  58. uint32_t capacity_index = 0;
  59. uint32_t num_elements = 0;
  60. _FORCE_INLINE_ uint32_t _hash(const TKey &p_key) const {
  61. uint32_t hash = Hasher::hash(p_key);
  62. if (unlikely(hash == EMPTY_HASH)) {
  63. hash = EMPTY_HASH + 1;
  64. }
  65. return hash;
  66. }
  67. static _FORCE_INLINE_ uint32_t _get_probe_length(const uint32_t p_pos, const uint32_t p_hash, const uint32_t p_capacity, const uint64_t p_capacity_inv) {
  68. const uint32_t original_pos = fastmod(p_hash, p_capacity_inv, p_capacity);
  69. return fastmod(p_pos - original_pos + p_capacity, p_capacity_inv, p_capacity);
  70. }
  71. bool _lookup_pos(const TKey &p_key, uint32_t &r_pos) const {
  72. if (keys == nullptr || num_elements == 0) {
  73. return false; // Failed lookups, no elements
  74. }
  75. const uint32_t capacity = hash_table_size_primes[capacity_index];
  76. const uint64_t capacity_inv = hash_table_size_primes_inv[capacity_index];
  77. uint32_t hash = _hash(p_key);
  78. uint32_t pos = fastmod(hash, capacity_inv, 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], capacity, capacity_inv)) {
  85. return false;
  86. }
  87. if (hashes[pos] == hash && Comparator::compare(keys[hash_to_key[pos]], p_key)) {
  88. r_pos = hash_to_key[pos];
  89. return true;
  90. }
  91. pos = fastmod(pos + 1, capacity_inv, capacity);
  92. distance++;
  93. }
  94. }
  95. uint32_t _insert_with_hash(uint32_t p_hash, uint32_t p_index) {
  96. const uint32_t capacity = hash_table_size_primes[capacity_index];
  97. const uint64_t capacity_inv = hash_table_size_primes_inv[capacity_index];
  98. uint32_t hash = p_hash;
  99. uint32_t index = p_index;
  100. uint32_t distance = 0;
  101. uint32_t pos = fastmod(hash, capacity_inv, capacity);
  102. while (true) {
  103. if (hashes[pos] == EMPTY_HASH) {
  104. hashes[pos] = hash;
  105. key_to_hash[index] = pos;
  106. hash_to_key[pos] = index;
  107. return pos;
  108. }
  109. // Not an empty slot, let's check the probing length of the existing one.
  110. uint32_t existing_probe_len = _get_probe_length(pos, hashes[pos], capacity, capacity_inv);
  111. if (existing_probe_len < distance) {
  112. key_to_hash[index] = pos;
  113. SWAP(hash, hashes[pos]);
  114. SWAP(index, hash_to_key[pos]);
  115. distance = existing_probe_len;
  116. }
  117. pos = fastmod(pos + 1, capacity_inv, capacity);
  118. distance++;
  119. }
  120. }
  121. void _resize_and_rehash(uint32_t p_new_capacity_index) {
  122. // Capacity can't be 0.
  123. capacity_index = MAX((uint32_t)MIN_CAPACITY_INDEX, p_new_capacity_index);
  124. uint32_t capacity = hash_table_size_primes[capacity_index];
  125. uint32_t *old_hashes = hashes;
  126. uint32_t *old_key_to_hash = key_to_hash;
  127. hashes = reinterpret_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  128. keys = reinterpret_cast<TKey *>(Memory::realloc_static(keys, sizeof(TKey) * capacity));
  129. key_to_hash = reinterpret_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  130. hash_to_key = reinterpret_cast<uint32_t *>(Memory::realloc_static(hash_to_key, sizeof(uint32_t) * capacity));
  131. for (uint32_t i = 0; i < capacity; i++) {
  132. hashes[i] = EMPTY_HASH;
  133. }
  134. for (uint32_t i = 0; i < num_elements; i++) {
  135. uint32_t h = old_hashes[old_key_to_hash[i]];
  136. _insert_with_hash(h, i);
  137. }
  138. Memory::free_static(old_hashes);
  139. Memory::free_static(old_key_to_hash);
  140. }
  141. _FORCE_INLINE_ int32_t _insert(const TKey &p_key) {
  142. uint32_t capacity = hash_table_size_primes[capacity_index];
  143. if (unlikely(keys == nullptr)) {
  144. // Allocate on demand to save memory.
  145. hashes = reinterpret_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  146. keys = reinterpret_cast<TKey *>(Memory::alloc_static(sizeof(TKey) * capacity));
  147. key_to_hash = reinterpret_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  148. hash_to_key = reinterpret_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  149. for (uint32_t i = 0; i < capacity; i++) {
  150. hashes[i] = EMPTY_HASH;
  151. }
  152. }
  153. uint32_t pos = 0;
  154. bool exists = _lookup_pos(p_key, pos);
  155. if (exists) {
  156. return pos;
  157. } else {
  158. if (num_elements + 1 > MAX_OCCUPANCY * capacity) {
  159. ERR_FAIL_COND_V_MSG(capacity_index + 1 == HASH_TABLE_SIZE_MAX, -1, "Hash table maximum capacity reached, aborting insertion.");
  160. _resize_and_rehash(capacity_index + 1);
  161. }
  162. uint32_t hash = _hash(p_key);
  163. memnew_placement(&keys[num_elements], TKey(p_key));
  164. _insert_with_hash(hash, num_elements);
  165. num_elements++;
  166. return num_elements - 1;
  167. }
  168. }
  169. void _init_from(const HashSet &p_other) {
  170. capacity_index = p_other.capacity_index;
  171. num_elements = p_other.num_elements;
  172. if (p_other.num_elements == 0) {
  173. return;
  174. }
  175. uint32_t capacity = hash_table_size_primes[capacity_index];
  176. hashes = reinterpret_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  177. keys = reinterpret_cast<TKey *>(Memory::alloc_static(sizeof(TKey) * capacity));
  178. key_to_hash = reinterpret_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  179. hash_to_key = reinterpret_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  180. for (uint32_t i = 0; i < num_elements; i++) {
  181. memnew_placement(&keys[i], TKey(p_other.keys[i]));
  182. key_to_hash[i] = p_other.key_to_hash[i];
  183. }
  184. for (uint32_t i = 0; i < capacity; i++) {
  185. hashes[i] = p_other.hashes[i];
  186. hash_to_key[i] = p_other.hash_to_key[i];
  187. }
  188. }
  189. public:
  190. _FORCE_INLINE_ uint32_t get_capacity() const { return hash_table_size_primes[capacity_index]; }
  191. _FORCE_INLINE_ uint32_t size() const { return num_elements; }
  192. /* Standard Godot Container API */
  193. bool is_empty() const {
  194. return num_elements == 0;
  195. }
  196. void clear() {
  197. if (keys == nullptr || num_elements == 0) {
  198. return;
  199. }
  200. uint32_t capacity = hash_table_size_primes[capacity_index];
  201. for (uint32_t i = 0; i < capacity; i++) {
  202. hashes[i] = EMPTY_HASH;
  203. }
  204. for (uint32_t i = 0; i < num_elements; i++) {
  205. keys[i].~TKey();
  206. }
  207. num_elements = 0;
  208. }
  209. _FORCE_INLINE_ bool has(const TKey &p_key) const {
  210. uint32_t _pos = 0;
  211. return _lookup_pos(p_key, _pos);
  212. }
  213. bool erase(const TKey &p_key) {
  214. uint32_t pos = 0;
  215. bool exists = _lookup_pos(p_key, pos);
  216. if (!exists) {
  217. return false;
  218. }
  219. uint32_t key_pos = pos;
  220. pos = key_to_hash[pos]; //make hash pos
  221. const uint32_t capacity = hash_table_size_primes[capacity_index];
  222. const uint64_t capacity_inv = hash_table_size_primes_inv[capacity_index];
  223. uint32_t next_pos = fastmod(pos + 1, capacity_inv, capacity);
  224. while (hashes[next_pos] != EMPTY_HASH && _get_probe_length(next_pos, hashes[next_pos], capacity, capacity_inv) != 0) {
  225. uint32_t kpos = hash_to_key[pos];
  226. uint32_t kpos_next = hash_to_key[next_pos];
  227. SWAP(key_to_hash[kpos], key_to_hash[kpos_next]);
  228. SWAP(hashes[next_pos], hashes[pos]);
  229. SWAP(hash_to_key[next_pos], hash_to_key[pos]);
  230. pos = next_pos;
  231. next_pos = fastmod(pos + 1, capacity_inv, capacity);
  232. }
  233. hashes[pos] = EMPTY_HASH;
  234. keys[key_pos].~TKey();
  235. num_elements--;
  236. if (key_pos < num_elements) {
  237. // Not the last key, move the last one here to keep keys lineal
  238. memnew_placement(&keys[key_pos], TKey(keys[num_elements]));
  239. keys[num_elements].~TKey();
  240. key_to_hash[key_pos] = key_to_hash[num_elements];
  241. hash_to_key[key_to_hash[num_elements]] = key_pos;
  242. }
  243. return true;
  244. }
  245. // Reserves space for a number of elements, useful to avoid many resizes and rehashes.
  246. // If adding a known (possibly large) number of elements at once, must be larger than old capacity.
  247. void reserve(uint32_t p_new_capacity) {
  248. uint32_t new_index = capacity_index;
  249. while (hash_table_size_primes[new_index] < p_new_capacity) {
  250. ERR_FAIL_COND_MSG(new_index + 1 == (uint32_t)HASH_TABLE_SIZE_MAX, nullptr);
  251. new_index++;
  252. }
  253. if (new_index == capacity_index) {
  254. return;
  255. }
  256. if (keys == nullptr) {
  257. capacity_index = new_index;
  258. return; // Unallocated yet.
  259. }
  260. _resize_and_rehash(new_index);
  261. }
  262. /** Iterator API **/
  263. struct Iterator {
  264. _FORCE_INLINE_ const TKey &operator*() const {
  265. return keys[index];
  266. }
  267. _FORCE_INLINE_ const TKey *operator->() const {
  268. return &keys[index];
  269. }
  270. _FORCE_INLINE_ Iterator &operator++() {
  271. index++;
  272. if (index >= (int32_t)num_keys) {
  273. index = -1;
  274. keys = nullptr;
  275. num_keys = 0;
  276. }
  277. return *this;
  278. }
  279. _FORCE_INLINE_ Iterator &operator--() {
  280. index--;
  281. if (index < 0) {
  282. index = -1;
  283. keys = nullptr;
  284. num_keys = 0;
  285. }
  286. return *this;
  287. }
  288. _FORCE_INLINE_ bool operator==(const Iterator &b) const { return keys == b.keys && index == b.index; }
  289. _FORCE_INLINE_ bool operator!=(const Iterator &b) const { return keys != b.keys || index != b.index; }
  290. _FORCE_INLINE_ explicit operator bool() const {
  291. return keys != nullptr;
  292. }
  293. _FORCE_INLINE_ Iterator(const TKey *p_keys, uint32_t p_num_keys, int32_t p_index = -1) {
  294. keys = p_keys;
  295. num_keys = p_num_keys;
  296. index = p_index;
  297. }
  298. _FORCE_INLINE_ Iterator() {}
  299. _FORCE_INLINE_ Iterator(const Iterator &p_it) {
  300. keys = p_it.keys;
  301. num_keys = p_it.num_keys;
  302. index = p_it.index;
  303. }
  304. _FORCE_INLINE_ void operator=(const Iterator &p_it) {
  305. keys = p_it.keys;
  306. num_keys = p_it.num_keys;
  307. index = p_it.index;
  308. }
  309. private:
  310. const TKey *keys = nullptr;
  311. uint32_t num_keys = 0;
  312. int32_t index = -1;
  313. };
  314. _FORCE_INLINE_ Iterator begin() const {
  315. return num_elements ? Iterator(keys, num_elements, 0) : Iterator();
  316. }
  317. _FORCE_INLINE_ Iterator end() const {
  318. return Iterator();
  319. }
  320. _FORCE_INLINE_ Iterator last() const {
  321. if (num_elements == 0) {
  322. return Iterator();
  323. }
  324. return Iterator(keys, num_elements, num_elements - 1);
  325. }
  326. _FORCE_INLINE_ Iterator find(const TKey &p_key) const {
  327. uint32_t pos = 0;
  328. bool exists = _lookup_pos(p_key, pos);
  329. if (!exists) {
  330. return end();
  331. }
  332. return Iterator(keys, num_elements, pos);
  333. }
  334. _FORCE_INLINE_ void remove(const Iterator &p_iter) {
  335. if (p_iter) {
  336. erase(*p_iter);
  337. }
  338. }
  339. /* Insert */
  340. Iterator insert(const TKey &p_key) {
  341. uint32_t pos = _insert(p_key);
  342. return Iterator(keys, num_elements, pos);
  343. }
  344. /* Constructors */
  345. HashSet(const HashSet &p_other) {
  346. _init_from(p_other);
  347. }
  348. void operator=(const HashSet &p_other) {
  349. if (this == &p_other) {
  350. return; // Ignore self assignment.
  351. }
  352. clear();
  353. if (keys != nullptr) {
  354. Memory::free_static(keys);
  355. Memory::free_static(key_to_hash);
  356. Memory::free_static(hash_to_key);
  357. Memory::free_static(hashes);
  358. keys = nullptr;
  359. hashes = nullptr;
  360. hash_to_key = nullptr;
  361. key_to_hash = nullptr;
  362. }
  363. _init_from(p_other);
  364. }
  365. HashSet(uint32_t p_initial_capacity) {
  366. // Capacity can't be 0.
  367. capacity_index = 0;
  368. reserve(p_initial_capacity);
  369. }
  370. HashSet() {
  371. capacity_index = MIN_CAPACITY_INDEX;
  372. }
  373. void reset() {
  374. clear();
  375. if (keys != nullptr) {
  376. Memory::free_static(keys);
  377. Memory::free_static(key_to_hash);
  378. Memory::free_static(hash_to_key);
  379. Memory::free_static(hashes);
  380. keys = nullptr;
  381. hashes = nullptr;
  382. hash_to_key = nullptr;
  383. key_to_hash = nullptr;
  384. }
  385. capacity_index = MIN_CAPACITY_INDEX;
  386. }
  387. ~HashSet() {
  388. clear();
  389. if (keys != nullptr) {
  390. Memory::free_static(keys);
  391. Memory::free_static(key_to_hash);
  392. Memory::free_static(hash_to_key);
  393. Memory::free_static(hashes);
  394. }
  395. }
  396. };
  397. #endif // HASH_SET_H