/** * Fetch an item with a given key value from the hash table * * @param table The hash table * @param key The key value * @return The item or NULL if the item was not found */ void * hashtable_fetch(HASHTABLE *table, void *key) { unsigned int hashkey; HASHENTRIES *entry; if (table == NULL || key == NULL || 0 == table->hashsize) { return NULL; } hashkey = table->hashfn(key) % table->hashsize; hashtable_read_lock(table); entry = table->entries[hashkey % table->hashsize]; while (entry && entry->key && table->cmpfn(key, entry->key) != 0) { entry = entry->next; } if (entry == NULL) { hashtable_read_unlock(table); return NULL; } else { hashtable_read_unlock(table); return entry->value; } }
/** * Return the next key for a hashtable iterator * * @param iter The hashtable iterator * @return The next key value or NULL */ void * hashtable_next(HASHITERATOR *iter) { int i; HASHENTRIES *entries; iter->depth++; while (iter->chain < iter->table->hashsize) { if ((entries = iter->table->entries[iter->chain]) != NULL) { i = 0; hashtable_read_lock(iter->table); while (entries && i < iter->depth) { entries = entries->next; i++; } hashtable_read_unlock(iter->table); if (entries) return entries->key; } iter->depth = 0; iter->chain++; } return NULL; }
/** * Produces stat output about hashtable * * Parameters: * @param table - <usage> * <description> * * @param hashsize - <usage> * <description> * * @param nelems - <usage> * <description> * * @param longest - <usage> * <description> * * @return void * * */ void hashtable_get_stats( void* table, int* hashsize, int* nelems, int* longest) { HASHTABLE* ht; HASHENTRIES* entries; int i; int j; ht = (HASHTABLE *)table; CHK_HASHTABLE(ht); *nelems = 0; *longest = 0; hashtable_read_lock(ht); for (i = 0; i < ht->hashsize; i++) { j = 0; entries = ht->entries[i]; while (entries) { j++; entries = entries->next; } *nelems += j; if (j > *longest) { *longest = j; } } *hashsize = ht->hashsize; hashtable_read_unlock(ht); }
/** * Print hash table statistics to the standard output * * @param table The hash table */ void hashtable_stats(HASHTABLE *table) { int total, longest, i, j; HASHENTRIES *entries; printf("Hashtable: %p, size %d\n", table, table->hashsize); total = 0; longest = 0; hashtable_read_lock(table); for (i = 0; i < table->hashsize; i++) { j = 0; entries = table->entries[i]; while (entries) { j++; entries = entries->next; } total += j; if (j > longest) longest = j; } hashtable_read_unlock(table); printf("\tNo. of entries: %d\n", total); printf("\tAverage chain length: %.1f\n", (float)total / table->hashsize); printf("\tLongest chain length: %d\n", longest); }