hash.c 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106
  1. /* hash - hashing table processing.
  2. Copyright (C) 1998-2004, 2006-2007, 2009-2020 Free Software Foundation, Inc.
  3. Written by Jim Meyering, 1992.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <https://www.gnu.org/licenses/>. */
  14. /* A generic hash table package. */
  15. /* Define USE_OBSTACK to 1 if you want the allocator to use obstacks instead
  16. of malloc. If you change USE_OBSTACK, you have to recompile! */
  17. #include <config.h>
  18. #include "hash.h"
  19. #include "bitrotate.h"
  20. #include "xalloc-oversized.h"
  21. #include <stdint.h>
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #if USE_OBSTACK
  25. # include "obstack.h"
  26. # ifndef obstack_chunk_alloc
  27. # define obstack_chunk_alloc malloc
  28. # endif
  29. # ifndef obstack_chunk_free
  30. # define obstack_chunk_free free
  31. # endif
  32. #endif
  33. struct hash_entry
  34. {
  35. void *data;
  36. struct hash_entry *next;
  37. };
  38. struct hash_table
  39. {
  40. /* The array of buckets starts at BUCKET and extends to BUCKET_LIMIT-1,
  41. for a possibility of N_BUCKETS. Among those, N_BUCKETS_USED buckets
  42. are not empty, there are N_ENTRIES active entries in the table. */
  43. struct hash_entry *bucket;
  44. struct hash_entry const *bucket_limit;
  45. size_t n_buckets;
  46. size_t n_buckets_used;
  47. size_t n_entries;
  48. /* Tuning arguments, kept in a physically separate structure. */
  49. const Hash_tuning *tuning;
  50. /* Three functions are given to 'hash_initialize', see the documentation
  51. block for this function. In a word, HASHER randomizes a user entry
  52. into a number up from 0 up to some maximum minus 1; COMPARATOR returns
  53. true if two user entries compare equally; and DATA_FREER is the cleanup
  54. function for a user entry. */
  55. Hash_hasher hasher;
  56. Hash_comparator comparator;
  57. Hash_data_freer data_freer;
  58. /* A linked list of freed struct hash_entry structs. */
  59. struct hash_entry *free_entry_list;
  60. #if USE_OBSTACK
  61. /* Whenever obstacks are used, it is possible to allocate all overflowed
  62. entries into a single stack, so they all can be freed in a single
  63. operation. It is not clear if the speedup is worth the trouble. */
  64. struct obstack entry_stack;
  65. #endif
  66. };
  67. /* A hash table contains many internal entries, each holding a pointer to
  68. some user-provided data (also called a user entry). An entry indistinctly
  69. refers to both the internal entry and its associated user entry. A user
  70. entry contents may be hashed by a randomization function (the hashing
  71. function, or just "hasher" for short) into a number (or "slot") between 0
  72. and the current table size. At each slot position in the hash table,
  73. starts a linked chain of entries for which the user data all hash to this
  74. slot. A bucket is the collection of all entries hashing to the same slot.
  75. A good "hasher" function will distribute entries rather evenly in buckets.
  76. In the ideal case, the length of each bucket is roughly the number of
  77. entries divided by the table size. Finding the slot for a data is usually
  78. done in constant time by the "hasher", and the later finding of a precise
  79. entry is linear in time with the size of the bucket. Consequently, a
  80. larger hash table size (that is, a larger number of buckets) is prone to
  81. yielding shorter chains, *given* the "hasher" function behaves properly.
  82. Long buckets slow down the lookup algorithm. One might use big hash table
  83. sizes in hope to reduce the average length of buckets, but this might
  84. become inordinate, as unused slots in the hash table take some space. The
  85. best bet is to make sure you are using a good "hasher" function (beware
  86. that those are not that easy to write! :-), and to use a table size
  87. larger than the actual number of entries. */
  88. /* If an insertion makes the ratio of nonempty buckets to table size larger
  89. than the growth threshold (a number between 0.0 and 1.0), then increase
  90. the table size by multiplying by the growth factor (a number greater than
  91. 1.0). The growth threshold defaults to 0.8, and the growth factor
  92. defaults to 1.414, meaning that the table will have doubled its size
  93. every second time 80% of the buckets get used. */
  94. #define DEFAULT_GROWTH_THRESHOLD 0.8f
  95. #define DEFAULT_GROWTH_FACTOR 1.414f
  96. /* If a deletion empties a bucket and causes the ratio of used buckets to
  97. table size to become smaller than the shrink threshold (a number between
  98. 0.0 and 1.0), then shrink the table by multiplying by the shrink factor (a
  99. number greater than the shrink threshold but smaller than 1.0). The shrink
  100. threshold and factor default to 0.0 and 1.0, meaning that the table never
  101. shrinks. */
  102. #define DEFAULT_SHRINK_THRESHOLD 0.0f
  103. #define DEFAULT_SHRINK_FACTOR 1.0f
  104. /* Use this to initialize or reset a TUNING structure to
  105. some sensible values. */
  106. static const Hash_tuning default_tuning =
  107. {
  108. DEFAULT_SHRINK_THRESHOLD,
  109. DEFAULT_SHRINK_FACTOR,
  110. DEFAULT_GROWTH_THRESHOLD,
  111. DEFAULT_GROWTH_FACTOR,
  112. false
  113. };
  114. /* Information and lookup. */
  115. size_t
  116. hash_get_n_buckets (const Hash_table *table)
  117. {
  118. return table->n_buckets;
  119. }
  120. size_t
  121. hash_get_n_buckets_used (const Hash_table *table)
  122. {
  123. return table->n_buckets_used;
  124. }
  125. size_t
  126. hash_get_n_entries (const Hash_table *table)
  127. {
  128. return table->n_entries;
  129. }
  130. size_t
  131. hash_get_max_bucket_length (const Hash_table *table)
  132. {
  133. struct hash_entry const *bucket;
  134. size_t max_bucket_length = 0;
  135. for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
  136. {
  137. if (bucket->data)
  138. {
  139. struct hash_entry const *cursor = bucket;
  140. size_t bucket_length = 1;
  141. while (cursor = cursor->next, cursor)
  142. bucket_length++;
  143. if (bucket_length > max_bucket_length)
  144. max_bucket_length = bucket_length;
  145. }
  146. }
  147. return max_bucket_length;
  148. }
  149. bool
  150. hash_table_ok (const Hash_table *table)
  151. {
  152. struct hash_entry const *bucket;
  153. size_t n_buckets_used = 0;
  154. size_t n_entries = 0;
  155. for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
  156. {
  157. if (bucket->data)
  158. {
  159. struct hash_entry const *cursor = bucket;
  160. /* Count bucket head. */
  161. n_buckets_used++;
  162. n_entries++;
  163. /* Count bucket overflow. */
  164. while (cursor = cursor->next, cursor)
  165. n_entries++;
  166. }
  167. }
  168. if (n_buckets_used == table->n_buckets_used && n_entries == table->n_entries)
  169. return true;
  170. return false;
  171. }
  172. void
  173. hash_print_statistics (const Hash_table *table, FILE *stream)
  174. {
  175. size_t n_entries = hash_get_n_entries (table);
  176. size_t n_buckets = hash_get_n_buckets (table);
  177. size_t n_buckets_used = hash_get_n_buckets_used (table);
  178. size_t max_bucket_length = hash_get_max_bucket_length (table);
  179. fprintf (stream, "# entries: %lu\n", (unsigned long int) n_entries);
  180. fprintf (stream, "# buckets: %lu\n", (unsigned long int) n_buckets);
  181. fprintf (stream, "# buckets used: %lu (%.2f%%)\n",
  182. (unsigned long int) n_buckets_used,
  183. (100.0 * n_buckets_used) / n_buckets);
  184. fprintf (stream, "max bucket length: %lu\n",
  185. (unsigned long int) max_bucket_length);
  186. }
  187. /* Hash KEY and return a pointer to the selected bucket.
  188. If TABLE->hasher misbehaves, abort. */
  189. static struct hash_entry *
  190. safe_hasher (const Hash_table *table, const void *key)
  191. {
  192. size_t n = table->hasher (key, table->n_buckets);
  193. if (! (n < table->n_buckets))
  194. abort ();
  195. return table->bucket + n;
  196. }
  197. void *
  198. hash_lookup (const Hash_table *table, const void *entry)
  199. {
  200. struct hash_entry const *bucket = safe_hasher (table, entry);
  201. struct hash_entry const *cursor;
  202. if (bucket->data == NULL)
  203. return NULL;
  204. for (cursor = bucket; cursor; cursor = cursor->next)
  205. if (entry == cursor->data || table->comparator (entry, cursor->data))
  206. return cursor->data;
  207. return NULL;
  208. }
  209. /* Walking. */
  210. void *
  211. hash_get_first (const Hash_table *table)
  212. {
  213. struct hash_entry const *bucket;
  214. if (table->n_entries == 0)
  215. return NULL;
  216. for (bucket = table->bucket; ; bucket++)
  217. if (! (bucket < table->bucket_limit))
  218. abort ();
  219. else if (bucket->data)
  220. return bucket->data;
  221. }
  222. void *
  223. hash_get_next (const Hash_table *table, const void *entry)
  224. {
  225. struct hash_entry const *bucket = safe_hasher (table, entry);
  226. struct hash_entry const *cursor;
  227. /* Find next entry in the same bucket. */
  228. cursor = bucket;
  229. do
  230. {
  231. if (cursor->data == entry && cursor->next)
  232. return cursor->next->data;
  233. cursor = cursor->next;
  234. }
  235. while (cursor != NULL);
  236. /* Find first entry in any subsequent bucket. */
  237. while (++bucket < table->bucket_limit)
  238. if (bucket->data)
  239. return bucket->data;
  240. /* None found. */
  241. return NULL;
  242. }
  243. size_t
  244. hash_get_entries (const Hash_table *table, void **buffer,
  245. size_t buffer_size)
  246. {
  247. size_t counter = 0;
  248. struct hash_entry const *bucket;
  249. struct hash_entry const *cursor;
  250. for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
  251. {
  252. if (bucket->data)
  253. {
  254. for (cursor = bucket; cursor; cursor = cursor->next)
  255. {
  256. if (counter >= buffer_size)
  257. return counter;
  258. buffer[counter++] = cursor->data;
  259. }
  260. }
  261. }
  262. return counter;
  263. }
  264. size_t
  265. hash_do_for_each (const Hash_table *table, Hash_processor processor,
  266. void *processor_data)
  267. {
  268. size_t counter = 0;
  269. struct hash_entry const *bucket;
  270. struct hash_entry const *cursor;
  271. for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
  272. {
  273. if (bucket->data)
  274. {
  275. for (cursor = bucket; cursor; cursor = cursor->next)
  276. {
  277. if (! processor (cursor->data, processor_data))
  278. return counter;
  279. counter++;
  280. }
  281. }
  282. }
  283. return counter;
  284. }
  285. /* Allocation and clean-up. */
  286. #if USE_DIFF_HASH
  287. /* About hashings, Paul Eggert writes to me (FP), on 1994-01-01: "Please see
  288. B. J. McKenzie, R. Harries & T. Bell, Selecting a hashing algorithm,
  289. Software--practice & experience 20, 2 (Feb 1990), 209-224. Good hash
  290. algorithms tend to be domain-specific, so what's good for [diffutils'] io.c
  291. may not be good for your application." */
  292. size_t
  293. hash_string (const char *string, size_t n_buckets)
  294. {
  295. # define HASH_ONE_CHAR(Value, Byte) \
  296. ((Byte) + rotl_sz (Value, 7))
  297. size_t value = 0;
  298. unsigned char ch;
  299. for (; (ch = *string); string++)
  300. value = HASH_ONE_CHAR (value, ch);
  301. return value % n_buckets;
  302. # undef HASH_ONE_CHAR
  303. }
  304. #else /* not USE_DIFF_HASH */
  305. /* This one comes from 'recode', and performs a bit better than the above as
  306. per a few experiments. It is inspired from a hashing routine found in the
  307. very old Cyber 'snoop', itself written in typical Greg Mansfield style.
  308. (By the way, what happened to this excellent man? Is he still alive?) */
  309. size_t
  310. hash_string (const char *string, size_t n_buckets)
  311. {
  312. size_t value = 0;
  313. unsigned char ch;
  314. for (; (ch = *string); string++)
  315. value = (value * 31 + ch) % n_buckets;
  316. return value;
  317. }
  318. #endif /* not USE_DIFF_HASH */
  319. /* Return true if CANDIDATE is a prime number. CANDIDATE should be an odd
  320. number at least equal to 11. */
  321. static bool _GL_ATTRIBUTE_CONST
  322. is_prime (size_t candidate)
  323. {
  324. size_t divisor = 3;
  325. size_t square = divisor * divisor;
  326. while (square < candidate && (candidate % divisor))
  327. {
  328. divisor++;
  329. square += 4 * divisor;
  330. divisor++;
  331. }
  332. return (candidate % divisor ? true : false);
  333. }
  334. /* Round a given CANDIDATE number up to the nearest prime, and return that
  335. prime. Primes lower than 10 are merely skipped. */
  336. static size_t _GL_ATTRIBUTE_CONST
  337. next_prime (size_t candidate)
  338. {
  339. /* Skip small primes. */
  340. if (candidate < 10)
  341. candidate = 10;
  342. /* Make it definitely odd. */
  343. candidate |= 1;
  344. while (SIZE_MAX != candidate && !is_prime (candidate))
  345. candidate += 2;
  346. return candidate;
  347. }
  348. void
  349. hash_reset_tuning (Hash_tuning *tuning)
  350. {
  351. *tuning = default_tuning;
  352. }
  353. /* If the user passes a NULL hasher, we hash the raw pointer. */
  354. static size_t
  355. raw_hasher (const void *data, size_t n)
  356. {
  357. /* When hashing unique pointers, it is often the case that they were
  358. generated by malloc and thus have the property that the low-order
  359. bits are 0. As this tends to give poorer performance with small
  360. tables, we rotate the pointer value before performing division,
  361. in an attempt to improve hash quality. */
  362. size_t val = rotr_sz ((size_t) data, 3);
  363. return val % n;
  364. }
  365. /* If the user passes a NULL comparator, we use pointer comparison. */
  366. static bool
  367. raw_comparator (const void *a, const void *b)
  368. {
  369. return a == b;
  370. }
  371. /* For the given hash TABLE, check the user supplied tuning structure for
  372. reasonable values, and return true if there is no gross error with it.
  373. Otherwise, definitively reset the TUNING field to some acceptable default
  374. in the hash table (that is, the user loses the right of further modifying
  375. tuning arguments), and return false. */
  376. static bool
  377. check_tuning (Hash_table *table)
  378. {
  379. const Hash_tuning *tuning = table->tuning;
  380. float epsilon;
  381. if (tuning == &default_tuning)
  382. return true;
  383. /* Be a bit stricter than mathematics would require, so that
  384. rounding errors in size calculations do not cause allocations to
  385. fail to grow or shrink as they should. The smallest allocation
  386. is 11 (due to next_prime's algorithm), so an epsilon of 0.1
  387. should be good enough. */
  388. epsilon = 0.1f;
  389. if (epsilon < tuning->growth_threshold
  390. && tuning->growth_threshold < 1 - epsilon
  391. && 1 + epsilon < tuning->growth_factor
  392. && 0 <= tuning->shrink_threshold
  393. && tuning->shrink_threshold + epsilon < tuning->shrink_factor
  394. && tuning->shrink_factor <= 1
  395. && tuning->shrink_threshold + epsilon < tuning->growth_threshold)
  396. return true;
  397. table->tuning = &default_tuning;
  398. return false;
  399. }
  400. /* Compute the size of the bucket array for the given CANDIDATE and
  401. TUNING, or return 0 if there is no possible way to allocate that
  402. many entries. */
  403. static size_t _GL_ATTRIBUTE_PURE
  404. compute_bucket_size (size_t candidate, const Hash_tuning *tuning)
  405. {
  406. if (!tuning->is_n_buckets)
  407. {
  408. float new_candidate = candidate / tuning->growth_threshold;
  409. if (SIZE_MAX <= new_candidate)
  410. return 0;
  411. candidate = new_candidate;
  412. }
  413. candidate = next_prime (candidate);
  414. if (xalloc_oversized (candidate, sizeof (struct hash_entry *)))
  415. return 0;
  416. return candidate;
  417. }
  418. Hash_table *
  419. hash_initialize (size_t candidate, const Hash_tuning *tuning,
  420. Hash_hasher hasher, Hash_comparator comparator,
  421. Hash_data_freer data_freer)
  422. {
  423. Hash_table *table;
  424. if (hasher == NULL)
  425. hasher = raw_hasher;
  426. if (comparator == NULL)
  427. comparator = raw_comparator;
  428. table = malloc (sizeof *table);
  429. if (table == NULL)
  430. return NULL;
  431. if (!tuning)
  432. tuning = &default_tuning;
  433. table->tuning = tuning;
  434. if (!check_tuning (table))
  435. {
  436. /* Fail if the tuning options are invalid. This is the only occasion
  437. when the user gets some feedback about it. Once the table is created,
  438. if the user provides invalid tuning options, we silently revert to
  439. using the defaults, and ignore further request to change the tuning
  440. options. */
  441. goto fail;
  442. }
  443. table->n_buckets = compute_bucket_size (candidate, tuning);
  444. if (!table->n_buckets)
  445. goto fail;
  446. table->bucket = calloc (table->n_buckets, sizeof *table->bucket);
  447. if (table->bucket == NULL)
  448. goto fail;
  449. table->bucket_limit = table->bucket + table->n_buckets;
  450. table->n_buckets_used = 0;
  451. table->n_entries = 0;
  452. table->hasher = hasher;
  453. table->comparator = comparator;
  454. table->data_freer = data_freer;
  455. table->free_entry_list = NULL;
  456. #if USE_OBSTACK
  457. obstack_init (&table->entry_stack);
  458. #endif
  459. return table;
  460. fail:
  461. free (table);
  462. return NULL;
  463. }
  464. void
  465. hash_clear (Hash_table *table)
  466. {
  467. struct hash_entry *bucket;
  468. for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
  469. {
  470. if (bucket->data)
  471. {
  472. struct hash_entry *cursor;
  473. struct hash_entry *next;
  474. /* Free the bucket overflow. */
  475. for (cursor = bucket->next; cursor; cursor = next)
  476. {
  477. if (table->data_freer)
  478. table->data_freer (cursor->data);
  479. cursor->data = NULL;
  480. next = cursor->next;
  481. /* Relinking is done one entry at a time, as it is to be expected
  482. that overflows are either rare or short. */
  483. cursor->next = table->free_entry_list;
  484. table->free_entry_list = cursor;
  485. }
  486. /* Free the bucket head. */
  487. if (table->data_freer)
  488. table->data_freer (bucket->data);
  489. bucket->data = NULL;
  490. bucket->next = NULL;
  491. }
  492. }
  493. table->n_buckets_used = 0;
  494. table->n_entries = 0;
  495. }
  496. void
  497. hash_free (Hash_table *table)
  498. {
  499. struct hash_entry *bucket;
  500. struct hash_entry *cursor;
  501. struct hash_entry *next;
  502. /* Call the user data_freer function. */
  503. if (table->data_freer && table->n_entries)
  504. {
  505. for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
  506. {
  507. if (bucket->data)
  508. {
  509. for (cursor = bucket; cursor; cursor = cursor->next)
  510. table->data_freer (cursor->data);
  511. }
  512. }
  513. }
  514. #if USE_OBSTACK
  515. obstack_free (&table->entry_stack, NULL);
  516. #else
  517. /* Free all bucket overflowed entries. */
  518. for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
  519. {
  520. for (cursor = bucket->next; cursor; cursor = next)
  521. {
  522. next = cursor->next;
  523. free (cursor);
  524. }
  525. }
  526. /* Also reclaim the internal list of previously freed entries. */
  527. for (cursor = table->free_entry_list; cursor; cursor = next)
  528. {
  529. next = cursor->next;
  530. free (cursor);
  531. }
  532. #endif
  533. /* Free the remainder of the hash table structure. */
  534. free (table->bucket);
  535. free (table);
  536. }
  537. /* Insertion and deletion. */
  538. /* Get a new hash entry for a bucket overflow, possibly by recycling a
  539. previously freed one. If this is not possible, allocate a new one. */
  540. static struct hash_entry *
  541. allocate_entry (Hash_table *table)
  542. {
  543. struct hash_entry *new;
  544. if (table->free_entry_list)
  545. {
  546. new = table->free_entry_list;
  547. table->free_entry_list = new->next;
  548. }
  549. else
  550. {
  551. #if USE_OBSTACK
  552. new = obstack_alloc (&table->entry_stack, sizeof *new);
  553. #else
  554. new = malloc (sizeof *new);
  555. #endif
  556. }
  557. return new;
  558. }
  559. /* Free a hash entry which was part of some bucket overflow,
  560. saving it for later recycling. */
  561. static void
  562. free_entry (Hash_table *table, struct hash_entry *entry)
  563. {
  564. entry->data = NULL;
  565. entry->next = table->free_entry_list;
  566. table->free_entry_list = entry;
  567. }
  568. /* This private function is used to help with insertion and deletion. When
  569. ENTRY matches an entry in the table, return a pointer to the corresponding
  570. user data and set *BUCKET_HEAD to the head of the selected bucket.
  571. Otherwise, return NULL. When DELETE is true and ENTRY matches an entry in
  572. the table, unlink the matching entry. */
  573. static void *
  574. hash_find_entry (Hash_table *table, const void *entry,
  575. struct hash_entry **bucket_head, bool delete)
  576. {
  577. struct hash_entry *bucket = safe_hasher (table, entry);
  578. struct hash_entry *cursor;
  579. *bucket_head = bucket;
  580. /* Test for empty bucket. */
  581. if (bucket->data == NULL)
  582. return NULL;
  583. /* See if the entry is the first in the bucket. */
  584. if (entry == bucket->data || table->comparator (entry, bucket->data))
  585. {
  586. void *data = bucket->data;
  587. if (delete)
  588. {
  589. if (bucket->next)
  590. {
  591. struct hash_entry *next = bucket->next;
  592. /* Bump the first overflow entry into the bucket head, then save
  593. the previous first overflow entry for later recycling. */
  594. *bucket = *next;
  595. free_entry (table, next);
  596. }
  597. else
  598. {
  599. bucket->data = NULL;
  600. }
  601. }
  602. return data;
  603. }
  604. /* Scan the bucket overflow. */
  605. for (cursor = bucket; cursor->next; cursor = cursor->next)
  606. {
  607. if (entry == cursor->next->data
  608. || table->comparator (entry, cursor->next->data))
  609. {
  610. void *data = cursor->next->data;
  611. if (delete)
  612. {
  613. struct hash_entry *next = cursor->next;
  614. /* Unlink the entry to delete, then save the freed entry for later
  615. recycling. */
  616. cursor->next = next->next;
  617. free_entry (table, next);
  618. }
  619. return data;
  620. }
  621. }
  622. /* No entry found. */
  623. return NULL;
  624. }
  625. /* Internal helper, to move entries from SRC to DST. Both tables must
  626. share the same free entry list. If SAFE, only move overflow
  627. entries, saving bucket heads for later, so that no allocations will
  628. occur. Return false if the free entry list is exhausted and an
  629. allocation fails. */
  630. static bool
  631. transfer_entries (Hash_table *dst, Hash_table *src, bool safe)
  632. {
  633. struct hash_entry *bucket;
  634. struct hash_entry *cursor;
  635. struct hash_entry *next;
  636. for (bucket = src->bucket; bucket < src->bucket_limit; bucket++)
  637. if (bucket->data)
  638. {
  639. void *data;
  640. struct hash_entry *new_bucket;
  641. /* Within each bucket, transfer overflow entries first and
  642. then the bucket head, to minimize memory pressure. After
  643. all, the only time we might allocate is when moving the
  644. bucket head, but moving overflow entries first may create
  645. free entries that can be recycled by the time we finally
  646. get to the bucket head. */
  647. for (cursor = bucket->next; cursor; cursor = next)
  648. {
  649. data = cursor->data;
  650. new_bucket = safe_hasher (dst, data);
  651. next = cursor->next;
  652. if (new_bucket->data)
  653. {
  654. /* Merely relink an existing entry, when moving from a
  655. bucket overflow into a bucket overflow. */
  656. cursor->next = new_bucket->next;
  657. new_bucket->next = cursor;
  658. }
  659. else
  660. {
  661. /* Free an existing entry, when moving from a bucket
  662. overflow into a bucket header. */
  663. new_bucket->data = data;
  664. dst->n_buckets_used++;
  665. free_entry (dst, cursor);
  666. }
  667. }
  668. /* Now move the bucket head. Be sure that if we fail due to
  669. allocation failure that the src table is in a consistent
  670. state. */
  671. data = bucket->data;
  672. bucket->next = NULL;
  673. if (safe)
  674. continue;
  675. new_bucket = safe_hasher (dst, data);
  676. if (new_bucket->data)
  677. {
  678. /* Allocate or recycle an entry, when moving from a bucket
  679. header into a bucket overflow. */
  680. struct hash_entry *new_entry = allocate_entry (dst);
  681. if (new_entry == NULL)
  682. return false;
  683. new_entry->data = data;
  684. new_entry->next = new_bucket->next;
  685. new_bucket->next = new_entry;
  686. }
  687. else
  688. {
  689. /* Move from one bucket header to another. */
  690. new_bucket->data = data;
  691. dst->n_buckets_used++;
  692. }
  693. bucket->data = NULL;
  694. src->n_buckets_used--;
  695. }
  696. return true;
  697. }
  698. bool
  699. hash_rehash (Hash_table *table, size_t candidate)
  700. {
  701. Hash_table storage;
  702. Hash_table *new_table;
  703. size_t new_size = compute_bucket_size (candidate, table->tuning);
  704. if (!new_size)
  705. return false;
  706. if (new_size == table->n_buckets)
  707. return true;
  708. new_table = &storage;
  709. new_table->bucket = calloc (new_size, sizeof *new_table->bucket);
  710. if (new_table->bucket == NULL)
  711. return false;
  712. new_table->n_buckets = new_size;
  713. new_table->bucket_limit = new_table->bucket + new_size;
  714. new_table->n_buckets_used = 0;
  715. new_table->n_entries = 0;
  716. new_table->tuning = table->tuning;
  717. new_table->hasher = table->hasher;
  718. new_table->comparator = table->comparator;
  719. new_table->data_freer = table->data_freer;
  720. /* In order for the transfer to successfully complete, we need
  721. additional overflow entries when distinct buckets in the old
  722. table collide into a common bucket in the new table. The worst
  723. case possible is a hasher that gives a good spread with the old
  724. size, but returns a constant with the new size; if we were to
  725. guarantee table->n_buckets_used-1 free entries in advance, then
  726. the transfer would be guaranteed to not allocate memory.
  727. However, for large tables, a guarantee of no further allocation
  728. introduces a lot of extra memory pressure, all for an unlikely
  729. corner case (most rehashes reduce, rather than increase, the
  730. number of overflow entries needed). So, we instead ensure that
  731. the transfer process can be reversed if we hit a memory
  732. allocation failure mid-transfer. */
  733. /* Merely reuse the extra old space into the new table. */
  734. #if USE_OBSTACK
  735. new_table->entry_stack = table->entry_stack;
  736. #endif
  737. new_table->free_entry_list = table->free_entry_list;
  738. if (transfer_entries (new_table, table, false))
  739. {
  740. /* Entries transferred successfully; tie up the loose ends. */
  741. free (table->bucket);
  742. table->bucket = new_table->bucket;
  743. table->bucket_limit = new_table->bucket_limit;
  744. table->n_buckets = new_table->n_buckets;
  745. table->n_buckets_used = new_table->n_buckets_used;
  746. table->free_entry_list = new_table->free_entry_list;
  747. /* table->n_entries and table->entry_stack already hold their value. */
  748. return true;
  749. }
  750. /* We've allocated new_table->bucket (and possibly some entries),
  751. exhausted the free list, and moved some but not all entries into
  752. new_table. We must undo the partial move before returning
  753. failure. The only way to get into this situation is if new_table
  754. uses fewer buckets than the old table, so we will reclaim some
  755. free entries as overflows in the new table are put back into
  756. distinct buckets in the old table.
  757. There are some pathological cases where a single pass through the
  758. table requires more intermediate overflow entries than using two
  759. passes. Two passes give worse cache performance and takes
  760. longer, but at this point, we're already out of memory, so slow
  761. and safe is better than failure. */
  762. table->free_entry_list = new_table->free_entry_list;
  763. if (! (transfer_entries (table, new_table, true)
  764. && transfer_entries (table, new_table, false)))
  765. abort ();
  766. /* table->n_entries already holds its value. */
  767. free (new_table->bucket);
  768. return false;
  769. }
  770. int
  771. hash_insert_if_absent (Hash_table *table, void const *entry,
  772. void const **matched_ent)
  773. {
  774. void *data;
  775. struct hash_entry *bucket;
  776. /* The caller cannot insert a NULL entry, since hash_lookup returns NULL
  777. to indicate "not found", and hash_find_entry uses "bucket->data == NULL"
  778. to indicate an empty bucket. */
  779. if (! entry)
  780. abort ();
  781. /* If there's a matching entry already in the table, return that. */
  782. if ((data = hash_find_entry (table, entry, &bucket, false)) != NULL)
  783. {
  784. if (matched_ent)
  785. *matched_ent = data;
  786. return 0;
  787. }
  788. /* If the growth threshold of the buckets in use has been reached, increase
  789. the table size and rehash. There's no point in checking the number of
  790. entries: if the hashing function is ill-conditioned, rehashing is not
  791. likely to improve it. */
  792. if (table->n_buckets_used
  793. > table->tuning->growth_threshold * table->n_buckets)
  794. {
  795. /* Check more fully, before starting real work. If tuning arguments
  796. became invalid, the second check will rely on proper defaults. */
  797. check_tuning (table);
  798. if (table->n_buckets_used
  799. > table->tuning->growth_threshold * table->n_buckets)
  800. {
  801. const Hash_tuning *tuning = table->tuning;
  802. float candidate =
  803. (tuning->is_n_buckets
  804. ? (table->n_buckets * tuning->growth_factor)
  805. : (table->n_buckets * tuning->growth_factor
  806. * tuning->growth_threshold));
  807. if (SIZE_MAX <= candidate)
  808. return -1;
  809. /* If the rehash fails, arrange to return NULL. */
  810. if (!hash_rehash (table, candidate))
  811. return -1;
  812. /* Update the bucket we are interested in. */
  813. if (hash_find_entry (table, entry, &bucket, false) != NULL)
  814. abort ();
  815. }
  816. }
  817. /* ENTRY is not matched, it should be inserted. */
  818. if (bucket->data)
  819. {
  820. struct hash_entry *new_entry = allocate_entry (table);
  821. if (new_entry == NULL)
  822. return -1;
  823. /* Add ENTRY in the overflow of the bucket. */
  824. new_entry->data = (void *) entry;
  825. new_entry->next = bucket->next;
  826. bucket->next = new_entry;
  827. table->n_entries++;
  828. return 1;
  829. }
  830. /* Add ENTRY right in the bucket head. */
  831. bucket->data = (void *) entry;
  832. table->n_entries++;
  833. table->n_buckets_used++;
  834. return 1;
  835. }
  836. void *
  837. hash_insert (Hash_table *table, void const *entry)
  838. {
  839. void const *matched_ent;
  840. int err = hash_insert_if_absent (table, entry, &matched_ent);
  841. return (err == -1
  842. ? NULL
  843. : (void *) (err == 0 ? matched_ent : entry));
  844. }
  845. void *
  846. hash_remove (Hash_table *table, const void *entry)
  847. {
  848. void *data;
  849. struct hash_entry *bucket;
  850. data = hash_find_entry (table, entry, &bucket, true);
  851. if (!data)
  852. return NULL;
  853. table->n_entries--;
  854. if (!bucket->data)
  855. {
  856. table->n_buckets_used--;
  857. /* If the shrink threshold of the buckets in use has been reached,
  858. rehash into a smaller table. */
  859. if (table->n_buckets_used
  860. < table->tuning->shrink_threshold * table->n_buckets)
  861. {
  862. /* Check more fully, before starting real work. If tuning arguments
  863. became invalid, the second check will rely on proper defaults. */
  864. check_tuning (table);
  865. if (table->n_buckets_used
  866. < table->tuning->shrink_threshold * table->n_buckets)
  867. {
  868. const Hash_tuning *tuning = table->tuning;
  869. size_t candidate =
  870. (tuning->is_n_buckets
  871. ? table->n_buckets * tuning->shrink_factor
  872. : (table->n_buckets * tuning->shrink_factor
  873. * tuning->growth_threshold));
  874. if (!hash_rehash (table, candidate))
  875. {
  876. /* Failure to allocate memory in an attempt to
  877. shrink the table is not fatal. But since memory
  878. is low, we can at least be kind and free any
  879. spare entries, rather than keeping them tied up
  880. in the free entry list. */
  881. #if ! USE_OBSTACK
  882. struct hash_entry *cursor = table->free_entry_list;
  883. struct hash_entry *next;
  884. while (cursor)
  885. {
  886. next = cursor->next;
  887. free (cursor);
  888. cursor = next;
  889. }
  890. table->free_entry_list = NULL;
  891. #endif
  892. }
  893. }
  894. }
  895. }
  896. return data;
  897. }
  898. void *
  899. hash_delete (Hash_table *table, const void *entry)
  900. {
  901. return hash_remove (table, entry);
  902. }
  903. /* Testing. */
  904. #if TESTING
  905. void
  906. hash_print (const Hash_table *table)
  907. {
  908. struct hash_entry *bucket = (struct hash_entry *) table->bucket;
  909. for ( ; bucket < table->bucket_limit; bucket++)
  910. {
  911. struct hash_entry *cursor;
  912. if (bucket)
  913. printf ("%lu:\n", (unsigned long int) (bucket - table->bucket));
  914. for (cursor = bucket; cursor; cursor = cursor->next)
  915. {
  916. char const *s = cursor->data;
  917. /* FIXME */
  918. if (s)
  919. printf (" %s\n", s);
  920. }
  921. }
  922. }
  923. #endif /* TESTING */