]> sjero.net Git - wget/blob - src/hash.c
[svn] Commit hash table bugfix.
[wget] / src / hash.c
1 /* Hash tables.
2    Copyright (C) 2000 Free Software Foundation, Inc.
3
4 This file is part of Wget.
5
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or (at
9 your option) any later version.
10
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
19
20 #ifdef HAVE_CONFIG_H
21 # include <config.h>
22 #endif
23
24 #include <stdlib.h>
25 #include <assert.h>
26
27 #include "wget.h"
28 #include "utils.h"
29
30 #include "hash.h"
31
32 #ifdef STANDALONE
33 # define xmalloc malloc
34 # define xrealloc realloc
35 #endif
36
37 /* INTERFACE:
38
39    Hash tables are an implementation technique used to implement
40    mapping between objects.  Provided a good hashing function is used,
41    they guarantee constant-time access and storing of information.
42    Duplicate keys are not allowed.
43
44    The basics are all covered.  hash_table_new creates a hash table,
45    and hash_table_destroy deletes it.  hash_table_put establishes a
46    mapping between a key and a value.  hash_table_get retrieves the
47    value that corresponds to a key.  hash_table_exists queries whether
48    a key is stored in a table at all.  hash_table_remove removes a
49    mapping that corresponds to a key.  hash_table_map allows you to
50    map through all the entries in a hash table.  hash_table_clear
51    clears all the entries from the hash table.
52
53    The number of mappings in a table is not limited, except by the
54    amount of memory.  As you add new elements to a table, it regrows
55    as necessary.  If you have an idea about how many elements you will
56    store, you can provide a hint to hash_table_new().
57
58    The hashing and equality functions are normally provided by the
59    user.  For the special (and frequent) case of hashing strings, you
60    can use the pre-canned make_string_hash_table(), which provides the
61    string hashing function from the Dragon Book, and a string equality
62    wrapper around strcmp().
63
64    When specifying your own hash and test functions, make sure the
65    following holds true:
66
67    - The test function returns non-zero for keys that are considered
68      "equal", zero otherwise.
69
70    - The hash function returns a number that represents the
71      "distinctness" of the object.  In more precise terms, it means
72      that for any two objects that test "equal" under the test
73      function, the hash function MUST produce the same result.
74
75      This does not mean that each distinct object must produce a
76      distinct value, only that non-distinct objects must produce the
77      same values!  For instance, a hash function that returns 0 for
78      any given object is a perfectly valid (albeit extremely bad) hash
79      function.
80
81      The above stated rule is quite easy to enforce.  For example, if
82      your testing function compares strings case-insensitively, all
83      your function needs to do is lower-case the string characters
84      before calculating a hash.  That way you have easily guaranteed
85      that changes in case will not result in a different hash.
86
87    - (optional) Choose the hash function to get as good "spreading" as
88      possible.  A good hash function will react to even a small change
89      in its input with a completely different resulting hash.
90      Finally, don't make your hash function extremely slow, because
91      you're then defeating the purpose of hashing.
92
93    Note that neither keys nor values are copied when inserted into the
94    hash table, so they must exist for the lifetime of the table.  This
95    means that e.g. the use of static strings is OK, but objects with a
96    shorter life-time need to be copied (with strdup() or the like in
97    the case of strings) before being inserted.  */
98
99 /* IMPLEMENTATION:
100
101    All the hash mappings (key-value pairs of pointers) are stored in a
102    contiguous array.  The position of each mapping is determined by
103    applying the hash function to the key: location = hash(key) % size.
104    If two different keys end up on the same position, the collision is
105    resolved by placing the second mapping at the next empty place in
106    the array following the occupied place.  This method of collision
107    resolution is called "linear probing".
108
109    There are more advanced collision resolution mechanisms (quadratic
110    probing, double hashing), but we don't use them because they
111    involve more non-sequential access to the array, and therefore
112    worse cache behavior.  Linear probing works well as long as the
113    fullness/size ratio is kept below 75%.  We make sure to regrow or
114    rehash the hash table whenever this threshold is exceeded.
115
116    Collisions make deletion tricky because finding collisions again
117    relies on new empty spots not being created.  That's why
118    hash_table_remove only marks the spot as deleted rather than really
119    making it empty. */
120
121 struct mapping {
122   void *key;
123   void *value;
124 };
125
126 struct hash_table {
127   unsigned long (*hash_function) (const void *);
128   int (*test_function) (const void *, const void *);
129
130   int size;                     /* size of the array */
131   int fullness;                 /* number of non-empty fields */
132   int count;                    /* number of non-empty, non-deleted
133                                    fields. */
134
135   struct mapping *mappings;
136 };
137
138 #define ENTRY_DELETED ((void *)0xdeadbeef)
139 #define ENTRY_EMPTY   NULL
140
141 #define DELETED_ENTRY_P(ptr) ((ptr) == ENTRY_DELETED)
142 #define EMPTY_ENTRY_P(ptr)   ((ptr) == ENTRY_EMPTY)
143
144 /* Find a prime near, but greather than or equal to SIZE. */
145
146 int
147 prime_size (int size)
148 {
149   static const unsigned long primes [] = {
150     19, 29, 41, 59, 79, 107, 149, 197, 263, 347, 457, 599, 787, 1031,
151     1361, 1777, 2333, 3037, 3967, 5167, 6719, 8737, 11369, 14783,
152     19219, 24989, 32491, 42257, 54941, 71429, 92861, 120721, 156941,
153     204047, 265271, 344857, 448321, 582821, 757693, 985003, 1280519,
154     1664681, 2164111, 2813353, 3657361, 4754591, 6180989, 8035301,
155     10445899, 13579681, 17653589, 22949669, 29834603, 38784989,
156     50420551, 65546729, 85210757, 110774011, 144006217, 187208107,
157     243370577, 316381771, 411296309, 534685237, 695090819, 903618083,
158     1174703521, 1527114613, 1985248999, 2580823717UL, 3355070839UL
159   };
160   int i;
161   for (i = 0; i < ARRAY_SIZE (primes); i++)
162     if (primes[i] >= size)
163       return primes[i];
164   /* huh? */
165   return size;
166 }
167
168 /* Create a hash table of INITIAL_SIZE with hash function
169    HASH_FUNCTION and test function TEST_FUNCTION.  If you wish to
170    start out with a "small" table which will be regrown as needed,
171    specify 0 as INITIAL_SIZE.  */
172
173 struct hash_table *
174 hash_table_new (int initial_size,
175                 unsigned long (*hash_function) (const void *),
176                 int (*test_function) (const void *, const void *))
177 {
178   struct hash_table *ht
179     = (struct hash_table *)xmalloc (sizeof (struct hash_table));
180   ht->hash_function = hash_function;
181   ht->test_function = test_function;
182   ht->size = prime_size (initial_size);
183   ht->fullness = 0;
184   ht->count    = 0;
185   ht->mappings = xmalloc (ht->size * sizeof (struct mapping));
186   memset (ht->mappings, '\0', ht->size * sizeof (struct mapping));
187   return ht;
188 }
189
190 /* Free the data associated with hash table HT. */
191
192 void
193 hash_table_destroy (struct hash_table *ht)
194 {
195   free (ht->mappings);
196   free (ht);
197 }
198
199 /* The heart of almost all functions in this file -- find the mapping
200    whose KEY is equal to key, using a linear probing loop.  Returns
201    the offset of the mapping in ht->mappings.  This should probably be
202    declared inline.  */
203
204 static int
205 find_mapping (struct hash_table *ht, const void *key)
206 {
207   struct mapping *mappings = ht->mappings;
208   int size = ht->size;
209   int location = ht->hash_function (key) % size;
210   while (1)
211     {
212       struct mapping *mp = mappings + location;
213       void *mp_key = mp->key;
214
215       if (EMPTY_ENTRY_P (mp_key))
216         return -1;
217       else if (DELETED_ENTRY_P (mp_key)
218                || !ht->test_function (key, mp_key))
219         {
220           if (++location == size)
221             location = 0;
222         }
223       else
224         return location;
225     }
226 }
227
228 /* Get the value that corresponds to the key KEY in the hash table HT.
229    If no value is found, return NULL.  Note that NULL is a legal value
230    for value; if you are storing NULLs in your hash table, you can use
231    hash_table_exists to be sure that a (possibly NULL) value exists in
232    the table.  Or, you can use hash_table_get_pair instead of this
233    function.  */
234
235 void *
236 hash_table_get (struct hash_table *ht, const void *key)
237 {
238   int location = find_mapping (ht, key);
239   if (location < 0)
240     return NULL;
241   else
242     return ht->mappings[location].value;
243 }
244
245 /* Like hash_table_get, but writes out the pointers to both key and
246    value.  Returns non-zero on success.  */
247
248 int
249 hash_table_get_pair (struct hash_table *ht, const void *lookup_key,
250                      void *orig_key, void *value)
251 {
252   int location = find_mapping (ht, lookup_key);
253   if (location < 0)
254     return 0;
255   else
256     {
257       struct mapping *mp = ht->mappings + location;
258       if (orig_key)
259         *(void **)orig_key = mp->key;
260       if (value)
261         *(void **)value = mp->value;
262       return 1;
263     }
264 }
265
266 /* Return 1 if KEY exists in HT, 0 otherwise. */
267
268 int
269 hash_table_exists (struct hash_table *ht, const void *key)
270 {
271   return find_mapping (ht, key) >= 0;
272 }
273
274 #define MAX(i, j) (((i) >= (j)) ? (i) : (j))
275
276 /* Grow hash table HT as necessary, and rehash all the key-value
277    mappings.  */
278
279 static void
280 grow_hash_table (struct hash_table *ht)
281 {
282   int i;
283   struct mapping *old_mappings = ht->mappings;
284   int old_count = ht->count;    /* for assert() below */
285   int old_size = ht->size;
286
287   /* To minimize the number of regrowth, we'd like to resize the hash
288      table exponentially.  Normally, this would be done by doubling
289      ht->size (and round it to next prime) on each regrow:
290
291          ht->size = prime_size (ht->size * 2);
292
293      But it is possible that the table has large fullness because of
294      the many deleted entries.  If that is the case, we don't want to
295      blindly grow the table; we just want to rehash it.  For that
296      reason, we use ht->count as the relevant parameter.  MAX is used
297      only because we don't want to actually shrink the table.  (But
298      maybe that's wrong.)  */
299
300   int needed_size = prime_size (ht->count * 3);
301   ht->size = MAX (old_size, needed_size);
302
303 #if 0
304   printf ("growing from %d to %d\n", old_size, ht->size);
305 #endif
306
307   ht->mappings = xmalloc (ht->size * sizeof (struct mapping));
308   memset (ht->mappings, '\0', ht->size * sizeof (struct mapping));
309
310   /* Need to reset these two; hash_table_put will reinitialize them.  */
311   ht->fullness = 0;
312   ht->count    = 0;
313   for (i = 0; i < old_size; i++)
314     {
315       struct mapping *mp = old_mappings + i;
316       void *mp_key = mp->key;
317
318       if (!EMPTY_ENTRY_P (mp_key)
319           && !DELETED_ENTRY_P (mp_key))
320         hash_table_put (ht, mp_key, mp->value);
321     }
322   assert (ht->count == old_count);
323   free (old_mappings);
324 }
325
326 /* Put VALUE in the hash table HT under the key KEY.  This regrows the
327    table if necessary.  */
328
329 void
330 hash_table_put (struct hash_table *ht, const void *key, void *value)
331 {
332   /* Cannot use find_mapping here because we're actually looking for
333      an *empty* entry.  */
334
335   struct mapping *mappings = ht->mappings;
336   int size = ht->size;
337   int location = ht->hash_function (key) % size;
338   while (1)
339     {
340       struct mapping *mp = mappings + location;
341       void *mp_key = mp->key;
342
343       if (EMPTY_ENTRY_P (mp_key))
344         {
345           ++ht->fullness;
346           ++ht->count;
347         just_insert:
348           mp->key = (void *)key; /* const? */
349           mp->value = value;
350           break;
351         }
352       else if (DELETED_ENTRY_P (mp_key)
353                || !ht->test_function (key, mp_key))
354         {
355           if (++location == size)
356             location = 0;
357         }
358       else                      /* equal to key and not deleted */
359         {
360           /* We're replacing an existing entry, so ht->count and
361              ht->fullness remain unchanged.  */
362           goto just_insert;
363         }
364     }
365   if (ht->fullness * 4 > ht->size * 3)
366     /* When fullness exceeds 75% of size, regrow the table. */
367     grow_hash_table (ht);
368 }
369
370 /* Remove KEY from HT. */
371
372 int
373 hash_table_remove (struct hash_table *ht, const void *key)
374 {
375   int location = find_mapping (ht, key);
376   if (location < 0)
377     return 0;
378   else
379     {
380       struct mapping *mappings = ht->mappings;
381       struct mapping *mp = mappings + location;
382       /* We don't really remove an entry from the hash table: we just
383          mark it as deleted.  This is because there may be other
384          entries located after this entry whose hash points to a
385          location before this entry.  (Example: keys A, B and C have
386          the same hash.  If you were to really *delete* B from the
387          table, C could no longer be found.) */
388
389       /* Optimization addendum: if the mapping that follows LOCATION
390          is already empty, that is a sure sign that nobody depends on
391          LOCATION being non-empty.  (This is because we're using
392          linear probing.  This would not be the case with double
393          hashing.)  In that case, we may safely delete the mapping.  */
394
395       /* This could be generalized so that the all the non-empty
396          locations following LOCATION are simply shifted leftward.  It
397          would make deletion a bit slower, but it would remove the
398          ugly DELETED_ENTRY_P checks from all the rest of the code,
399          making the whole thing faster.  */
400       int location_after = (location + 1) == ht->size ? 0 : location + 1;
401       struct mapping *mp_after = mappings + location_after;
402
403       if (EMPTY_ENTRY_P (mp_after->key))
404         {
405           mp->key = ENTRY_EMPTY;
406           --ht->fullness;
407         }
408       else
409         mp->key = ENTRY_DELETED;
410
411       --ht->count;
412       return 1;
413     }
414 }
415
416 /* Clear HT of all entries.  After calling this function, the count
417    and the fullness of the hash table will be zero.  The size will
418    remain unchanged.  */
419
420 void
421 hash_table_clear (struct hash_table *ht)
422 {
423   memset (ht->mappings, '\0', ht->size * sizeof (struct mapping));
424   ht->fullness = 0;
425   ht->count    = 0;
426 }
427
428 /* Map MAPFUN over all the mappings in hash table HT.  MAPFUN is
429    called with three arguments: the key, the value, and the CLOSURE.
430    Don't add or remove entries from HT while hash_table_map is being
431    called, or strange things may happen.  */
432
433 void
434 hash_table_map (struct hash_table *ht,
435                 int (*mapfun) (void *, void *, void *),
436                 void *closure)
437 {
438   struct mapping *mappings = ht->mappings;
439   int i;
440   for (i = 0; i < ht->size; i++)
441     {
442       struct mapping *mp = mappings + i;
443       void *mp_key = mp->key;
444
445       if (!EMPTY_ENTRY_P (mp_key)
446           && !DELETED_ENTRY_P (mp_key))
447         if (mapfun (mp_key, mp->value, closure))
448           return;
449     }
450 }
451 \f
452 /* Support for hash tables whose keys are strings.  */
453
454 /* supposedly from the Dragon Book P436. */
455 unsigned long
456 string_hash (const void *sv)
457 {
458   unsigned int h = 0;
459   unsigned const char *x = (unsigned const char *) sv;
460
461   while (*x)
462     {
463       unsigned int g;
464       h = (h << 4) + *x++;
465       if ((g = h & 0xf0000000) != 0)
466         h = (h ^ (g >> 24)) ^ g;
467     }
468
469   return h;
470 }
471
472 #if 0
473 /* If I ever need it: hashing of integers. */
474
475 unsigned int
476 inthash (unsigned int key)
477 {
478   key += (key << 12);
479   key ^= (key >> 22);
480   key += (key << 4);
481   key ^= (key >> 9);
482   key += (key << 10);
483   key ^= (key >> 2);
484   key += (key << 7);
485   key ^= (key >> 12);
486   return key;
487 }
488 #endif
489
490 int
491 string_cmp (const void *s1, const void *s2)
492 {
493   return !strcmp ((const char *)s1, (const char *)s2);
494 }
495
496 /* Return a hash table of initial size INITIAL_SIZE suitable to use
497    strings as keys.  */
498
499 struct hash_table *
500 make_string_hash_table (int initial_size)
501 {
502   return hash_table_new (initial_size, string_hash, string_cmp);
503 }
504
505 \f
506 #ifdef STANDALONE
507
508 #include <stdio.h>
509 #include <string.h>
510
511 int
512 print_hash_table_mapper (void *key, void *value, void *count)
513 {
514   ++*(int *)count;
515   printf ("%s: %s\n", (const char *)key, (char *)value);
516   return 0;
517 }
518
519 void
520 print_hash (struct hash_table *sht)
521 {
522   int debug_count = 0;
523   hash_table_map (sht, print_hash_table_mapper, &debug_count);
524   assert (debug_count == sht->count);
525 }
526
527 int
528 main (void)
529 {
530   struct hash_table *ht = make_string_hash_table (0);
531   char line[80];
532   while ((fgets (line, sizeof (line), stdin)))
533     {
534       int len = strlen (line);
535       if (len <= 1)
536         continue;
537       line[--len] = '\0';
538       if (!hash_table_exists (ht, line))
539         hash_table_put (ht, strdup (line), "here I am!");
540 #if 1
541       if (len % 3)
542         {
543           char *line_copy;
544           if (hash_table_get_pair (ht, line, &line_copy, NULL))
545             {
546               hash_table_remove (ht, line);
547               free (line_copy);
548             }
549         }
550 #endif
551     }
552 #if 0
553   print_hash (ht);
554 #endif
555 #if 1
556   printf ("%d %d %d\n", ht->count, ht->fullness, ht->size);
557 #endif
558   return 0;
559 }
560 #endif