]> sjero.net Git - wget/blob - src/hash.c
[svn] Committed a bunch of different tweaks of mine.
[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   printf ("growing from %d to %d\n", old_size, ht->size);
304
305   ht->mappings = xmalloc (ht->size * sizeof (struct mapping));
306   memset (ht->mappings, '\0', ht->size * sizeof (struct mapping));
307
308   /* Need to reset these two; hash_table_put will reinitialize them.  */
309   ht->fullness = 0;
310   ht->count    = 0;
311   for (i = 0; i < old_size; i++)
312     {
313       struct mapping *mp = old_mappings + i;
314       void *mp_key = mp->key;
315
316       if (!EMPTY_ENTRY_P (mp_key)
317           && !DELETED_ENTRY_P (mp_key))
318         hash_table_put (ht, mp_key, mp->value);
319     }
320   assert (ht->count == old_count);
321   free (old_mappings);
322 }
323
324 /* Put VALUE in the hash table HT under the key KEY.  This regrows the
325    table if necessary.  */
326
327 void
328 hash_table_put (struct hash_table *ht, const void *key, void *value)
329 {
330   /* Cannot use find_mapping here because we treat deleted entries
331      specially.  */
332
333   struct mapping *mappings = ht->mappings;
334   int size = ht->size;
335   int location = ht->hash_function (key) % size;
336   while (1)
337     {
338       struct mapping *mp = mappings + location;
339       void *mp_key = mp->key;
340
341       if (EMPTY_ENTRY_P (mp_key))
342         {
343           ++ht->fullness;
344           ++ht->count;
345         just_insert:
346           mp->key = (void *)key; /* const? */
347           mp->value = value;
348           break;
349         }
350       else if (DELETED_ENTRY_P (mp_key))
351         {
352           /* We're replacing a deleteed entry, so ht->count gets
353              increased, but ht->fullness remains unchanged.  */
354           ++ht->count;
355           goto just_insert;
356         }
357       else if (ht->test_function (key, mp_key))
358         {
359           /* We're replacing an existing entry, so ht->count and
360              ht->fullness remain unchanged.  */
361           goto just_insert;
362         }
363       else
364         {
365           if (++location == size)
366             location = 0;
367         }
368     }
369   if (ht->fullness * 4 > ht->size * 3)
370     /* When fullness exceeds 75% of size, regrow the table. */
371     grow_hash_table (ht);
372 }
373
374 /* Remove KEY from HT. */
375
376 int
377 hash_table_remove (struct hash_table *ht, const void *key)
378 {
379   int location = find_mapping (ht, key);
380   if (location < 0)
381     return 0;
382   else
383     {
384       struct mapping *mappings = ht->mappings;
385       struct mapping *mp = mappings + location;
386       /* We don't really remove an entry from the hash table: we just
387          mark it as deleted.  This is because there may be other
388          entries located after this entry whose hash points to a
389          location before this entry.  (Example: keys A, B and C have
390          the same hash.  If you were to really *delete* B from the
391          table, C could no longer be found.) */
392
393       /* Optimization addendum: if the mapping that follows LOCATION
394          is already empty, that is a sure sign that nobody depends on
395          LOCATION being non-empty.  (This is because we're using
396          linear probing.  This would not be the case with double
397          hashing.)  In that case, we may safely delete the mapping.  */
398
399       /* This could be generalized so that the all the non-empty
400          locations following LOCATION are simply shifted leftward.  It
401          would make deletion a bit slower, but it would remove the
402          ugly DELETED_ENTRY_P checks from all the rest of the code,
403          making the whole thing faster.  */
404       int location_after = (location + 1) == ht->size ? 0 : location + 1;
405       struct mapping *mp_after = mappings + location_after;
406
407       if (EMPTY_ENTRY_P (mp_after->key))
408         {
409           mp->key = ENTRY_EMPTY;
410           --ht->fullness;
411         }
412       else
413         mp->key = ENTRY_DELETED;
414
415       --ht->count;
416       return 1;
417     }
418 }
419
420 /* Clear HT of all entries.  After calling this function, the count
421    and the fullness of the hash table will be zero.  The size will
422    remain unchanged.  */
423
424 void
425 hash_table_clear (struct hash_table *ht)
426 {
427   memset (ht->mappings, '\0', ht->size * sizeof (struct mapping));
428   ht->fullness = 0;
429   ht->count    = 0;
430 }
431
432 /* Map MAPFUN over all the mappings in hash table HT.  MAPFUN is
433    called with three arguments: the key, the value, and the CLOSURE.
434    Don't add or remove entries from HT while hash_table_map is being
435    called, or strange things may happen.  */
436
437 void
438 hash_table_map (struct hash_table *ht,
439                 int (*mapfun) (void *, void *, void *),
440                 void *closure)
441 {
442   struct mapping *mappings = ht->mappings;
443   int i;
444   for (i = 0; i < ht->size; i++)
445     {
446       struct mapping *mp = mappings + i;
447       void *mp_key = mp->key;
448
449       if (!EMPTY_ENTRY_P (mp_key)
450           && !DELETED_ENTRY_P (mp_key))
451         if (mapfun (mp_key, mp->value, closure))
452           return;
453     }
454 }
455 \f
456 /* Support for hash tables whose keys are strings.  */
457
458 /* supposedly from the Dragon Book P436. */
459 unsigned long
460 string_hash (const void *sv)
461 {
462   unsigned int h = 0;
463   unsigned const char *x = (unsigned const char *) sv;
464
465   while (*x)
466     {
467       unsigned int g;
468       h = (h << 4) + *x++;
469       if ((g = h & 0xf0000000) != 0)
470         h = (h ^ (g >> 24)) ^ g;
471     }
472
473   return h;
474 }
475
476 #if 0
477 /* If I ever need it: hashing of integers. */
478
479 unsigned int
480 inthash (unsigned int key)
481 {
482   key += (key << 12);
483   key ^= (key >> 22);
484   key += (key << 4);
485   key ^= (key >> 9);
486   key += (key << 10);
487   key ^= (key >> 2);
488   key += (key << 7);
489   key ^= (key >> 12);
490   return key;
491 }
492 #endif
493
494 int
495 string_cmp (const void *s1, const void *s2)
496 {
497   return !strcmp ((const char *)s1, (const char *)s2);
498 }
499
500 /* Return a hash table of initial size INITIAL_SIZE suitable to use
501    strings as keys.  */
502
503 struct hash_table *
504 make_string_hash_table (int initial_size)
505 {
506   return hash_table_new (initial_size, string_hash, string_cmp);
507 }
508
509 \f
510 #ifdef STANDALONE
511
512 #include <stdio.h>
513 #include <string.h>
514
515 int
516 print_hash_table_mapper (void *key, void *value, void *count)
517 {
518   ++*(int *)count;
519   printf ("%s: %s\n", (const char *)key, (char *)value);
520   return 0;
521 }
522
523 void
524 print_hash (struct hash_table *sht)
525 {
526   int debug_count = 0;
527   hash_table_map (sht, print_hash_table_mapper, &debug_count);
528   assert (debug_count == sht->count);
529 }
530
531 int
532 main (void)
533 {
534   struct hash_table *ht = make_string_hash_table (0);
535   char line[80];
536   while ((fgets (line, sizeof (line), stdin)))
537     {
538       int len = strlen (line);
539       if (len <= 1)
540         continue;
541       line[--len] = '\0';
542       if (!hash_table_exists (ht, line))
543         hash_table_put (ht, strdup (line), "here I am!");
544 #if 1
545       if (len % 3)
546         {
547           char *line_copy;
548           if (hash_table_get_pair (ht, line, &line_copy, NULL))
549             {
550               hash_table_remove (ht, line);
551               free (line_copy);
552             }
553         }
554 #endif
555     }
556 #if 0
557   print_hash (ht);
558 #endif
559 #if 1
560   printf ("%d %d %d\n", ht->count, ht->fullness, ht->size);
561 #endif
562   return 0;
563 }
564 #endif