hash_set.h 14 KB

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