hash_set.hpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. /**************************************************************************/
  2. /* hash_set.hpp */
  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 <godot_cpp/core/error_macros.hpp>
  32. #include <godot_cpp/core/memory.hpp>
  33. #include <godot_cpp/templates/hash_map.hpp>
  34. #include <godot_cpp/templates/hashfuncs.hpp>
  35. #include <godot_cpp/templates/pair.hpp>
  36. namespace godot {
  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 <typename TKey,
  46. typename Hasher = HashMapHasherDefault,
  47. typename 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. _FORCE_INLINE_ uint32_t _get_probe_length(uint32_t p_pos, uint32_t p_hash, uint32_t p_capacity) const {
  68. uint32_t original_pos = p_hash % p_capacity;
  69. return (p_pos - original_pos + p_capacity) % p_capacity;
  70. }
  71. bool _lookup_pos(const TKey &p_key, uint32_t &r_pos) const {
  72. if (keys == nullptr) {
  73. return false; // Failed lookups, no elements
  74. }
  75. uint32_t capacity = hash_table_size_primes[capacity_index];
  76. uint32_t hash = _hash(p_key);
  77. uint32_t pos = hash % capacity;
  78. uint32_t distance = 0;
  79. while (true) {
  80. if (hashes[pos] == EMPTY_HASH) {
  81. return false;
  82. }
  83. if (distance > _get_probe_length(pos, hashes[pos], capacity)) {
  84. return false;
  85. }
  86. if (hashes[pos] == hash && Comparator::compare(keys[hash_to_key[pos]], p_key)) {
  87. r_pos = hash_to_key[pos];
  88. return true;
  89. }
  90. pos = (pos + 1) % capacity;
  91. distance++;
  92. }
  93. }
  94. uint32_t _insert_with_hash(uint32_t p_hash, uint32_t p_index) {
  95. uint32_t capacity = hash_table_size_primes[capacity_index];
  96. uint32_t hash = p_hash;
  97. uint32_t index = p_index;
  98. uint32_t distance = 0;
  99. uint32_t pos = hash % capacity;
  100. while (true) {
  101. if (hashes[pos] == EMPTY_HASH) {
  102. hashes[pos] = hash;
  103. key_to_hash[index] = pos;
  104. hash_to_key[pos] = index;
  105. return pos;
  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], capacity);
  109. if (existing_probe_len < distance) {
  110. key_to_hash[index] = pos;
  111. SWAP(hash, hashes[pos]);
  112. SWAP(index, hash_to_key[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_index) {
  120. // Capacity can't be 0.
  121. capacity_index = MAX((uint32_t)MIN_CAPACITY_INDEX, p_new_capacity_index);
  122. uint32_t capacity = hash_table_size_primes[capacity_index];
  123. uint32_t *old_hashes = hashes;
  124. uint32_t *old_key_to_hash = key_to_hash;
  125. hashes = reinterpret_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  126. keys = reinterpret_cast<TKey *>(Memory::realloc_static(keys, sizeof(TKey) * capacity));
  127. key_to_hash = reinterpret_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  128. hash_to_key = reinterpret_cast<uint32_t *>(Memory::realloc_static(hash_to_key, sizeof(uint32_t) * capacity));
  129. for (uint32_t i = 0; i < capacity; i++) {
  130. hashes[i] = EMPTY_HASH;
  131. }
  132. for (uint32_t i = 0; i < num_elements; i++) {
  133. uint32_t h = old_hashes[old_key_to_hash[i]];
  134. _insert_with_hash(h, i);
  135. }
  136. Memory::free_static(old_hashes);
  137. Memory::free_static(old_key_to_hash);
  138. }
  139. _FORCE_INLINE_ int32_t _insert(const TKey &p_key) {
  140. uint32_t capacity = hash_table_size_primes[capacity_index];
  141. if (unlikely(keys == nullptr)) {
  142. // Allocate on demand to save memory.
  143. hashes = reinterpret_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  144. keys = reinterpret_cast<TKey *>(Memory::alloc_static(sizeof(TKey) * capacity));
  145. key_to_hash = reinterpret_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  146. hash_to_key = reinterpret_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  147. for (uint32_t i = 0; i < capacity; i++) {
  148. hashes[i] = EMPTY_HASH;
  149. }
  150. }
  151. uint32_t pos = 0;
  152. bool exists = _lookup_pos(p_key, pos);
  153. if (exists) {
  154. return pos;
  155. } else {
  156. if (num_elements + 1 > MAX_OCCUPANCY * capacity) {
  157. ERR_FAIL_COND_V_MSG(capacity_index + 1 == HASH_TABLE_SIZE_MAX, -1, "Hash table maximum capacity reached, aborting insertion.");
  158. _resize_and_rehash(capacity_index + 1);
  159. }
  160. uint32_t hash = _hash(p_key);
  161. memnew_placement(&keys[num_elements], TKey(p_key));
  162. _insert_with_hash(hash, num_elements);
  163. num_elements++;
  164. return num_elements - 1;
  165. }
  166. }
  167. void _init_from(const HashSet &p_other) {
  168. capacity_index = p_other.capacity_index;
  169. num_elements = p_other.num_elements;
  170. if (p_other.num_elements == 0) {
  171. return;
  172. }
  173. uint32_t capacity = hash_table_size_primes[capacity_index];
  174. hashes = reinterpret_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  175. keys = reinterpret_cast<TKey *>(Memory::alloc_static(sizeof(TKey) * capacity));
  176. key_to_hash = reinterpret_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  177. hash_to_key = reinterpret_cast<uint32_t *>(Memory::alloc_static(sizeof(uint32_t) * capacity));
  178. for (uint32_t i = 0; i < num_elements; i++) {
  179. memnew_placement(&keys[i], TKey(p_other.keys[i]));
  180. key_to_hash[i] = p_other.key_to_hash[i];
  181. }
  182. for (uint32_t i = 0; i < capacity; i++) {
  183. hashes[i] = p_other.hashes[i];
  184. hash_to_key[i] = p_other.hash_to_key[i];
  185. }
  186. }
  187. public:
  188. _FORCE_INLINE_ uint32_t get_capacity() const { return hash_table_size_primes[capacity_index]; }
  189. _FORCE_INLINE_ uint32_t size() const { return num_elements; }
  190. /* Standard Godot Container API */
  191. bool is_empty() const {
  192. return num_elements == 0;
  193. }
  194. void clear() {
  195. if (keys == nullptr) {
  196. return;
  197. }
  198. uint32_t capacity = hash_table_size_primes[capacity_index];
  199. for (uint32_t i = 0; i < capacity; i++) {
  200. hashes[i] = EMPTY_HASH;
  201. }
  202. for (uint32_t i = 0; i < num_elements; i++) {
  203. keys[i].~TKey();
  204. }
  205. num_elements = 0;
  206. }
  207. _FORCE_INLINE_ bool has(const TKey &p_key) const {
  208. uint32_t _pos = 0;
  209. return _lookup_pos(p_key, _pos);
  210. }
  211. bool erase(const TKey &p_key) {
  212. uint32_t pos = 0;
  213. bool exists = _lookup_pos(p_key, pos);
  214. if (!exists) {
  215. return false;
  216. }
  217. uint32_t key_pos = pos;
  218. pos = key_to_hash[pos]; // make hash pos
  219. uint32_t capacity = hash_table_size_primes[capacity_index];
  220. uint32_t next_pos = (pos + 1) % capacity;
  221. while (hashes[next_pos] != EMPTY_HASH && _get_probe_length(next_pos, hashes[next_pos], capacity) != 0) {
  222. uint32_t kpos = hash_to_key[pos];
  223. uint32_t kpos_next = hash_to_key[next_pos];
  224. SWAP(key_to_hash[kpos], key_to_hash[kpos_next]);
  225. SWAP(hashes[next_pos], hashes[pos]);
  226. SWAP(hash_to_key[next_pos], hash_to_key[pos]);
  227. pos = next_pos;
  228. next_pos = (pos + 1) % capacity;
  229. }
  230. hashes[pos] = EMPTY_HASH;
  231. keys[key_pos].~TKey();
  232. num_elements--;
  233. if (key_pos < num_elements) {
  234. // Not the last key, move the last one here to keep keys lineal
  235. memnew_placement(&keys[key_pos], TKey(keys[num_elements]));
  236. keys[num_elements].~TKey();
  237. key_to_hash[key_pos] = key_to_hash[num_elements];
  238. hash_to_key[key_to_hash[num_elements]] = key_pos;
  239. }
  240. return true;
  241. }
  242. // Reserves space for a number of elements, useful to avoid many resizes and rehashes.
  243. // If adding a known (possibly large) number of elements at once, must be larger than old capacity.
  244. void reserve(uint32_t p_new_capacity) {
  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. void reset() {
  371. clear();
  372. if (keys != nullptr) {
  373. Memory::free_static(keys);
  374. Memory::free_static(key_to_hash);
  375. Memory::free_static(hash_to_key);
  376. Memory::free_static(hashes);
  377. keys = nullptr;
  378. hashes = nullptr;
  379. hash_to_key = nullptr;
  380. key_to_hash = nullptr;
  381. }
  382. capacity_index = MIN_CAPACITY_INDEX;
  383. }
  384. ~HashSet() {
  385. clear();
  386. if (keys != nullptr) {
  387. Memory::free_static(keys);
  388. Memory::free_static(key_to_hash);
  389. Memory::free_static(hash_to_key);
  390. Memory::free_static(hashes);
  391. }
  392. }
  393. };
  394. } // namespace godot