19 #define BITS_IN_int (sizeof(int) * CHAR_BIT)
20 #define THREE_QUARTERS ((int)((BITS_IN_int * 3) / 4))
21 #define ONE_EIGHTH ((int)(BITS_IN_int / 8))
22 #define HIGH_BITS (~((unsigned int)(~0) >> ONE_EIGHTH))
24 static unsigned int hash_pjw(
void *key);
25 static int string_compare(
void *a,
void *b);
39 static unsigned int hash_pjw(
void *key)
41 char *datum = (
char*)key;
42 unsigned int hash_value, i;
47 for (hash_value = 0; *datum; ++datum) {
48 hash_value = (hash_value << ONE_EIGHTH) + *datum;
49 if ((i = hash_value & HIGH_BITS) != 0)
50 hash_value = (hash_value ^ (i >> THREE_QUARTERS)) & ~HIGH_BITS;
56 static int string_compare(
void *a,
void *b)
58 return (strcmp( (
char*)a, (
char*)b ) == 0);
73 unsigned int (*hash_function)(
void*),
74 int (*hash_key_compare)(
void*,
void*))
89 ht->nbuckets = nbuckets;
90 for(i = 0; i < ht->nbuckets; i++)
91 ht->buckets[i] = NULL;
93 ht->hash_function = hash_function ? hash_function : hash_pjw;
94 ht->hash_key_compare = hash_key_compare ? hash_key_compare : string_compare;
112 unsigned int hash_val;
117 hash_val = (*ht->hash_function)(key) % ht->nbuckets;
118 for (curr = ht->buckets[hash_val]; curr != NULL; curr = curr->next)
119 if (ht->hash_key_compare(curr->key, key))
138 unsigned int hash_val;
143 hash_val = (*ht->hash_function)(key) % ht->nbuckets;
144 for (curr = ht->buckets[hash_val]; curr != NULL; curr = curr->next)
145 if (ht->hash_key_compare(curr->key, key))
155 curr->next = ht->buckets[hash_val];
157 ht->buckets[hash_val] = curr;
175 icl_hash_t *ht,
void* key,
void *data,
void **olddata)
178 unsigned int hash_val;
183 hash_val = (*ht->hash_function)(key) % ht->nbuckets;
186 for (prev = NULL, curr=ht->buckets[hash_val];
188 prev = curr, curr = curr->next)
191 if (ht->hash_key_compare(curr->key, key)) {
192 if (olddata != NULL) {
193 *olddata = curr->data;
197 ht->buckets[hash_val] = curr->next;
199 prev->next = curr->next;
210 curr->next = ht->buckets[hash_val];
212 ht->buckets[hash_val] = curr;
215 if (olddata != NULL && *olddata != NULL)
236 void (*free_key)(
void*),
237 void (*free_data)(
void*))
240 unsigned int hash_val;
245 hash_val = (*ht->hash_function)(key) % ht->nbuckets;
248 for (curr = ht->buckets[hash_val]; curr != NULL;) {
249 if (ht->hash_key_compare(curr->key, key)) {
251 ht->buckets[hash_val] = curr->next;
254 prev->next = curr->next;
256 if (*free_key && curr->key)
257 (*free_key)(curr->key);
258 if (*free_data && curr->data)
259 (*free_data)(curr->data);
284 void (*free_key)(
void*),
285 void (*free_data)(
void*))
293 for (i = 0; i < ht->nbuckets; i++) {
294 bucket = ht->buckets[i];
295 for (curr = bucket; curr!=NULL;) {
297 if (*free_key && curr->key)
298 (*free_key)(curr->key);
299 if (*free_data && curr->data)
300 (*free_data)(curr->data);
331 for (i = 0; i < ht->nbuckets; i++) {
332 bucket = ht->buckets[i];
333 for (curr = bucket; curr!=NULL;) {
336 "icl_hash_dump: %s: %p\n", (
char*)curr->key, curr->data);