2 * Some generic hashing helpers.
8 * Look up a hash entry in the hash table. Return the pointer to
9 * the existing entry, or the empty slot if none existed. The caller
10 * can then look at the (*ptr) to see whether it existed or not.
12 static struct hash_table_entry *lookup_hash_entry(unsigned int hash, struct hash_table *table)
14 unsigned int size = table->size, nr = hash % size;
15 struct hash_table_entry *array = table->array;
17 while (array[nr].ptr) {
18 if (array[nr].hash == hash)
29 * Insert a new hash entry pointer into the table.
31 * If that hash entry already existed, return the pointer to
32 * the existing entry (and the caller can create a list of the
33 * pointers or do anything else). If it didn't exist, return
34 * NULL (and the caller knows the pointer has been inserted).
36 static void **insert_hash_entry(unsigned int hash, void *ptr, struct hash_table *table)
38 struct hash_table_entry *entry = lookup_hash_entry(hash, table);
49 static void grow_hash_table(struct hash_table *table)
52 unsigned int old_size = table->size, new_size;
53 struct hash_table_entry *old_array = table->array, *new_array;
55 new_size = alloc_nr(old_size);
56 new_array = xcalloc(sizeof(struct hash_table_entry), new_size);
57 table->size = new_size;
58 table->array = new_array;
60 for (i = 0; i < old_size; i++) {
61 unsigned int hash = old_array[i].hash;
62 void *ptr = old_array[i].ptr;
64 insert_hash_entry(hash, ptr, table);
69 void *lookup_hash(unsigned int hash, struct hash_table *table)
73 return lookup_hash_entry(hash, table)->ptr;
76 void **insert_hash(unsigned int hash, void *ptr, struct hash_table *table)
78 unsigned int nr = table->nr;
79 if (nr >= table->size/2)
80 grow_hash_table(table);
81 return insert_hash_entry(hash, ptr, table);
84 int for_each_hash(struct hash_table *table, int (*fn)(void *))
88 unsigned int size = table->size;
89 struct hash_table_entry *array = table->array;
91 for (i = 0; i < size; i++) {
92 void *ptr = array->ptr;
104 void free_hash(struct hash_table *table)