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