tweak comments
[gnulib.git] / lib / hash.c
1 /* hash - hashing table processing.
2    Copyright (C) 1998, 1999 Free Software Foundation, Inc.
3    Written by Jim Meyering, 1992.
4
5    This program is free software; you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 2, or (at your option)
8    any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program; if not, write to the Free Software Foundation,
17    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */
18
19 /* A generic hash table package.  */
20
21 /* Define USE_OBSTACK to 1 if you want the allocator to use obstacks instead
22    of malloc.  If you change USE_OBSTACK, you have to recompile!  */
23
24 #if HAVE_CONFIG_H
25 # include <config.h>
26 #endif
27 #if HAVE_STDLIB_H
28 # include <stdlib.h>
29 #endif
30 #if HAVE_STDBOOL_H
31 # include <stdbool.h>
32 #else
33 typedef enum {false = 0, true = 1} bool;
34 #endif
35 #include <stdio.h>
36 #include <assert.h>
37
38 #if !HAVE_DECL_FREE
39 void free ();
40 #endif
41 #if !HAVE_DECL_MALLOC
42 char *malloc ();
43 #endif
44
45 #if USE_OBSTACK
46 # include "obstack.h"
47 # ifndef obstack_chunk_alloc
48 #  define obstack_chunk_alloc malloc
49 # endif
50 # ifndef obstack_chunk_free
51 #  define obstack_chunk_free free
52 # endif
53 #endif
54
55 #include "hash.h"
56
57 /* A hash table contains many internal entries, each holding a pointer to
58    some user provided data (also called a user entry).  An entry indistinctly
59    refers to both the internal entry and its associated user entry.  A user
60    entry contents may be hashed by a randomization function (the hashing
61    function, or just `hasher' for short) into a number (or `slot') between 0
62    and the current table size.  At each slot position in the hash table,
63    starts a linked chain of entries for which the user data all hash to this
64    slot.  A bucket is the collection of all entries hashing to the same slot.
65
66    A good `hasher' function will distribute entries rather evenly in buckets.
67    In the ideal case, the length of each bucket is roughly the number of
68    entries divided by the table size.  Finding the slot for a data is usually
69    done in constant time by the `hasher', and the later finding of a precise
70    entry is linear in time with the size of the bucket.  Consequently, a
71    larger hash table size (that is, a larger number of buckets) is prone to
72    yielding shorter chains, *given* the `hasher' function behaves properly.
73
74    Long buckets slow down the lookup algorithm.  One might use big hash table
75    sizes in hope to reduce the average length of buckets, but this might
76    become inordinate, as unused slots in the hash table take some space.  The
77    best bet is to make sure you are using a good `hasher' function (beware
78    that those are not that easy to write! :-), and to use a table size
79    larger than the actual number of entries.  */
80
81 /* If an insertion makes the ratio of nonempty buckets to table size larger
82    than the growth threshold (a number between 0.0 and 1.0), then increase
83    the table size by multiplying by the growth factor (a number greater than
84    1.0).  The growth threshold defaults to 0.8, and the growth factor
85    defaults to 1.414, meaning that the table will have doubled its size
86    every second time 80% of the buckets get used.  */
87 #define DEFAULT_GROWTH_THRESHOLD 0.8
88 #define DEFAULT_GROWTH_FACTOR 1.414
89
90 /* If a deletion empties a bucket and causes the ratio of used buckets to
91    table size to become smaller than the shrink threshold (a number between
92    0.0 and 1.0), then shrink the table by multiplying by the shrink factor (a
93    number greater than the shrink threshold but smaller than 1.0).  The shrink
94    threshold and factor default to 0.0 and 1.0, meaning that the table never
95    shrinks.  */
96 #define DEFAULT_SHRINK_THRESHOLD 0.0
97 #define DEFAULT_SHRINK_FACTOR 1.0
98
99 /* Use this to initialize or reset a TUNING structure to
100    some sensible values. */
101 static const Hash_tuning default_tuning =
102   {
103     DEFAULT_SHRINK_THRESHOLD,
104     DEFAULT_SHRINK_FACTOR,
105     DEFAULT_GROWTH_THRESHOLD,
106     DEFAULT_GROWTH_FACTOR,
107     false
108   };
109
110 /* Information and lookup.  */
111
112 /* The following few functions provide information about the overall hash
113    table organization: the number of entries, number of buckets and maximum
114    length of buckets.  */
115
116 /* Return the number of buckets in the hash table.  The table size, the total
117    number of buckets (used plus unused), or the maximum number of slots, are
118    the same quantity.  */
119
120 unsigned
121 hash_get_n_buckets (const Hash_table *table)
122 {
123   return table->n_buckets;
124 }
125
126 /* Return the number of slots in use (non-empty buckets).  */
127
128 unsigned
129 hash_get_n_buckets_used (const Hash_table *table)
130 {
131   return table->n_buckets_used;
132 }
133
134 /* Return the number of active entries.  */
135
136 unsigned
137 hash_get_n_entries (const Hash_table *table)
138 {
139   return table->n_entries;
140 }
141
142 /* Return the length of the longest chain (bucket).  */
143
144 unsigned
145 hash_get_max_bucket_length (const Hash_table *table)
146 {
147   struct hash_entry *bucket;
148   unsigned max_bucket_length = 0;
149
150   for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
151     {
152       if (bucket->data)
153         {
154           struct hash_entry *cursor = bucket;
155           unsigned bucket_length = 1;
156
157           while (cursor = cursor->next, cursor)
158             bucket_length++;
159
160           if (bucket_length > max_bucket_length)
161             max_bucket_length = bucket_length;
162         }
163     }
164
165   return max_bucket_length;
166 }
167
168 /* Do a mild validation of a hash table, by traversing it and checking two
169    statistics.  */
170
171 bool
172 hash_table_ok (const Hash_table *table)
173 {
174   struct hash_entry *bucket;
175   unsigned n_buckets_used = 0;
176   unsigned n_entries = 0;
177
178   for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
179     {
180       if (bucket->data)
181         {
182           struct hash_entry *cursor = bucket;
183
184           /* Count bucket head.  */
185           n_buckets_used++;
186           n_entries++;
187
188           /* Count bucket overflow.  */
189           while (cursor = cursor->next, cursor)
190             n_entries++;
191         }
192     }
193
194   if (n_buckets_used == table->n_buckets_used && n_entries == table->n_entries)
195     return true;
196
197   return false;
198 }
199
200 void
201 hash_print_statistics (const Hash_table *table, FILE *stream)
202 {
203   unsigned n_entries = hash_get_n_entries (table);
204   unsigned n_buckets = hash_get_n_buckets (table);
205   unsigned n_buckets_used = hash_get_n_buckets_used (table);
206   unsigned max_bucket_length = hash_get_max_bucket_length (table);
207
208   fprintf (stream, "# entries:         %u\n", n_entries);
209   fprintf (stream, "# buckets:         %u\n", n_buckets);
210   fprintf (stream, "# buckets used:    %u (%.2f%%)\n", n_buckets_used,
211            (100.0 * n_buckets_used) / n_buckets);
212   fprintf (stream, "max bucket length: %u\n", max_bucket_length);
213 }
214
215 /* If ENTRY matches an entry already in the hash table, return the
216    entry from the table.  Otherwise, return NULL.  */
217
218 void *
219 hash_lookup (const Hash_table *table, const void *entry)
220 {
221   struct hash_entry *bucket
222     = table->bucket + table->hasher (entry, table->n_buckets);
223   struct hash_entry *cursor;
224
225   assert (bucket < table->bucket_limit);
226
227   if (bucket->data == NULL)
228     return NULL;
229
230   for (cursor = bucket; cursor; cursor = cursor->next)
231     if (table->comparator (entry, cursor->data))
232       return cursor->data;
233
234   return NULL;
235 }
236
237 /* Walking.  */
238
239 /* The functions in this page traverse the hash table and process the
240    contained entries.  For the traversal to work properly, the hash table
241    should not be resized nor modified while any particular entry is being
242    processed.  In particular, entries should not be added or removed.  */
243
244 /* Return the first data in the table, or NULL if the table is empty.  */
245
246 void *
247 hash_get_first (const Hash_table *table)
248 {
249   struct hash_entry *bucket;
250
251   if (table->n_entries == 0)
252     return NULL;
253
254   for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
255     if (bucket->data)
256       return bucket->data;
257
258   assert (0);
259 }
260
261 /* Return the user data for the entry following ENTRY, where ENTRY has been
262    returned by a previous call to either `hash_get_first' or `hash_get_next'.
263    Return NULL if there is no more entries.  */
264
265 void *
266 hash_get_next (const Hash_table *table, const void *entry)
267 {
268   struct hash_entry *bucket
269     = table->bucket + table->hasher (entry, table->n_buckets);
270   struct hash_entry *cursor;
271
272   assert (bucket < table->bucket_limit);
273
274   /* Find next entry in the same bucket.  */
275   for (cursor = bucket; cursor; cursor = cursor->next)
276     if (cursor->data == entry && cursor->next)
277       return cursor->next->data;
278
279   /* Find first entry in any subsequent bucket.  */
280   for (; bucket < table->bucket_limit; bucket++)
281     if (bucket->data)
282       return bucket->data;
283
284   /* None found.  */
285   return NULL;
286 }
287
288 /* Fill BUFFER with pointers to active user entries in the hash table, then
289    return the number of pointers copied.  Do not copy more than BUFFER_SIZE
290    pointers.  */
291
292 unsigned
293 hash_get_entries (const Hash_table *table, void **buffer,
294                   unsigned buffer_size)
295 {
296   unsigned counter = 0;
297   struct hash_entry *bucket;
298   struct hash_entry *cursor;
299
300   for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
301     {
302       if (bucket->data)
303         {
304           for (cursor = bucket; cursor; cursor = cursor->next)
305             {
306               if (counter >= buffer_size)
307                 return counter;
308               buffer[counter++] = cursor->data;
309             }
310         }
311     }
312
313   return counter;
314 }
315
316 /* Call a PROCESSOR function for each entry of a hash table, and return the
317    number of entries for which the processor function returned success.  A
318    pointer to some PROCESSOR_DATA which will be made available to each call to
319    the processor function.  The PROCESSOR accepts two arguments: the first is
320    the user entry being walked into, the second is the value of PROCESSOR_DATA
321    as received.  The walking continue for as long as the PROCESSOR function
322    returns nonzero.  When it returns zero, the walking is interrupted.  */
323
324 unsigned
325 hash_do_for_each (const Hash_table *table, Hash_processor processor,
326                   void *processor_data)
327 {
328   unsigned counter = 0;
329   struct hash_entry *bucket;
330   struct hash_entry *cursor;
331
332   for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
333     {
334       if (bucket->data)
335         {
336           for (cursor = bucket; cursor; cursor = cursor->next)
337             {
338               if (!(*processor) (cursor->data, processor_data))
339                 return counter;
340               counter++;
341             }
342         }
343     }
344
345   return counter;
346 }
347
348 /* Allocation and clean-up.  */
349
350 /* Return a hash index for a NUL-terminated STRING between 0 and N_BUCKETS-1.
351    This is a convenience routine for constructing other hashing functions.  */
352
353 #if USE_DIFF_HASH
354
355 /* About hashings, Paul Eggert writes to me (FP), on 1994-01-01: "Please see
356    B. J. McKenzie, R. Harries & T. Bell, Selecting a hashing algorithm,
357    Software--practice & experience 20, 2 (Feb 1990), 209-224.  Good hash
358    algorithms tend to be domain-specific, so what's good for [diffutils'] io.c
359    may not be good for your application."  */
360
361 unsigned
362 hash_string (const char *string, unsigned n_buckets)
363 {
364 # ifndef CHAR_BIT
365 #  define CHAR_BIT 8
366 # endif
367 # define ROTATE_LEFT(Value, Shift) \
368   ((Value) << (Shift) | (Value) >> ((sizeof (unsigned) * CHAR_BIT) - (Shift)))
369 # define HASH_ONE_CHAR(Value, Byte) \
370   ((Byte) + ROTATE_LEFT (Value, 7))
371
372   unsigned value = 0;
373
374   for (; *string; string++)
375     value = HASH_ONE_CHAR (value, *(const unsigned char *) string);
376   return value % n_buckets;
377
378 # undef ROTATE_LEFT
379 # undef HASH_ONE_CHAR
380 }
381
382 #else /* not USE_DIFF_HASH */
383
384 /* This one comes from `recode', and performs a bit better than the above as
385    per a few experiments.  It is inspired from a hashing routine found in the
386    very old Cyber `snoop', itself written in typical Greg Mansfield style.
387    (By the way, what happened to this excellent man?  Is he still alive?)  */
388
389 unsigned
390 hash_string (const char *string, unsigned n_buckets)
391 {
392   unsigned value = 0;
393
394   while (*string)
395     value = ((value * 31 + (int) *(const unsigned char *) string++)
396              % n_buckets);
397   return value;
398 }
399
400 #endif /* not USE_DIFF_HASH */
401
402 /* Return true if CANDIDATE is a prime number.  CANDIDATE should be an odd
403    number at least equal to 11.  */
404
405 static int
406 is_prime (unsigned long candidate)
407 {
408   unsigned long divisor = 3;
409   unsigned long square = divisor * divisor;
410
411   while (square < candidate && (candidate % divisor))
412     {
413       divisor++;
414       square += 4 * divisor;
415       divisor++;
416     }
417
418   return candidate % divisor != 0;
419 }
420
421 /* Round a given CANDIDATE number up to the nearest prime, and return that
422    prime.  Primes lower than 10 are merely skipped.  */
423
424 static unsigned long
425 next_prime (unsigned long candidate)
426 {
427   /* Skip small primes.  */
428   if (candidate < 10)
429     candidate = 10;
430
431   /* Make it definitely odd.  */
432   candidate |= 1;
433
434   while (!is_prime (candidate))
435     candidate += 2;
436
437   return candidate;
438 }
439
440 void
441 hash_reset_tuning (Hash_tuning *tuning)
442 {
443   *tuning = default_tuning;
444 }
445
446 /* For the given hash TABLE, check the user supplied tuning structure for
447    reasonable values, and return true if there is no gross error with it.
448    Otherwise, definitvely reset the TUNING field to some acceptable default in
449    the hash table (that is, the user loses the right of further modifying
450    tuning arguments), and return false.  */
451
452 static bool
453 check_tuning (Hash_table *table)
454 {
455   const Hash_tuning *tuning = table->tuning;
456
457   if (tuning->growth_threshold > 0.0
458       && tuning->growth_threshold < 1.0
459       && tuning->growth_factor > 1.0
460       && tuning->shrink_threshold >= 0.0
461       && tuning->shrink_threshold < 1.0
462       && tuning->shrink_factor > tuning->shrink_threshold
463       && tuning->shrink_factor <= 1.0
464       && tuning->shrink_threshold < tuning->growth_threshold)
465     return true;
466
467   table->tuning = &default_tuning;
468   return false;
469 }
470
471 /* Allocate and return a new hash table, or NULL upon failure.  The
472    initial number of buckets is automatically selected so as to _guarantee_ that
473    you may insert at least CANDIDATE different user entries before any growth
474    of the hash table size occurs.  So, if have a reasonably tight a-priori
475    upper bound on the
476    number of entries you intend to insert in the hash table, you may save some
477    table memory and insertion time, by specifying it here.  If the
478    IS_N_BUCKETS field of the TUNING structure is true, the CANDIDATE argument
479    has its meaning changed to the wanted number of buckets.
480
481    TUNING points to a structure of user-supplied values, in case some fine
482    tuning is wanted over the default behavior of the hasher.  If TUNING is
483    NULL, the default tuning parameters are used instead.
484
485    The user-supplied HASHER function should be provided.  It accepts two
486    arguments ENTRY and TABLE_SIZE.  It computes, by hashing ENTRY contents, a
487    slot number for that entry which should be in the range 0..TABLE_SIZE-1.
488    This slot number is then returned.
489
490    The user-supplied COMPARATOR function should be provided.  It accepts two
491    arguments pointing to user data, it then returns true for a pair of entries
492    that compare equal, or false otherwise.  This function is internally called
493    on entries which are already known to hash to the same bucket index.
494
495    The user-supplied DATA_FREER function, when not NULL, may be later called
496    with the user data as an argument, just before the entry containing the
497    data gets freed.  This happens from within `hash_free' or `hash_clear'.
498    You should specify this function only if you want these functions to free
499    all of your `data' data.  This is typically the case when your data is
500    simply an auxiliary struct that you have malloc'd to aggregate several
501    values.  */
502
503 Hash_table *
504 hash_initialize (unsigned candidate, const Hash_tuning *tuning,
505                  Hash_hasher hasher, Hash_comparator comparator,
506                  Hash_data_freer data_freer)
507 {
508   Hash_table *table;
509   struct hash_entry *bucket;
510
511   if (hasher == NULL || comparator == NULL)
512     return NULL;
513
514   table = (Hash_table *) malloc (sizeof (Hash_table));
515   if (table == NULL)
516     return NULL;
517
518   if (!tuning)
519     tuning = &default_tuning;
520   table->tuning = tuning;
521   if (!check_tuning (table))
522     {
523       /* Fail if the tuning options are invalid.  This is the only occasion
524          when the user gets some feedback about it.  Once the table is created,
525          if the user provides invalid tuning options, we silently revert to
526          using the defaults, and ignore further request to change the tuning
527          options.  */
528       free (table);
529       return NULL;
530     }
531
532   table->n_buckets
533     = next_prime (tuning->is_n_buckets ? candidate
534                   : (unsigned) (candidate / tuning->growth_threshold));
535
536   table->bucket = (struct hash_entry *)
537     malloc (table->n_buckets * sizeof (struct hash_entry));
538   if (table->bucket == NULL)
539     {
540       free (table);
541       return NULL;
542     }
543   table->bucket_limit = table->bucket + table->n_buckets;
544
545   for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
546     {
547       bucket->data = NULL;
548       bucket->next = NULL;
549     }
550   table->n_buckets_used = 0;
551   table->n_entries = 0;
552
553   table->hasher = hasher;
554   table->comparator = comparator;
555   table->data_freer = data_freer;
556
557   table->free_entry_list = NULL;
558 #if USE_OBSTACK
559   obstack_init (&table->entry_stack);
560 #endif
561   return table;
562 }
563
564 /* Make all buckets empty, placing any chained entries on the free list.
565    Apply the user-specified function data_freer (if any) to the datas of any
566    affected entries.  */
567
568 void
569 hash_clear (Hash_table *table)
570 {
571   struct hash_entry *bucket;
572   struct hash_entry *cursor;
573
574   for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
575     {
576       if (bucket->data)
577         {
578           /* Free the bucket overflow.  */
579           for (cursor = bucket->next; cursor; cursor = cursor->next)
580             {
581               if (table->data_freer)
582                 (*table->data_freer) (cursor->data);
583               cursor->data = NULL;
584
585               /* Relinking is done one entry at a time, as it is to be expected
586                  that overflows are either rare or short.  */
587               cursor->next = table->free_entry_list;
588               table->free_entry_list = cursor;
589             }
590
591           /* Free the bucket head.  */
592           if (table->data_freer)
593             (*table->data_freer) (bucket->data);
594           bucket->data = NULL;
595           bucket->next = NULL;
596         }
597     }
598
599   table->n_buckets_used = 0;
600   table->n_entries = 0;
601 }
602
603 /* Reclaim all storage associated with a hash table.  If a data_freer
604    function has been supplied by the user when the hash table was created,
605    this function applies it to the data of each entry before freeing that
606    entry.  */
607
608 void
609 hash_free (Hash_table *table)
610 {
611   struct hash_entry *bucket;
612   struct hash_entry *cursor;
613   struct hash_entry *next;
614
615   /* Call the user data_freer function.  */
616   if (table->data_freer && table->n_entries)
617     {
618       for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
619         {
620           if (bucket->data)
621             {
622               for (cursor = bucket; cursor; cursor = cursor->next)
623                 {
624                   (*table->data_freer) (cursor->data);
625                 }
626             }
627         }
628     }
629
630 #if USE_OBSTACK
631
632   obstack_free (&table->entry_stack, NULL);
633
634 #else
635
636   /* Free all bucket overflowed entries.  */
637   for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
638     {
639       for (cursor = bucket->next; cursor; cursor = next)
640         {
641           next = cursor->next;
642           free (cursor);
643         }
644     }
645
646   /* Also reclaim the internal list of previously freed entries.  */
647   for (cursor = table->free_entry_list; cursor; cursor = next)
648     {
649       next = cursor->next;
650       free (cursor);
651     }
652
653 #endif
654
655   /* Free the remainder of the hash table structure.  */
656   free (table->bucket);
657   free (table);
658 }
659
660 /* Insertion and deletion.  */
661
662 /* Get a new hash entry for a bucket overflow, possibly by reclying a
663    previously freed one.  If this is not possible, allocate a new one.  */
664
665 static struct hash_entry *
666 allocate_entry (Hash_table *table)
667 {
668   struct hash_entry *new;
669
670   if (table->free_entry_list)
671     {
672       new = table->free_entry_list;
673       table->free_entry_list = new->next;
674     }
675   else
676     {
677 #if USE_OBSTACK
678       new = (struct hash_entry *)
679         obstack_alloc (&table->entry_stack, sizeof (struct hash_entry));
680 #else
681       new = (struct hash_entry *) malloc (sizeof (struct hash_entry));
682 #endif
683     }
684
685   return new;
686 }
687
688 /* Free a hash entry which was part of some bucket overflow,
689    saving it for later recycling.  */
690
691 static void
692 free_entry (Hash_table *table, struct hash_entry *entry)
693 {
694   entry->data = NULL;
695   entry->next = table->free_entry_list;
696   table->free_entry_list = entry;
697 }
698
699 /* This private function is used to help with insertion and deletion.  When
700    ENTRY matches an entry in the table, return a pointer to the corresponding
701    user data and set *BUCKET_HEAD to the head of the selected bucket.
702    Otherwise, return NULL.  When DELETE is true and ENTRY matches an entry in
703    the table, unlink the matching entry.  */
704
705 static void *
706 hash_find_entry (Hash_table *table, const void *entry,
707                  struct hash_entry **bucket_head, bool delete)
708 {
709   struct hash_entry *bucket
710     = table->bucket + table->hasher (entry, table->n_buckets);
711   struct hash_entry *cursor;
712
713   assert (bucket < table->bucket_limit);
714   *bucket_head = bucket;
715
716   /* Test for empty bucket.  */
717   if (bucket->data == NULL)
718     return NULL;
719
720   /* Check if then entry is found as the bucket head.  */
721   if ((*table->comparator) (entry, bucket->data))
722     {
723       void *data = bucket->data;
724
725       if (delete)
726         {
727           if (bucket->next)
728             {
729               struct hash_entry *next = bucket->next;
730
731               /* Bump the first overflow entry into the bucket head, then save
732                  the previous first overflow entry for later recycling.  */
733               *bucket = *next;
734               free_entry (table, next);
735             }
736           else
737             {
738               bucket->data = NULL;
739             }
740         }
741
742       return data;
743     }
744
745   /* Scan the bucket overflow.  */
746   for (cursor = bucket; cursor->next; cursor = cursor->next)
747     {
748       if ((*table->comparator) (entry, cursor->next->data))
749         {
750           void *data = cursor->next->data;
751
752           if (delete)
753             {
754               struct hash_entry *next = cursor->next;
755
756               /* Unlink the entry to delete, then save the freed entry for later
757                  recycling.  */
758               cursor->next = next->next;
759               free_entry (table, next);
760             }
761
762           return data;
763         }
764     }
765
766   /* No entry found.  */
767   return NULL;
768 }
769
770 /* For an already existing hash table, change the number of buckets through
771    specifying CANDIDATE.  The contents of the hash table are preserved.  The
772    new number of buckets is automatically selected so as to _guarantee_ that the
773    table may receive at least CANDIDATE different user entries, including
774    those already in the table, before any other growth of the hash table size
775    occurs.  If TUNING->IS_N_BUCKETS is true, then CANDIDATE specifies the
776    exact number of buckets desired.  */
777
778 bool
779 hash_rehash (Hash_table *table, unsigned candidate)
780 {
781   Hash_table *new_table;
782   struct hash_entry *bucket;
783   struct hash_entry *cursor;
784   struct hash_entry *next;
785
786   new_table = hash_initialize (candidate, table->tuning, table->hasher,
787                                table->comparator, table->data_freer);
788   if (new_table == NULL)
789     return false;
790
791   /* Merely reuse the extra old space into the new table.  */
792 #if USE_OBSTACK
793   obstack_free (&new_table->entry_stack, NULL);
794   new_table->entry_stack = table->entry_stack;
795 #endif
796   new_table->free_entry_list = table->free_entry_list;
797
798   for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
799     if (bucket->data)
800       for (cursor = bucket; cursor; cursor = next)
801         {
802           void *data = cursor->data;
803           struct hash_entry *new_bucket
804             = (new_table->bucket
805                + new_table->hasher (data, new_table->n_buckets));
806
807           assert (new_bucket < new_table->bucket_limit);
808           next = cursor->next;
809
810           if (new_bucket->data)
811             {
812               if (cursor == bucket)
813                 {
814                   /* Allocate or recycle an entry, when moving from a bucket
815                      header into a bucket overflow.  */
816                   struct hash_entry *new_entry = allocate_entry (new_table);
817
818                   if (new_entry == NULL)
819                     return false;
820
821                   new_entry->data = data;
822                   new_entry->next = new_bucket->next;
823                   new_bucket->next = new_entry;
824                 }
825               else
826                 {
827                   /* Merely relink an existing entry, when moving from a
828                      bucket overflow into a bucket overflow.  */
829                   cursor->next = new_bucket->next;
830                   new_bucket->next = cursor;
831                 }
832             }
833           else
834             {
835               /* Free an existing entry, when moving from a bucket
836                  overflow into a bucket header.  Also take care of the
837                  simple case of moving from a bucket header into a bucket
838                  header.  */
839               new_bucket->data = data;
840               new_table->n_buckets_used++;
841               if (cursor != bucket)
842                 free_entry (new_table, cursor);
843             }
844         }
845
846   free (table->bucket);
847   table->bucket = new_table->bucket;
848   table->bucket_limit = new_table->bucket_limit;
849   table->n_buckets = new_table->n_buckets;
850   table->n_buckets_used = new_table->n_buckets_used;
851   /* table->n_entries already holds its value.  */
852 #if USE_OBSTACK
853   table->entry_stack = new_table->entry_stack;
854 #endif
855   free (new_table);
856
857   return true;
858 }
859
860 /* If ENTRY matches an entry already in the hash table, return the pointer
861    to the entry from the table.  Otherwise, insert ENTRY and return ENTRY.
862    Return NULL if the storage required for insertion cannot be allocated.  */
863
864 void *
865 hash_insert (Hash_table *table, const void *entry)
866 {
867   void *data;
868   struct hash_entry *bucket;
869
870   assert (entry);               /* cannot insert a NULL entry */
871
872   /* If there's a matching entry already in the table, return that.  */
873   if ((data = hash_find_entry (table, entry, &bucket, false)) != NULL)
874     return data;
875
876   /* ENTRY is not matched, it should be inserted.  */
877
878   if (bucket->data)
879     {
880       struct hash_entry *new_entry = allocate_entry (table);
881
882       if (new_entry == NULL)
883         return NULL;
884
885       /* Add ENTRY in the overflow of the bucket.  */
886
887       new_entry->data = (void *) entry;
888       new_entry->next = bucket->next;
889       bucket->next = new_entry;
890       table->n_entries++;
891       return (void *) entry;
892     }
893
894   /* Add ENTRY right in the bucket head.  */
895
896   bucket->data = (void *) entry;
897   table->n_entries++;
898   table->n_buckets_used++;
899
900   /* If the growth threshold of the buckets in use has been reached, increase
901      the table size and rehash.  There's no point in checking the number of
902      entries:  if the hashing function is ill-conditioned, rehashing is not
903      likely to improve it.  */
904
905   if (table->n_buckets_used
906       > table->tuning->growth_threshold * table->n_buckets)
907     {
908       /* Check more fully, before starting real work.  If tuning arguments
909          became invalid, the second check will rely on proper defaults.  */
910       check_tuning (table);
911       if (table->n_buckets_used
912           > table->tuning->growth_threshold * table->n_buckets)
913         {
914           const Hash_tuning *tuning = table->tuning;
915           unsigned candidate
916             = (unsigned) (tuning->is_n_buckets
917                           ? (table->n_buckets * tuning->growth_factor)
918                           : (table->n_buckets * tuning->growth_factor
919                              * tuning->growth_threshold));
920
921           /* If the rehash fails, arrange to return NULL.  */
922           if (!hash_rehash (table, candidate))
923             entry = NULL;
924         }
925     }
926
927   return (void *) entry;
928 }
929
930 /* If ENTRY is already in the table, remove it and return the just-deleted
931    data (the user may want to deallocate its storage).  If ENTRY is not in the
932    table, don't modify the table and return NULL.  */
933
934 void *
935 hash_delete (Hash_table *table, const void *entry)
936 {
937   void *data;
938   struct hash_entry *bucket;
939
940   if (data = hash_find_entry (table, entry, &bucket, true), !data)
941     return NULL;
942
943   table->n_entries--;
944   if (!bucket->data)
945     {
946       table->n_buckets_used--;
947
948       /* If the shrink threshold of the buckets in use has been reached,
949          rehash into a smaller table.  */
950
951       if (table->n_buckets_used
952           < table->tuning->shrink_threshold * table->n_buckets)
953         {
954           /* Check more fully, before starting real work.  If tuning arguments
955              became invalid, the second check will rely on proper defaults.  */
956           check_tuning (table);
957           if (table->n_buckets_used
958               < table->tuning->shrink_threshold * table->n_buckets)
959             {
960               const Hash_tuning *tuning = table->tuning;
961               unsigned candidate
962                 = (unsigned) (tuning->is_n_buckets
963                               ? table->n_buckets * tuning->shrink_factor
964                               : (table->n_buckets * tuning->shrink_factor
965                                  * tuning->growth_threshold));
966
967               hash_rehash (table, candidate);
968             }
969         }
970     }
971
972   return data;
973 }
974
975 /* Testing.  */
976
977 #if TESTING
978
979 void
980 hash_print (const Hash_table *table)
981 {
982   struct hash_entry *bucket;
983
984   for (bucket = table->bucket; bucket < table->bucket_limit; bucket++)
985     {
986       struct hash_entry *cursor;
987
988       if (bucket)
989         printf ("%d:\n", slot);
990
991       for (cursor = bucket; cursor; cursor = cursor->next)
992         {
993           char *s = (char *) cursor->data;
994           /* FIXME */
995           printf ("  %s\n", s);
996         }
997     }
998 }
999
1000 #endif /* TESTING */