hash.c 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  1. /* hash - hashing table processing.
  2. Copyright (C) 1998-2004, 2006-2007, 2009-2013 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 <http://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. /* The following few functions provide information about the overall hash
  116. table organization: the number of entries, number of buckets and maximum
  117. length of buckets. */
  118. /* Return the number of buckets in the hash table. The table size, the total
  119. number of buckets (used plus unused), or the maximum number of slots, are
  120. the same quantity. */
  121. size_t
  122. hash_get_n_buckets (const Hash_table *table)
  123. {
  124. return table->n_buckets;
  125. }
  126. /* Return the number of slots in use (non-empty buckets). */
  127. size_t
  128. hash_get_n_buckets_used (const Hash_table *table)
  129. {
  130. return table->n_buckets_used;
  131. }
  132. /* Return the number of active entries. */
  133. size_t
  134. hash_get_n_entries (const Hash_table *table)
  135. {
  136. return table->n_entries;
  137. }
  138. /* Return the length of the longest chain (bucket). */
  139. size_t
  140. hash_get_max_bucket_length (const Hash_table *table)
  141. {
  142. struct hash_entry const *bucket;
  143. size_t max_bucket_length = 0;
  144. for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
  145. {
  146. if (bucket->data)
  147. {
  148. struct hash_entry const *cursor = bucket;
  149. size_t bucket_length = 1;
  150. while (cursor = cursor->next, cursor)
  151. bucket_length++;
  152. if (bucket_length > max_bucket_length)
  153. max_bucket_length = bucket_length;
  154. }
  155. }
  156. return max_bucket_length;
  157. }
  158. /* Do a mild validation of a hash table, by traversing it and checking two
  159. statistics. */
  160. bool
  161. hash_table_ok (const Hash_table *table)
  162. {
  163. struct hash_entry const *bucket;
  164. size_t n_buckets_used = 0;
  165. size_t n_entries = 0;
  166. for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
  167. {
  168. if (bucket->data)
  169. {
  170. struct hash_entry const *cursor = bucket;
  171. /* Count bucket head. */
  172. n_buckets_used++;
  173. n_entries++;
  174. /* Count bucket overflow. */
  175. while (cursor = cursor->next, cursor)
  176. n_entries++;
  177. }
  178. }
  179. if (n_buckets_used == table->n_buckets_used && n_entries == table->n_entries)
  180. return true;
  181. return false;
  182. }
  183. void
  184. hash_print_statistics (const Hash_table *table, FILE *stream)
  185. {
  186. size_t n_entries = hash_get_n_entries (table);
  187. size_t n_buckets = hash_get_n_buckets (table);
  188. size_t n_buckets_used = hash_get_n_buckets_used (table);
  189. size_t max_bucket_length = hash_get_max_bucket_length (table);
  190. fprintf (stream, "# entries: %lu\n", (unsigned long int) n_entries);
  191. fprintf (stream, "# buckets: %lu\n", (unsigned long int) n_buckets);
  192. fprintf (stream, "# buckets used: %lu (%.2f%%)\n",
  193. (unsigned long int) n_buckets_used,
  194. (100.0 * n_buckets_used) / n_buckets);
  195. fprintf (stream, "max bucket length: %lu\n",
  196. (unsigned long int) max_bucket_length);
  197. }
  198. /* Hash KEY and return a pointer to the selected bucket.
  199. If TABLE->hasher misbehaves, abort. */
  200. static struct hash_entry *
  201. safe_hasher (const Hash_table *table, const void *key)
  202. {
  203. size_t n = table->hasher (key, table->n_buckets);
  204. if (! (n < table->n_buckets))
  205. abort ();
  206. return table->bucket + n;
  207. }
  208. /* If ENTRY matches an entry already in the hash table, return the
  209. entry from the table. Otherwise, return NULL. */
  210. void *
  211. hash_lookup (const Hash_table *table, const void *entry)
  212. {
  213. struct hash_entry const *bucket = safe_hasher (table, entry);
  214. struct hash_entry const *cursor;
  215. if (bucket->data == NULL)
  216. return NULL;
  217. for (cursor = bucket; cursor; cursor = cursor->next)
  218. if (entry == cursor->data || table->comparator (entry, cursor->data))
  219. return cursor->data;
  220. return NULL;
  221. }
  222. /* Walking. */
  223. /* The functions in this page traverse the hash table and process the
  224. contained entries. For the traversal to work properly, the hash table
  225. should not be resized nor modified while any particular entry is being
  226. processed. In particular, entries should not be added, and an entry
  227. may be removed only if there is no shrink threshold and the entry being
  228. removed has already been passed to hash_get_next. */
  229. /* Return the first data in the table, or NULL if the table is empty. */
  230. void *
  231. hash_get_first (const Hash_table *table)
  232. {
  233. struct hash_entry const *bucket;
  234. if (table->n_entries == 0)
  235. return NULL;
  236. for (bucket = table->bucket; ; bucket++)
  237. if (! (bucket < table->bucket_limit))
  238. abort ();
  239. else if (bucket->data)
  240. return bucket->data;
  241. }
  242. /* Return the user data for the entry following ENTRY, where ENTRY has been
  243. returned by a previous call to either 'hash_get_first' or 'hash_get_next'.
  244. Return NULL if there are no more entries. */
  245. void *
  246. hash_get_next (const Hash_table *table, const void *entry)
  247. {
  248. struct hash_entry const *bucket = safe_hasher (table, entry);
  249. struct hash_entry const *cursor;
  250. /* Find next entry in the same bucket. */
  251. cursor = bucket;
  252. do
  253. {
  254. if (cursor->data == entry && cursor->next)
  255. return cursor->next->data;
  256. cursor = cursor->next;
  257. }
  258. while (cursor != NULL);
  259. /* Find first entry in any subsequent bucket. */
  260. while (++bucket < table->bucket_limit)
  261. if (bucket->data)
  262. return bucket->data;
  263. /* None found. */
  264. return NULL;
  265. }
  266. /* Fill BUFFER with pointers to active user entries in the hash table, then
  267. return the number of pointers copied. Do not copy more than BUFFER_SIZE
  268. pointers. */
  269. size_t
  270. hash_get_entries (const Hash_table *table, void **buffer,
  271. size_t buffer_size)
  272. {
  273. size_t counter = 0;
  274. struct hash_entry const *bucket;
  275. struct hash_entry const *cursor;
  276. for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
  277. {
  278. if (bucket->data)
  279. {
  280. for (cursor = bucket; cursor; cursor = cursor->next)
  281. {
  282. if (counter >= buffer_size)
  283. return counter;
  284. buffer[counter++] = cursor->data;
  285. }
  286. }
  287. }
  288. return counter;
  289. }
  290. /* Call a PROCESSOR function for each entry of a hash table, and return the
  291. number of entries for which the processor function returned success. A
  292. pointer to some PROCESSOR_DATA which will be made available to each call to
  293. the processor function. The PROCESSOR accepts two arguments: the first is
  294. the user entry being walked into, the second is the value of PROCESSOR_DATA
  295. as received. The walking continue for as long as the PROCESSOR function
  296. returns nonzero. When it returns zero, the walking is interrupted. */
  297. size_t
  298. hash_do_for_each (const Hash_table *table, Hash_processor processor,
  299. void *processor_data)
  300. {
  301. size_t counter = 0;
  302. struct hash_entry const *bucket;
  303. struct hash_entry const *cursor;
  304. for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
  305. {
  306. if (bucket->data)
  307. {
  308. for (cursor = bucket; cursor; cursor = cursor->next)
  309. {
  310. if (! processor (cursor->data, processor_data))
  311. return counter;
  312. counter++;
  313. }
  314. }
  315. }
  316. return counter;
  317. }
  318. /* Allocation and clean-up. */
  319. /* Return a hash index for a NUL-terminated STRING between 0 and N_BUCKETS-1.
  320. This is a convenience routine for constructing other hashing functions. */
  321. #if USE_DIFF_HASH
  322. /* About hashings, Paul Eggert writes to me (FP), on 1994-01-01: "Please see
  323. B. J. McKenzie, R. Harries & T. Bell, Selecting a hashing algorithm,
  324. Software--practice & experience 20, 2 (Feb 1990), 209-224. Good hash
  325. algorithms tend to be domain-specific, so what's good for [diffutils'] io.c
  326. may not be good for your application." */
  327. size_t
  328. hash_string (const char *string, size_t n_buckets)
  329. {
  330. # define HASH_ONE_CHAR(Value, Byte) \
  331. ((Byte) + rotl_sz (Value, 7))
  332. size_t value = 0;
  333. unsigned char ch;
  334. for (; (ch = *string); string++)
  335. value = HASH_ONE_CHAR (value, ch);
  336. return value % n_buckets;
  337. # undef HASH_ONE_CHAR
  338. }
  339. #else /* not USE_DIFF_HASH */
  340. /* This one comes from 'recode', and performs a bit better than the above as
  341. per a few experiments. It is inspired from a hashing routine found in the
  342. very old Cyber 'snoop', itself written in typical Greg Mansfield style.
  343. (By the way, what happened to this excellent man? Is he still alive?) */
  344. size_t
  345. hash_string (const char *string, size_t n_buckets)
  346. {
  347. size_t value = 0;
  348. unsigned char ch;
  349. for (; (ch = *string); string++)
  350. value = (value * 31 + ch) % n_buckets;
  351. return value;
  352. }
  353. #endif /* not USE_DIFF_HASH */
  354. /* Return true if CANDIDATE is a prime number. CANDIDATE should be an odd
  355. number at least equal to 11. */
  356. static bool _GL_ATTRIBUTE_CONST
  357. is_prime (size_t candidate)
  358. {
  359. size_t divisor = 3;
  360. size_t square = divisor * divisor;
  361. while (square < candidate && (candidate % divisor))
  362. {
  363. divisor++;
  364. square += 4 * divisor;
  365. divisor++;
  366. }
  367. return (candidate % divisor ? true : false);
  368. }
  369. /* Round a given CANDIDATE number up to the nearest prime, and return that
  370. prime. Primes lower than 10 are merely skipped. */
  371. static size_t _GL_ATTRIBUTE_CONST
  372. next_prime (size_t candidate)
  373. {
  374. /* Skip small primes. */
  375. if (candidate < 10)
  376. candidate = 10;
  377. /* Make it definitely odd. */
  378. candidate |= 1;
  379. while (SIZE_MAX != candidate && !is_prime (candidate))
  380. candidate += 2;
  381. return candidate;
  382. }
  383. void
  384. hash_reset_tuning (Hash_tuning *tuning)
  385. {
  386. *tuning = default_tuning;
  387. }
  388. /* If the user passes a NULL hasher, we hash the raw pointer. */
  389. static size_t
  390. raw_hasher (const void *data, size_t n)
  391. {
  392. /* When hashing unique pointers, it is often the case that they were
  393. generated by malloc and thus have the property that the low-order
  394. bits are 0. As this tends to give poorer performance with small
  395. tables, we rotate the pointer value before performing division,
  396. in an attempt to improve hash quality. */
  397. size_t val = rotr_sz ((size_t) data, 3);
  398. return val % n;
  399. }
  400. /* If the user passes a NULL comparator, we use pointer comparison. */
  401. static bool
  402. raw_comparator (const void *a, const void *b)
  403. {
  404. return a == b;
  405. }
  406. /* For the given hash TABLE, check the user supplied tuning structure for
  407. reasonable values, and return true if there is no gross error with it.
  408. Otherwise, definitively reset the TUNING field to some acceptable default
  409. in the hash table (that is, the user loses the right of further modifying
  410. tuning arguments), and return false. */
  411. static bool
  412. check_tuning (Hash_table *table)
  413. {
  414. const Hash_tuning *tuning = table->tuning;
  415. float epsilon;
  416. if (tuning == &default_tuning)
  417. return true;
  418. /* Be a bit stricter than mathematics would require, so that
  419. rounding errors in size calculations do not cause allocations to
  420. fail to grow or shrink as they should. The smallest allocation
  421. is 11 (due to next_prime's algorithm), so an epsilon of 0.1
  422. should be good enough. */
  423. epsilon = 0.1f;
  424. if (epsilon < tuning->growth_threshold
  425. && tuning->growth_threshold < 1 - epsilon
  426. && 1 + epsilon < tuning->growth_factor
  427. && 0 <= tuning->shrink_threshold
  428. && tuning->shrink_threshold + epsilon < tuning->shrink_factor
  429. && tuning->shrink_factor <= 1
  430. && tuning->shrink_threshold + epsilon < tuning->growth_threshold)
  431. return true;
  432. table->tuning = &default_tuning;
  433. return false;
  434. }
  435. /* Compute the size of the bucket array for the given CANDIDATE and
  436. TUNING, or return 0 if there is no possible way to allocate that
  437. many entries. */
  438. static size_t _GL_ATTRIBUTE_PURE
  439. compute_bucket_size (size_t candidate, const Hash_tuning *tuning)
  440. {
  441. if (!tuning->is_n_buckets)
  442. {
  443. float new_candidate = candidate / tuning->growth_threshold;
  444. if (SIZE_MAX <= new_candidate)
  445. return 0;
  446. candidate = new_candidate;
  447. }
  448. candidate = next_prime (candidate);
  449. if (xalloc_oversized (candidate, sizeof (struct hash_entry *)))
  450. return 0;
  451. return candidate;
  452. }
  453. /* Allocate and return a new hash table, or NULL upon failure. The initial
  454. number of buckets is automatically selected so as to _guarantee_ that you
  455. may insert at least CANDIDATE different user entries before any growth of
  456. the hash table size occurs. So, if have a reasonably tight a-priori upper
  457. bound on the number of entries you intend to insert in the hash table, you
  458. may save some table memory and insertion time, by specifying it here. If
  459. the IS_N_BUCKETS field of the TUNING structure is true, the CANDIDATE
  460. argument has its meaning changed to the wanted number of buckets.
  461. TUNING points to a structure of user-supplied values, in case some fine
  462. tuning is wanted over the default behavior of the hasher. If TUNING is
  463. NULL, the default tuning parameters are used instead. If TUNING is
  464. provided but the values requested are out of bounds or might cause
  465. rounding errors, return NULL.
  466. The user-supplied HASHER function, when not NULL, accepts two
  467. arguments ENTRY and TABLE_SIZE. It computes, by hashing ENTRY contents, a
  468. slot number for that entry which should be in the range 0..TABLE_SIZE-1.
  469. This slot number is then returned.
  470. The user-supplied COMPARATOR function, when not NULL, accepts two
  471. arguments pointing to user data, it then returns true for a pair of entries
  472. that compare equal, or false otherwise. This function is internally called
  473. on entries which are already known to hash to the same bucket index,
  474. but which are distinct pointers.
  475. The user-supplied DATA_FREER function, when not NULL, may be later called
  476. with the user data as an argument, just before the entry containing the
  477. data gets freed. This happens from within 'hash_free' or 'hash_clear'.
  478. You should specify this function only if you want these functions to free
  479. all of your 'data' data. This is typically the case when your data is
  480. simply an auxiliary struct that you have malloc'd to aggregate several
  481. values. */
  482. Hash_table *
  483. hash_initialize (size_t candidate, const Hash_tuning *tuning,
  484. Hash_hasher hasher, Hash_comparator comparator,
  485. Hash_data_freer data_freer)
  486. {
  487. Hash_table *table;
  488. if (hasher == NULL)
  489. hasher = raw_hasher;
  490. if (comparator == NULL)
  491. comparator = raw_comparator;
  492. table = malloc (sizeof *table);
  493. if (table == NULL)
  494. return NULL;
  495. if (!tuning)
  496. tuning = &default_tuning;
  497. table->tuning = tuning;
  498. if (!check_tuning (table))
  499. {
  500. /* Fail if the tuning options are invalid. This is the only occasion
  501. when the user gets some feedback about it. Once the table is created,
  502. if the user provides invalid tuning options, we silently revert to
  503. using the defaults, and ignore further request to change the tuning
  504. options. */
  505. goto fail;
  506. }
  507. table->n_buckets = compute_bucket_size (candidate, tuning);
  508. if (!table->n_buckets)
  509. goto fail;
  510. table->bucket = calloc (table->n_buckets, sizeof *table->bucket);
  511. if (table->bucket == NULL)
  512. goto fail;
  513. table->bucket_limit = table->bucket + table->n_buckets;
  514. table->n_buckets_used = 0;
  515. table->n_entries = 0;
  516. table->hasher = hasher;
  517. table->comparator = comparator;
  518. table->data_freer = data_freer;
  519. table->free_entry_list = NULL;
  520. #if USE_OBSTACK
  521. obstack_init (&table->entry_stack);
  522. #endif
  523. return table;
  524. fail:
  525. free (table);
  526. return NULL;
  527. }
  528. /* Make all buckets empty, placing any chained entries on the free list.
  529. Apply the user-specified function data_freer (if any) to the datas of any
  530. affected entries. */
  531. void
  532. hash_clear (Hash_table *table)
  533. {
  534. struct hash_entry *bucket;
  535. for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
  536. {
  537. if (bucket->data)
  538. {
  539. struct hash_entry *cursor;
  540. struct hash_entry *next;
  541. /* Free the bucket overflow. */
  542. for (cursor = bucket->next; cursor; cursor = next)
  543. {
  544. if (table->data_freer)
  545. table->data_freer (cursor->data);
  546. cursor->data = NULL;
  547. next = cursor->next;
  548. /* Relinking is done one entry at a time, as it is to be expected
  549. that overflows are either rare or short. */
  550. cursor->next = table->free_entry_list;
  551. table->free_entry_list = cursor;
  552. }
  553. /* Free the bucket head. */
  554. if (table->data_freer)
  555. table->data_freer (bucket->data);
  556. bucket->data = NULL;
  557. bucket->next = NULL;
  558. }
  559. }
  560. table->n_buckets_used = 0;
  561. table->n_entries = 0;
  562. }
  563. /* Reclaim all storage associated with a hash table. If a data_freer
  564. function has been supplied by the user when the hash table was created,
  565. this function applies it to the data of each entry before freeing that
  566. entry. */
  567. void
  568. hash_free (Hash_table *table)
  569. {
  570. struct hash_entry *bucket;
  571. struct hash_entry *cursor;
  572. struct hash_entry *next;
  573. /* Call the user data_freer function. */
  574. if (table->data_freer && table->n_entries)
  575. {
  576. for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
  577. {
  578. if (bucket->data)
  579. {
  580. for (cursor = bucket; cursor; cursor = cursor->next)
  581. table->data_freer (cursor->data);
  582. }
  583. }
  584. }
  585. #if USE_OBSTACK
  586. obstack_free (&table->entry_stack, NULL);
  587. #else
  588. /* Free all bucket overflowed entries. */
  589. for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
  590. {
  591. for (cursor = bucket->next; cursor; cursor = next)
  592. {
  593. next = cursor->next;
  594. free (cursor);
  595. }
  596. }
  597. /* Also reclaim the internal list of previously freed entries. */
  598. for (cursor = table->free_entry_list; cursor; cursor = next)
  599. {
  600. next = cursor->next;
  601. free (cursor);
  602. }
  603. #endif
  604. /* Free the remainder of the hash table structure. */
  605. free (table->bucket);
  606. free (table);
  607. }
  608. /* Insertion and deletion. */
  609. /* Get a new hash entry for a bucket overflow, possibly by recycling a
  610. previously freed one. If this is not possible, allocate a new one. */
  611. static struct hash_entry *
  612. allocate_entry (Hash_table *table)
  613. {
  614. struct hash_entry *new;
  615. if (table->free_entry_list)
  616. {
  617. new = table->free_entry_list;
  618. table->free_entry_list = new->next;
  619. }
  620. else
  621. {
  622. #if USE_OBSTACK
  623. new = obstack_alloc (&table->entry_stack, sizeof *new);
  624. #else
  625. new = malloc (sizeof *new);
  626. #endif
  627. }
  628. return new;
  629. }
  630. /* Free a hash entry which was part of some bucket overflow,
  631. saving it for later recycling. */
  632. static void
  633. free_entry (Hash_table *table, struct hash_entry *entry)
  634. {
  635. entry->data = NULL;
  636. entry->next = table->free_entry_list;
  637. table->free_entry_list = entry;
  638. }
  639. /* This private function is used to help with insertion and deletion. When
  640. ENTRY matches an entry in the table, return a pointer to the corresponding
  641. user data and set *BUCKET_HEAD to the head of the selected bucket.
  642. Otherwise, return NULL. When DELETE is true and ENTRY matches an entry in
  643. the table, unlink the matching entry. */
  644. static void *
  645. hash_find_entry (Hash_table *table, const void *entry,
  646. struct hash_entry **bucket_head, bool delete)
  647. {
  648. struct hash_entry *bucket = safe_hasher (table, entry);
  649. struct hash_entry *cursor;
  650. *bucket_head = bucket;
  651. /* Test for empty bucket. */
  652. if (bucket->data == NULL)
  653. return NULL;
  654. /* See if the entry is the first in the bucket. */
  655. if (entry == bucket->data || table->comparator (entry, bucket->data))
  656. {
  657. void *data = bucket->data;
  658. if (delete)
  659. {
  660. if (bucket->next)
  661. {
  662. struct hash_entry *next = bucket->next;
  663. /* Bump the first overflow entry into the bucket head, then save
  664. the previous first overflow entry for later recycling. */
  665. *bucket = *next;
  666. free_entry (table, next);
  667. }
  668. else
  669. {
  670. bucket->data = NULL;
  671. }
  672. }
  673. return data;
  674. }
  675. /* Scan the bucket overflow. */
  676. for (cursor = bucket; cursor->next; cursor = cursor->next)
  677. {
  678. if (entry == cursor->next->data
  679. || table->comparator (entry, cursor->next->data))
  680. {
  681. void *data = cursor->next->data;
  682. if (delete)
  683. {
  684. struct hash_entry *next = cursor->next;
  685. /* Unlink the entry to delete, then save the freed entry for later
  686. recycling. */
  687. cursor->next = next->next;
  688. free_entry (table, next);
  689. }
  690. return data;
  691. }
  692. }
  693. /* No entry found. */
  694. return NULL;
  695. }
  696. /* Internal helper, to move entries from SRC to DST. Both tables must
  697. share the same free entry list. If SAFE, only move overflow
  698. entries, saving bucket heads for later, so that no allocations will
  699. occur. Return false if the free entry list is exhausted and an
  700. allocation fails. */
  701. static bool
  702. transfer_entries (Hash_table *dst, Hash_table *src, bool safe)
  703. {
  704. struct hash_entry *bucket;
  705. struct hash_entry *cursor;
  706. struct hash_entry *next;
  707. for (bucket = src->bucket; bucket < src->bucket_limit; bucket++)
  708. if (bucket->data)
  709. {
  710. void *data;
  711. struct hash_entry *new_bucket;
  712. /* Within each bucket, transfer overflow entries first and
  713. then the bucket head, to minimize memory pressure. After
  714. all, the only time we might allocate is when moving the
  715. bucket head, but moving overflow entries first may create
  716. free entries that can be recycled by the time we finally
  717. get to the bucket head. */
  718. for (cursor = bucket->next; cursor; cursor = next)
  719. {
  720. data = cursor->data;
  721. new_bucket = safe_hasher (dst, data);
  722. next = cursor->next;
  723. if (new_bucket->data)
  724. {
  725. /* Merely relink an existing entry, when moving from a
  726. bucket overflow into a bucket overflow. */
  727. cursor->next = new_bucket->next;
  728. new_bucket->next = cursor;
  729. }
  730. else
  731. {
  732. /* Free an existing entry, when moving from a bucket
  733. overflow into a bucket header. */
  734. new_bucket->data = data;
  735. dst->n_buckets_used++;
  736. free_entry (dst, cursor);
  737. }
  738. }
  739. /* Now move the bucket head. Be sure that if we fail due to
  740. allocation failure that the src table is in a consistent
  741. state. */
  742. data = bucket->data;
  743. bucket->next = NULL;
  744. if (safe)
  745. continue;
  746. new_bucket = safe_hasher (dst, data);
  747. if (new_bucket->data)
  748. {
  749. /* Allocate or recycle an entry, when moving from a bucket
  750. header into a bucket overflow. */
  751. struct hash_entry *new_entry = allocate_entry (dst);
  752. if (new_entry == NULL)
  753. return false;
  754. new_entry->data = data;
  755. new_entry->next = new_bucket->next;
  756. new_bucket->next = new_entry;
  757. }
  758. else
  759. {
  760. /* Move from one bucket header to another. */
  761. new_bucket->data = data;
  762. dst->n_buckets_used++;
  763. }
  764. bucket->data = NULL;
  765. src->n_buckets_used--;
  766. }
  767. return true;
  768. }
  769. /* For an already existing hash table, change the number of buckets through
  770. specifying CANDIDATE. The contents of the hash table are preserved. The
  771. new number of buckets is automatically selected so as to _guarantee_ that
  772. the table may receive at least CANDIDATE different user entries, including
  773. those already in the table, before any other growth of the hash table size
  774. occurs. If TUNING->IS_N_BUCKETS is true, then CANDIDATE specifies the
  775. exact number of buckets desired. Return true iff the rehash succeeded. */
  776. bool
  777. hash_rehash (Hash_table *table, size_t candidate)
  778. {
  779. Hash_table storage;
  780. Hash_table *new_table;
  781. size_t new_size = compute_bucket_size (candidate, table->tuning);
  782. if (!new_size)
  783. return false;
  784. if (new_size == table->n_buckets)
  785. return true;
  786. new_table = &storage;
  787. new_table->bucket = calloc (new_size, sizeof *new_table->bucket);
  788. if (new_table->bucket == NULL)
  789. return false;
  790. new_table->n_buckets = new_size;
  791. new_table->bucket_limit = new_table->bucket + new_size;
  792. new_table->n_buckets_used = 0;
  793. new_table->n_entries = 0;
  794. new_table->tuning = table->tuning;
  795. new_table->hasher = table->hasher;
  796. new_table->comparator = table->comparator;
  797. new_table->data_freer = table->data_freer;
  798. /* In order for the transfer to successfully complete, we need
  799. additional overflow entries when distinct buckets in the old
  800. table collide into a common bucket in the new table. The worst
  801. case possible is a hasher that gives a good spread with the old
  802. size, but returns a constant with the new size; if we were to
  803. guarantee table->n_buckets_used-1 free entries in advance, then
  804. the transfer would be guaranteed to not allocate memory.
  805. However, for large tables, a guarantee of no further allocation
  806. introduces a lot of extra memory pressure, all for an unlikely
  807. corner case (most rehashes reduce, rather than increase, the
  808. number of overflow entries needed). So, we instead ensure that
  809. the transfer process can be reversed if we hit a memory
  810. allocation failure mid-transfer. */
  811. /* Merely reuse the extra old space into the new table. */
  812. #if USE_OBSTACK
  813. new_table->entry_stack = table->entry_stack;
  814. #endif
  815. new_table->free_entry_list = table->free_entry_list;
  816. if (transfer_entries (new_table, table, false))
  817. {
  818. /* Entries transferred successfully; tie up the loose ends. */
  819. free (table->bucket);
  820. table->bucket = new_table->bucket;
  821. table->bucket_limit = new_table->bucket_limit;
  822. table->n_buckets = new_table->n_buckets;
  823. table->n_buckets_used = new_table->n_buckets_used;
  824. table->free_entry_list = new_table->free_entry_list;
  825. /* table->n_entries and table->entry_stack already hold their value. */
  826. return true;
  827. }
  828. /* We've allocated new_table->bucket (and possibly some entries),
  829. exhausted the free list, and moved some but not all entries into
  830. new_table. We must undo the partial move before returning
  831. failure. The only way to get into this situation is if new_table
  832. uses fewer buckets than the old table, so we will reclaim some
  833. free entries as overflows in the new table are put back into
  834. distinct buckets in the old table.
  835. There are some pathological cases where a single pass through the
  836. table requires more intermediate overflow entries than using two
  837. passes. Two passes give worse cache performance and takes
  838. longer, but at this point, we're already out of memory, so slow
  839. and safe is better than failure. */
  840. table->free_entry_list = new_table->free_entry_list;
  841. if (! (transfer_entries (table, new_table, true)
  842. && transfer_entries (table, new_table, false)))
  843. abort ();
  844. /* table->n_entries already holds its value. */
  845. free (new_table->bucket);
  846. return false;
  847. }
  848. /* Insert ENTRY into hash TABLE if there is not already a matching entry.
  849. Return -1 upon memory allocation failure.
  850. Return 1 if insertion succeeded.
  851. Return 0 if there is already a matching entry in the table,
  852. and in that case, if MATCHED_ENT is non-NULL, set *MATCHED_ENT
  853. to that entry.
  854. This interface is easier to use than hash_insert when you must
  855. distinguish between the latter two cases. More importantly,
  856. hash_insert is unusable for some types of ENTRY values. When using
  857. hash_insert, the only way to distinguish those cases is to compare
  858. the return value and ENTRY. That works only when you can have two
  859. different ENTRY values that point to data that compares "equal". Thus,
  860. when the ENTRY value is a simple scalar, you must use
  861. hash_insert_if_absent. ENTRY must not be NULL. */
  862. int
  863. hash_insert_if_absent (Hash_table *table, void const *entry,
  864. void const **matched_ent)
  865. {
  866. void *data;
  867. struct hash_entry *bucket;
  868. /* The caller cannot insert a NULL entry, since hash_lookup returns NULL
  869. to indicate "not found", and hash_find_entry uses "bucket->data == NULL"
  870. to indicate an empty bucket. */
  871. if (! entry)
  872. abort ();
  873. /* If there's a matching entry already in the table, return that. */
  874. if ((data = hash_find_entry (table, entry, &bucket, false)) != NULL)
  875. {
  876. if (matched_ent)
  877. *matched_ent = data;
  878. return 0;
  879. }
  880. /* If the growth threshold of the buckets in use has been reached, increase
  881. the table size and rehash. There's no point in checking the number of
  882. entries: if the hashing function is ill-conditioned, rehashing is not
  883. likely to improve it. */
  884. if (table->n_buckets_used
  885. > table->tuning->growth_threshold * table->n_buckets)
  886. {
  887. /* Check more fully, before starting real work. If tuning arguments
  888. became invalid, the second check will rely on proper defaults. */
  889. check_tuning (table);
  890. if (table->n_buckets_used
  891. > table->tuning->growth_threshold * table->n_buckets)
  892. {
  893. const Hash_tuning *tuning = table->tuning;
  894. float candidate =
  895. (tuning->is_n_buckets
  896. ? (table->n_buckets * tuning->growth_factor)
  897. : (table->n_buckets * tuning->growth_factor
  898. * tuning->growth_threshold));
  899. if (SIZE_MAX <= candidate)
  900. return -1;
  901. /* If the rehash fails, arrange to return NULL. */
  902. if (!hash_rehash (table, candidate))
  903. return -1;
  904. /* Update the bucket we are interested in. */
  905. if (hash_find_entry (table, entry, &bucket, false) != NULL)
  906. abort ();
  907. }
  908. }
  909. /* ENTRY is not matched, it should be inserted. */
  910. if (bucket->data)
  911. {
  912. struct hash_entry *new_entry = allocate_entry (table);
  913. if (new_entry == NULL)
  914. return -1;
  915. /* Add ENTRY in the overflow of the bucket. */
  916. new_entry->data = (void *) entry;
  917. new_entry->next = bucket->next;
  918. bucket->next = new_entry;
  919. table->n_entries++;
  920. return 1;
  921. }
  922. /* Add ENTRY right in the bucket head. */
  923. bucket->data = (void *) entry;
  924. table->n_entries++;
  925. table->n_buckets_used++;
  926. return 1;
  927. }
  928. /* hash_insert0 is the deprecated name for hash_insert_if_absent.
  929. . */
  930. int
  931. hash_insert0 (Hash_table *table, void const *entry, void const **matched_ent)
  932. {
  933. return hash_insert_if_absent (table, entry, matched_ent);
  934. }
  935. /* If ENTRY matches an entry already in the hash table, return the pointer
  936. to the entry from the table. Otherwise, insert ENTRY and return ENTRY.
  937. Return NULL if the storage required for insertion cannot be allocated.
  938. This implementation does not support duplicate entries or insertion of
  939. NULL. */
  940. void *
  941. hash_insert (Hash_table *table, void const *entry)
  942. {
  943. void const *matched_ent;
  944. int err = hash_insert_if_absent (table, entry, &matched_ent);
  945. return (err == -1
  946. ? NULL
  947. : (void *) (err == 0 ? matched_ent : entry));
  948. }
  949. /* If ENTRY is already in the table, remove it and return the just-deleted
  950. data (the user may want to deallocate its storage). If ENTRY is not in the
  951. table, don't modify the table and return NULL. */
  952. void *
  953. hash_delete (Hash_table *table, const void *entry)
  954. {
  955. void *data;
  956. struct hash_entry *bucket;
  957. data = hash_find_entry (table, entry, &bucket, true);
  958. if (!data)
  959. return NULL;
  960. table->n_entries--;
  961. if (!bucket->data)
  962. {
  963. table->n_buckets_used--;
  964. /* If the shrink threshold of the buckets in use has been reached,
  965. rehash into a smaller table. */
  966. if (table->n_buckets_used
  967. < table->tuning->shrink_threshold * table->n_buckets)
  968. {
  969. /* Check more fully, before starting real work. If tuning arguments
  970. became invalid, the second check will rely on proper defaults. */
  971. check_tuning (table);
  972. if (table->n_buckets_used
  973. < table->tuning->shrink_threshold * table->n_buckets)
  974. {
  975. const Hash_tuning *tuning = table->tuning;
  976. size_t candidate =
  977. (tuning->is_n_buckets
  978. ? table->n_buckets * tuning->shrink_factor
  979. : (table->n_buckets * tuning->shrink_factor
  980. * tuning->growth_threshold));
  981. if (!hash_rehash (table, candidate))
  982. {
  983. /* Failure to allocate memory in an attempt to
  984. shrink the table is not fatal. But since memory
  985. is low, we can at least be kind and free any
  986. spare entries, rather than keeping them tied up
  987. in the free entry list. */
  988. #if ! USE_OBSTACK
  989. struct hash_entry *cursor = table->free_entry_list;
  990. struct hash_entry *next;
  991. while (cursor)
  992. {
  993. next = cursor->next;
  994. free (cursor);
  995. cursor = next;
  996. }
  997. table->free_entry_list = NULL;
  998. #endif
  999. }
  1000. }
  1001. }
  1002. }
  1003. return data;
  1004. }
  1005. /* Testing. */
  1006. #if TESTING
  1007. void
  1008. hash_print (const Hash_table *table)
  1009. {
  1010. struct hash_entry *bucket = (struct hash_entry *) table->bucket;
  1011. for ( ; bucket < table->bucket_limit; bucket++)
  1012. {
  1013. struct hash_entry *cursor;
  1014. if (bucket)
  1015. printf ("%lu:\n", (unsigned long int) (bucket - table->bucket));
  1016. for (cursor = bucket; cursor; cursor = cursor->next)
  1017. {
  1018. char const *s = cursor->data;
  1019. /* FIXME */
  1020. if (s)
  1021. printf (" %s\n", s);
  1022. }
  1023. }
  1024. }
  1025. #endif /* TESTING */