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