SDL_hashtable.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2025 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #include "SDL_internal.h"
  19. #include "SDL_hashtable.h"
  20. // XXX: We can't use SDL_assert here because it's going to call into hashtable code
  21. #ifdef NDEBUG
  22. #define HT_ASSERT(x) (void)(0)
  23. #else
  24. #if (defined(_WIN32) || defined(SDL_PLATFORM_CYGWIN)) && !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  25. #include <windows.h>
  26. #endif
  27. /* This is not declared in any header, although it is shared between some
  28. parts of SDL, because we don't want anything calling it without an
  29. extremely good reason. */
  30. extern SDL_NORETURN void SDL_ExitProcess(int exitcode);
  31. static void HT_ASSERT_FAIL(const char *msg)
  32. {
  33. const char *caption = "SDL_HashTable Assertion Failure!";
  34. (void)caption;
  35. #if (defined(_WIN32) || defined(SDL_PLATFORM_CYGWIN)) && !defined(SDL_PLATFORM_XBOXONE) && !defined(SDL_PLATFORM_XBOXSERIES)
  36. MessageBoxA(NULL, msg, caption, MB_OK | MB_ICONERROR);
  37. #elif defined(HAVE_STDIO_H)
  38. fprintf(stderr, "\n\n%s\n%s\n\n", caption, msg);
  39. fflush(stderr);
  40. #endif
  41. SDL_TriggerBreakpoint();
  42. SDL_ExitProcess(-1);
  43. }
  44. #define HT_ASSERT(x) if (!(x)) HT_ASSERT_FAIL("SDL_HashTable Assertion Failure: " #x)
  45. #endif
  46. typedef struct SDL_HashItem
  47. {
  48. // TODO: Splitting off values into a separate array might be more cache-friendly
  49. const void *key;
  50. const void *value;
  51. Uint32 hash;
  52. Uint32 probe_len : 31;
  53. Uint32 live : 1;
  54. } SDL_HashItem;
  55. // Must be a power of 2 >= sizeof(SDL_HashItem)
  56. #define MAX_HASHITEM_SIZEOF 32u
  57. SDL_COMPILE_TIME_ASSERT(sizeof_SDL_HashItem, sizeof(SDL_HashItem) <= MAX_HASHITEM_SIZEOF);
  58. // Anything larger than this will cause integer overflows
  59. #define MAX_HASHTABLE_SIZE (0x80000000u / (MAX_HASHITEM_SIZEOF))
  60. struct SDL_HashTable
  61. {
  62. SDL_RWLock *lock;
  63. SDL_HashItem *table;
  64. SDL_HashTable_HashFn hash;
  65. SDL_HashTable_KeyMatchFn keymatch;
  66. SDL_HashTable_NukeFn nuke;
  67. void *data;
  68. Uint32 hash_mask;
  69. Uint32 max_probe_len;
  70. Uint32 num_occupied_slots;
  71. bool stackable;
  72. };
  73. SDL_HashTable *SDL_CreateHashTable(void *data,
  74. Uint32 num_buckets,
  75. SDL_HashTable_HashFn hashfn,
  76. SDL_HashTable_KeyMatchFn keymatchfn,
  77. SDL_HashTable_NukeFn nukefn,
  78. bool threadsafe,
  79. bool stackable)
  80. {
  81. SDL_HashTable *table;
  82. // num_buckets must be a power of two so we can derive the bucket index with just a bit-and.
  83. if ((num_buckets < 1) || !SDL_HasExactlyOneBitSet32(num_buckets)) {
  84. SDL_SetError("num_buckets must be a power of two");
  85. return NULL;
  86. }
  87. if (num_buckets > MAX_HASHTABLE_SIZE) {
  88. SDL_SetError("num_buckets is too large");
  89. return NULL;
  90. }
  91. table = (SDL_HashTable *)SDL_calloc(1, sizeof(SDL_HashTable));
  92. if (!table) {
  93. return NULL;
  94. }
  95. if (threadsafe) {
  96. // Don't fail if we can't create a lock (single threaded environment?)
  97. table->lock = SDL_CreateRWLock();
  98. }
  99. table->table = (SDL_HashItem *)SDL_calloc(num_buckets, sizeof(SDL_HashItem));
  100. if (!table->table) {
  101. SDL_DestroyHashTable(table);
  102. return NULL;
  103. }
  104. table->hash_mask = num_buckets - 1;
  105. table->stackable = stackable;
  106. table->data = data;
  107. table->hash = hashfn;
  108. table->keymatch = keymatchfn;
  109. table->nuke = nukefn;
  110. return table;
  111. }
  112. static SDL_INLINE Uint32 calc_hash(const SDL_HashTable *table, const void *key)
  113. {
  114. const Uint32 BitMixer = 0x9E3779B1u;
  115. return table->hash(key, table->data) * BitMixer;
  116. }
  117. static SDL_INLINE Uint32 get_probe_length(Uint32 zero_idx, Uint32 actual_idx, Uint32 num_buckets)
  118. {
  119. // returns the probe sequence length from zero_idx to actual_idx
  120. if (actual_idx < zero_idx) {
  121. return num_buckets - zero_idx + actual_idx;
  122. }
  123. return actual_idx - zero_idx;
  124. }
  125. static SDL_HashItem *find_item(const SDL_HashTable *ht, const void *key, Uint32 hash, Uint32 *i, Uint32 *probe_len)
  126. {
  127. Uint32 hash_mask = ht->hash_mask;
  128. Uint32 max_probe_len = ht->max_probe_len;
  129. SDL_HashItem *table = ht->table;
  130. for (;;) {
  131. SDL_HashItem *item = table + *i;
  132. Uint32 item_hash = item->hash;
  133. if (!item->live) {
  134. return NULL;
  135. }
  136. if (item_hash == hash && ht->keymatch(item->key, key, ht->data)) {
  137. return item;
  138. }
  139. Uint32 item_probe_len = item->probe_len;
  140. HT_ASSERT(item_probe_len == get_probe_length(item_hash & hash_mask, (Uint32)(item - table), hash_mask + 1));
  141. if (*probe_len > item_probe_len) {
  142. return NULL;
  143. }
  144. if (++*probe_len > max_probe_len) {
  145. return NULL;
  146. }
  147. *i = (*i + 1) & hash_mask;
  148. }
  149. }
  150. static SDL_HashItem *find_first_item(const SDL_HashTable *ht, const void *key, Uint32 hash)
  151. {
  152. Uint32 i = hash & ht->hash_mask;
  153. Uint32 probe_len = 0;
  154. return find_item(ht, key, hash, &i, &probe_len);
  155. }
  156. static SDL_HashItem *insert_item(SDL_HashItem *item_to_insert, SDL_HashItem *table, Uint32 hash_mask, Uint32 *max_probe_len_ptr)
  157. {
  158. Uint32 idx = item_to_insert->hash & hash_mask;
  159. SDL_HashItem temp_item, *target = NULL;
  160. Uint32 num_buckets = hash_mask + 1;
  161. for (;;) {
  162. SDL_HashItem *candidate = table + idx;
  163. if (!candidate->live) {
  164. // Found an empty slot. Put it here and we're done.
  165. *candidate = *item_to_insert;
  166. if (target == NULL) {
  167. target = candidate;
  168. }
  169. Uint32 probe_len = get_probe_length(candidate->hash & hash_mask, idx, num_buckets);
  170. candidate->probe_len = probe_len;
  171. if (*max_probe_len_ptr < probe_len) {
  172. *max_probe_len_ptr = probe_len;
  173. }
  174. break;
  175. }
  176. Uint32 candidate_probe_len = candidate->probe_len;
  177. HT_ASSERT(candidate_probe_len == get_probe_length(candidate->hash & hash_mask, idx, num_buckets));
  178. Uint32 new_probe_len = get_probe_length(item_to_insert->hash & hash_mask, idx, num_buckets);
  179. if (candidate_probe_len < new_probe_len) {
  180. // Robin Hood hashing: the item at idx has a better probe length than our item would at this position.
  181. // Evict it and put our item in its place, then continue looking for a new spot for the displaced item.
  182. // This algorithm significantly reduces clustering in the table, making lookups take very few probes.
  183. temp_item = *candidate;
  184. *candidate = *item_to_insert;
  185. if (target == NULL) {
  186. target = candidate;
  187. }
  188. *item_to_insert = temp_item;
  189. HT_ASSERT(new_probe_len == get_probe_length(candidate->hash & hash_mask, idx, num_buckets));
  190. candidate->probe_len = new_probe_len;
  191. if (*max_probe_len_ptr < new_probe_len) {
  192. *max_probe_len_ptr = new_probe_len;
  193. }
  194. }
  195. idx = (idx + 1) & hash_mask;
  196. }
  197. return target;
  198. }
  199. static void delete_item(SDL_HashTable *ht, SDL_HashItem *item)
  200. {
  201. Uint32 hash_mask = ht->hash_mask;
  202. SDL_HashItem *table = ht->table;
  203. if (ht->nuke) {
  204. ht->nuke(item->key, item->value, ht->data);
  205. }
  206. ht->num_occupied_slots--;
  207. Uint32 idx = (Uint32)(item - ht->table);
  208. for (;;) {
  209. idx = (idx + 1) & hash_mask;
  210. SDL_HashItem *next_item = table + idx;
  211. if (next_item->probe_len < 1) {
  212. SDL_zerop(item);
  213. return;
  214. }
  215. *item = *next_item;
  216. item->probe_len -= 1;
  217. HT_ASSERT(item->probe_len < ht->max_probe_len);
  218. item = next_item;
  219. }
  220. }
  221. static bool resize(SDL_HashTable *ht, Uint32 new_size)
  222. {
  223. SDL_HashItem *old_table = ht->table;
  224. Uint32 old_size = ht->hash_mask + 1;
  225. Uint32 new_hash_mask = new_size - 1;
  226. SDL_HashItem *new_table = SDL_calloc(new_size, sizeof(*new_table));
  227. if (!new_table) {
  228. return false;
  229. }
  230. ht->max_probe_len = 0;
  231. ht->hash_mask = new_hash_mask;
  232. ht->table = new_table;
  233. for (Uint32 i = 0; i < old_size; ++i) {
  234. SDL_HashItem *item = old_table + i;
  235. if (item->live) {
  236. insert_item(item, new_table, new_hash_mask, &ht->max_probe_len);
  237. }
  238. }
  239. SDL_free(old_table);
  240. return true;
  241. }
  242. static bool maybe_resize(SDL_HashTable *ht)
  243. {
  244. Uint32 capacity = ht->hash_mask + 1;
  245. if (capacity >= MAX_HASHTABLE_SIZE) {
  246. return false;
  247. }
  248. Uint32 max_load_factor = 217; // range: 0-255; 217 is roughly 85%
  249. Uint32 resize_threshold = (Uint32)((max_load_factor * (Uint64)capacity) >> 8);
  250. if (ht->num_occupied_slots > resize_threshold) {
  251. return resize(ht, capacity * 2);
  252. }
  253. return true;
  254. }
  255. bool SDL_InsertIntoHashTable(SDL_HashTable *table, const void *key, const void *value)
  256. {
  257. SDL_HashItem *item;
  258. Uint32 hash;
  259. bool result = false;
  260. if (!table) {
  261. return false;
  262. }
  263. if (table->lock) {
  264. SDL_LockRWLockForWriting(table->lock);
  265. }
  266. hash = calc_hash(table, key);
  267. item = find_first_item(table, key, hash);
  268. if (item && !table->stackable) {
  269. // Allow overwrites, this might have been inserted on another thread
  270. delete_item(table, item);
  271. }
  272. SDL_HashItem new_item;
  273. new_item.key = key;
  274. new_item.value = value;
  275. new_item.hash = hash;
  276. new_item.live = true;
  277. new_item.probe_len = 0;
  278. table->num_occupied_slots++;
  279. if (!maybe_resize(table)) {
  280. table->num_occupied_slots--;
  281. goto done;
  282. }
  283. // This never returns NULL
  284. insert_item(&new_item, table->table, table->hash_mask, &table->max_probe_len);
  285. result = true;
  286. done:
  287. if (table->lock) {
  288. SDL_UnlockRWLock(table->lock);
  289. }
  290. return result;
  291. }
  292. bool SDL_FindInHashTable(const SDL_HashTable *table, const void *key, const void **value)
  293. {
  294. Uint32 hash;
  295. SDL_HashItem *i;
  296. bool result = false;
  297. if (!table) {
  298. if (value) {
  299. *value = NULL;
  300. }
  301. return false;
  302. }
  303. if (table->lock) {
  304. SDL_LockRWLockForReading(table->lock);
  305. }
  306. hash = calc_hash(table, key);
  307. i = find_first_item(table, key, hash);
  308. if (i) {
  309. if (value) {
  310. *value = i->value;
  311. }
  312. result = true;
  313. }
  314. if (table->lock) {
  315. SDL_UnlockRWLock(table->lock);
  316. }
  317. return result;
  318. }
  319. bool SDL_RemoveFromHashTable(SDL_HashTable *table, const void *key)
  320. {
  321. Uint32 hash;
  322. SDL_HashItem *item;
  323. bool result = false;
  324. if (!table) {
  325. return false;
  326. }
  327. if (table->lock) {
  328. SDL_LockRWLockForWriting(table->lock);
  329. }
  330. // FIXME: what to do for stacking hashtables?
  331. // The original code removes just one item.
  332. // This hashtable happens to preserve the insertion order of multi-value keys,
  333. // so deleting the first one will always delete the least-recently inserted one.
  334. // But maybe it makes more sense to remove all matching items?
  335. hash = calc_hash(table, key);
  336. item = find_first_item(table, key, hash);
  337. if (!item) {
  338. goto done;
  339. }
  340. delete_item(table, item);
  341. result = true;
  342. done:
  343. if (table->lock) {
  344. SDL_UnlockRWLock(table->lock);
  345. }
  346. return result;
  347. }
  348. bool SDL_IterateHashTableKey(const SDL_HashTable *table, const void *key, const void **_value, void **iter)
  349. {
  350. SDL_HashItem *item = (SDL_HashItem *)*iter;
  351. if (!table) {
  352. return false;
  353. }
  354. Uint32 i, probe_len, hash;
  355. if (item) {
  356. HT_ASSERT(item >= table->table);
  357. HT_ASSERT(item < table->table + (table->hash_mask + 1));
  358. hash = item->hash;
  359. probe_len = item->probe_len + 1;
  360. i = ((Uint32)(item - table->table) + 1) & table->hash_mask;
  361. item = table->table + i;
  362. } else {
  363. hash = calc_hash(table, key);
  364. i = hash & table->hash_mask;
  365. probe_len = 0;
  366. }
  367. item = find_item(table, key, hash, &i, &probe_len);
  368. if (!item) {
  369. *_value = NULL;
  370. return false;
  371. }
  372. *_value = item->value;
  373. *iter = item;
  374. return true;
  375. }
  376. bool SDL_IterateHashTable(const SDL_HashTable *table, const void **_key, const void **_value, void **iter)
  377. {
  378. SDL_HashItem *item = (SDL_HashItem *)*iter;
  379. if (!table) {
  380. return false;
  381. }
  382. if (!item) {
  383. item = table->table;
  384. } else {
  385. item++;
  386. }
  387. HT_ASSERT(item >= table->table);
  388. SDL_HashItem *end = table->table + (table->hash_mask + 1);
  389. while (item < end && !item->live) {
  390. ++item;
  391. }
  392. HT_ASSERT(item <= end);
  393. if (item == end) {
  394. if (_key) {
  395. *_key = NULL;
  396. }
  397. if (_value) {
  398. *_value = NULL;
  399. }
  400. return false;
  401. }
  402. if (_key) {
  403. *_key = item->key;
  404. }
  405. if (_value) {
  406. *_value = item->value;
  407. }
  408. *iter = item;
  409. return true;
  410. }
  411. bool SDL_HashTableEmpty(SDL_HashTable *table)
  412. {
  413. return !(table && table->num_occupied_slots);
  414. }
  415. static void nuke_all(SDL_HashTable *table)
  416. {
  417. void *data = table->data;
  418. SDL_HashItem *end = table->table + (table->hash_mask + 1);
  419. SDL_HashItem *i;
  420. for (i = table->table; i < end; ++i) {
  421. if (i->live) {
  422. table->nuke(i->key, i->value, data);
  423. }
  424. }
  425. }
  426. void SDL_EmptyHashTable(SDL_HashTable *table)
  427. {
  428. if (table) {
  429. SDL_LockRWLockForWriting(table->lock);
  430. {
  431. if (table->nuke) {
  432. nuke_all(table);
  433. }
  434. SDL_memset(table->table, 0, sizeof(*table->table) * (table->hash_mask + 1));
  435. table->num_occupied_slots = 0;
  436. }
  437. SDL_UnlockRWLock(table->lock);
  438. }
  439. }
  440. void SDL_DestroyHashTable(SDL_HashTable *table)
  441. {
  442. if (table) {
  443. SDL_EmptyHashTable(table);
  444. SDL_DestroyRWLock(table->lock);
  445. SDL_free(table->table);
  446. SDL_free(table);
  447. }
  448. }
  449. // this is djb's xor hashing function.
  450. static SDL_INLINE Uint32 hash_string_djbxor(const char *str, size_t len)
  451. {
  452. Uint32 hash = 5381;
  453. while (len--) {
  454. hash = ((hash << 5) + hash) ^ *(str++);
  455. }
  456. return hash;
  457. }
  458. Uint32 SDL_HashPointer(const void *key, void *unused)
  459. {
  460. (void)unused;
  461. return SDL_murmur3_32(&key, sizeof(key), 0);
  462. }
  463. bool SDL_KeyMatchPointer(const void *a, const void *b, void *unused)
  464. {
  465. (void)unused;
  466. return (a == b);
  467. }
  468. Uint32 SDL_HashString(const void *key, void *unused)
  469. {
  470. (void)unused;
  471. const char *str = (const char *)key;
  472. return hash_string_djbxor(str, SDL_strlen(str));
  473. }
  474. bool SDL_KeyMatchString(const void *a, const void *b, void *unused)
  475. {
  476. const char *a_string = (const char *)a;
  477. const char *b_string = (const char *)b;
  478. (void)unused;
  479. if (a == b) {
  480. return true; // same pointer, must match.
  481. } else if (!a || !b) {
  482. return false; // one pointer is NULL (and first test shows they aren't the same pointer), must not match.
  483. } else if (a_string[0] != b_string[0]) {
  484. return false; // we know they don't match
  485. }
  486. return (SDL_strcmp(a_string, b_string) == 0); // Check against actual string contents.
  487. }
  488. // We assume we can fit the ID in the key directly
  489. SDL_COMPILE_TIME_ASSERT(SDL_HashID_KeySize, sizeof(Uint32) <= sizeof(const void *));
  490. Uint32 SDL_HashID(const void *key, void *unused)
  491. {
  492. (void)unused;
  493. return (Uint32)(uintptr_t)key;
  494. }
  495. bool SDL_KeyMatchID(const void *a, const void *b, void *unused)
  496. {
  497. (void)unused;
  498. return (a == b);
  499. }
  500. void SDL_NukeFreeKey(const void *key, const void *value, void *unused)
  501. {
  502. (void)value;
  503. (void)unused;
  504. SDL_free((void *)key);
  505. }
  506. void SDL_NukeFreeValue(const void *key, const void *value, void *unused)
  507. {
  508. (void)key;
  509. (void)unused;
  510. SDL_free((void *)value);
  511. }