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. #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. uint32_t new_index = capacity_index;
  245. while (hash_table_size_primes[new_index] < p_new_capacity) {
  246. ERR_FAIL_COND_MSG(new_index + 1 == (uint32_t)HASH_TABLE_SIZE_MAX, nullptr);
  247. new_index++;
  248. }
  249. if (new_index == capacity_index) {
  250. return;
  251. }
  252. if (keys == nullptr) {
  253. capacity_index = new_index;
  254. return; // Unallocated yet.
  255. }
  256. _resize_and_rehash(new_index);
  257. }
  258. /** Iterator API **/
  259. struct Iterator {
  260. _FORCE_INLINE_ const TKey &operator*() const {
  261. return keys[index];
  262. }
  263. _FORCE_INLINE_ const TKey *operator->() const {
  264. return &keys[index];
  265. }
  266. _FORCE_INLINE_ Iterator &operator++() {
  267. index++;
  268. if (index >= (int32_t)num_keys) {
  269. index = -1;
  270. keys = nullptr;
  271. num_keys = 0;
  272. }
  273. return *this;
  274. }
  275. _FORCE_INLINE_ Iterator &operator--() {
  276. index--;
  277. if (index < 0) {
  278. index = -1;
  279. keys = nullptr;
  280. num_keys = 0;
  281. }
  282. return *this;
  283. }
  284. _FORCE_INLINE_ bool operator==(const Iterator &b) const { return keys == b.keys && index == b.index; }
  285. _FORCE_INLINE_ bool operator!=(const Iterator &b) const { return keys != b.keys || index != b.index; }
  286. _FORCE_INLINE_ explicit operator bool() const {
  287. return keys != nullptr;
  288. }
  289. _FORCE_INLINE_ Iterator(const TKey *p_keys, uint32_t p_num_keys, int32_t p_index = -1) {
  290. keys = p_keys;
  291. num_keys = p_num_keys;
  292. index = p_index;
  293. }
  294. _FORCE_INLINE_ Iterator() {}
  295. _FORCE_INLINE_ Iterator(const Iterator &p_it) {
  296. keys = p_it.keys;
  297. num_keys = p_it.num_keys;
  298. index = p_it.index;
  299. }
  300. _FORCE_INLINE_ void operator=(const Iterator &p_it) {
  301. keys = p_it.keys;
  302. num_keys = p_it.num_keys;
  303. index = p_it.index;
  304. }
  305. private:
  306. const TKey *keys = nullptr;
  307. uint32_t num_keys = 0;
  308. int32_t index = -1;
  309. };
  310. _FORCE_INLINE_ Iterator begin() const {
  311. return num_elements ? Iterator(keys, num_elements, 0) : Iterator();
  312. }
  313. _FORCE_INLINE_ Iterator end() const {
  314. return Iterator();
  315. }
  316. _FORCE_INLINE_ Iterator last() const {
  317. if (num_elements == 0) {
  318. return Iterator();
  319. }
  320. return Iterator(keys, num_elements, num_elements - 1);
  321. }
  322. _FORCE_INLINE_ Iterator find(const TKey &p_key) const {
  323. uint32_t pos = 0;
  324. bool exists = _lookup_pos(p_key, pos);
  325. if (!exists) {
  326. return end();
  327. }
  328. return Iterator(keys, num_elements, pos);
  329. }
  330. _FORCE_INLINE_ void remove(const Iterator &p_iter) {
  331. if (p_iter) {
  332. erase(*p_iter);
  333. }
  334. }
  335. /* Insert */
  336. Iterator insert(const TKey &p_key) {
  337. uint32_t pos = _insert(p_key);
  338. return Iterator(keys, num_elements, pos);
  339. }
  340. /* Constructors */
  341. HashSet(const HashSet &p_other) {
  342. _init_from(p_other);
  343. }
  344. void operator=(const HashSet &p_other) {
  345. if (this == &p_other) {
  346. return; // Ignore self assignment.
  347. }
  348. clear();
  349. if (keys != nullptr) {
  350. Memory::free_static(keys);
  351. Memory::free_static(key_to_hash);
  352. Memory::free_static(hash_to_key);
  353. Memory::free_static(hashes);
  354. keys = nullptr;
  355. hashes = nullptr;
  356. hash_to_key = nullptr;
  357. key_to_hash = nullptr;
  358. }
  359. _init_from(p_other);
  360. }
  361. HashSet(uint32_t p_initial_capacity) {
  362. // Capacity can't be 0.
  363. capacity_index = 0;
  364. reserve(p_initial_capacity);
  365. }
  366. HashSet() {
  367. capacity_index = MIN_CAPACITY_INDEX;
  368. }
  369. HashSet(std::initializer_list<TKey> p_init) {
  370. reserve(p_init.size());
  371. for (const TKey &E : p_init) {
  372. insert(E);
  373. }
  374. }
  375. void reset() {
  376. clear();
  377. if (keys != nullptr) {
  378. Memory::free_static(keys);
  379. Memory::free_static(key_to_hash);
  380. Memory::free_static(hash_to_key);
  381. Memory::free_static(hashes);
  382. keys = nullptr;
  383. hashes = nullptr;
  384. hash_to_key = nullptr;
  385. key_to_hash = nullptr;
  386. }
  387. capacity_index = MIN_CAPACITY_INDEX;
  388. }
  389. ~HashSet() {
  390. clear();
  391. if (keys != nullptr) {
  392. Memory::free_static(keys);
  393. Memory::free_static(key_to_hash);
  394. Memory::free_static(hash_to_key);
  395. Memory::free_static(hashes);
  396. }
  397. }
  398. };