2 Copyright (C) 2000 Free Software Foundation, Inc.
4 This file is part of Wget.
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.
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.
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. */
33 # define xmalloc malloc
34 # define xrealloc realloc
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.
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.
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().
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().
64 When specifying your own hash and test functions, make sure the
67 - The test function returns non-zero for keys that are considered
68 "equal", zero otherwise.
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.
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
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.
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.
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. */
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".
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.
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
127 unsigned long (*hash_function) (const void *);
128 int (*test_function) (const void *, const void *);
130 int size; /* size of the array */
131 int fullness; /* number of non-empty fields */
132 int count; /* number of non-empty, non-deleted
135 struct mapping *mappings;
138 #define ENTRY_DELETED ((void *)0xdeadbeef)
139 #define ENTRY_EMPTY NULL
141 #define DELETED_ENTRY_P(ptr) ((ptr) == ENTRY_DELETED)
142 #define EMPTY_ENTRY_P(ptr) ((ptr) == ENTRY_EMPTY)
144 /* Find a prime near, but greather than or equal to SIZE. */
147 prime_size (int size)
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
161 for (i = 0; i < ARRAY_SIZE (primes); i++)
162 if (primes[i] >= size)
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. */
174 hash_table_new (int initial_size,
175 unsigned long (*hash_function) (const void *),
176 int (*test_function) (const void *, const void *))
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);
185 ht->mappings = xmalloc (ht->size * sizeof (struct mapping));
186 memset (ht->mappings, '\0', ht->size * sizeof (struct mapping));
190 /* Free the data associated with hash table HT. */
193 hash_table_destroy (struct hash_table *ht)
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
205 find_mapping (struct hash_table *ht, const void *key)
207 struct mapping *mappings = ht->mappings;
209 int location = ht->hash_function (key) % size;
212 struct mapping *mp = mappings + location;
213 void *mp_key = mp->key;
215 if (EMPTY_ENTRY_P (mp_key))
217 else if (DELETED_ENTRY_P (mp_key)
218 || !ht->test_function (key, mp_key))
220 if (++location == size)
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
236 hash_table_get (struct hash_table *ht, const void *key)
238 int location = find_mapping (ht, key);
242 return ht->mappings[location].value;
245 /* Like hash_table_get, but writes out the pointers to both key and
246 value. Returns non-zero on success. */
249 hash_table_get_pair (struct hash_table *ht, const void *lookup_key,
250 void *orig_key, void *value)
252 int location = find_mapping (ht, lookup_key);
257 struct mapping *mp = ht->mappings + location;
259 *(void **)orig_key = mp->key;
261 *(void **)value = mp->value;
266 /* Return 1 if KEY exists in HT, 0 otherwise. */
269 hash_table_exists (struct hash_table *ht, const void *key)
271 return find_mapping (ht, key) >= 0;
274 #define MAX(i, j) (((i) >= (j)) ? (i) : (j))
276 /* Grow hash table HT as necessary, and rehash all the key-value
280 grow_hash_table (struct hash_table *ht)
283 struct mapping *old_mappings = ht->mappings;
284 int old_count = ht->count; /* for assert() below */
285 int old_size = ht->size;
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:
291 ht->size = prime_size (ht->size * 2);
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.) */
300 int needed_size = prime_size (ht->count * 3);
301 ht->size = MAX (old_size, needed_size);
303 printf ("growing from %d to %d\n", old_size, ht->size);
305 ht->mappings = xmalloc (ht->size * sizeof (struct mapping));
306 memset (ht->mappings, '\0', ht->size * sizeof (struct mapping));
308 /* Need to reset these two; hash_table_put will reinitialize them. */
311 for (i = 0; i < old_size; i++)
313 struct mapping *mp = old_mappings + i;
314 void *mp_key = mp->key;
316 if (!EMPTY_ENTRY_P (mp_key)
317 && !DELETED_ENTRY_P (mp_key))
318 hash_table_put (ht, mp_key, mp->value);
320 assert (ht->count == old_count);
324 /* Put VALUE in the hash table HT under the key KEY. This regrows the
325 table if necessary. */
328 hash_table_put (struct hash_table *ht, const void *key, void *value)
330 /* Cannot use find_mapping here because we treat deleted entries
333 struct mapping *mappings = ht->mappings;
335 int location = ht->hash_function (key) % size;
338 struct mapping *mp = mappings + location;
339 void *mp_key = mp->key;
341 if (EMPTY_ENTRY_P (mp_key))
346 mp->key = (void *)key; /* const? */
350 else if (DELETED_ENTRY_P (mp_key))
352 /* We're replacing a deleteed entry, so ht->count gets
353 increased, but ht->fullness remains unchanged. */
357 else if (ht->test_function (key, mp_key))
359 /* We're replacing an existing entry, so ht->count and
360 ht->fullness remain unchanged. */
365 if (++location == size)
369 if (ht->fullness * 4 > ht->size * 3)
370 /* When fullness exceeds 75% of size, regrow the table. */
371 grow_hash_table (ht);
374 /* Remove KEY from HT. */
377 hash_table_remove (struct hash_table *ht, const void *key)
379 int location = find_mapping (ht, key);
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.) */
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. */
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;
407 if (EMPTY_ENTRY_P (mp_after->key))
409 mp->key = ENTRY_EMPTY;
413 mp->key = ENTRY_DELETED;
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
425 hash_table_clear (struct hash_table *ht)
427 memset (ht->mappings, '\0', ht->size * sizeof (struct mapping));
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. */
438 hash_table_map (struct hash_table *ht,
439 int (*mapfun) (void *, void *, void *),
442 struct mapping *mappings = ht->mappings;
444 for (i = 0; i < ht->size; i++)
446 struct mapping *mp = mappings + i;
447 void *mp_key = mp->key;
449 if (!EMPTY_ENTRY_P (mp_key)
450 && !DELETED_ENTRY_P (mp_key))
451 if (mapfun (mp_key, mp->value, closure))
456 /* Support for hash tables whose keys are strings. */
458 /* supposedly from the Dragon Book P436. */
460 string_hash (const void *sv)
463 unsigned const char *x = (unsigned const char *) sv;
469 if ((g = h & 0xf0000000) != 0)
470 h = (h ^ (g >> 24)) ^ g;
477 /* If I ever need it: hashing of integers. */
480 inthash (unsigned int key)
495 string_cmp (const void *s1, const void *s2)
497 return !strcmp ((const char *)s1, (const char *)s2);
500 /* Return a hash table of initial size INITIAL_SIZE suitable to use
504 make_string_hash_table (int initial_size)
506 return hash_table_new (initial_size, string_hash, string_cmp);
516 print_hash_table_mapper (void *key, void *value, void *count)
519 printf ("%s: %s\n", (const char *)key, (char *)value);
524 print_hash (struct hash_table *sht)
527 hash_table_map (sht, print_hash_table_mapper, &debug_count);
528 assert (debug_count == sht->count);
534 struct hash_table *ht = make_string_hash_table (0);
536 while ((fgets (line, sizeof (line), stdin)))
538 int len = strlen (line);
542 if (!hash_table_exists (ht, line))
543 hash_table_put (ht, strdup (line), "here I am!");
548 if (hash_table_get_pair (ht, line, &line_copy, NULL))
550 hash_table_remove (ht, line);
560 printf ("%d %d %d\n", ht->count, ht->fullness, ht->size);