Our hash table implementation
This is a generic hash table implementation used in several coral applications, but is not an essential part of libcoral.
To create a hash table, use init_hash_table(), which sets up
the hash table and all of the necessary functions for using it. So before
doing this, you must create three functions:
Comparison function
int compare_function(const void *, const void *);
This function is used to check the equality of two entries.
Returns 0 if equal, non-zero otherwise.
Example:
int compare_long(const void * entry1, const void * entry2)
{
static long * typed_entry1 = (long *)entry1;
static long * typed_entry2 = (long *)entry2;
return *typed_entry1 == *typed_entry2;
}
Key Generation function
unsigned long key_function(const void *);
This function takes the pointer to an entry and creates a key from it. eg, a struct might have one of its members as a key, a long would just be its own key.
Example:
unsigned long make_key_long(const void * entry)
{
static long * typed_entry = (long *)entry;
return *typed_entry;
}
Deletion function
void delete_function(void *);
This function is called when a hash entry is to be deleted.
Example:
void delete_long(void * entry)
{
static long * typed_entry = (long *)entry;
free(typed_entry);
}
Once these functions are defined, you can create a hash table thusly:
....
hash_tab * long_hash;
long_hash = init_hash_table("My table of longs", compare_long, make_key_long,
delete_long, 101);
....
The rest of the functions are fairly self-explanatory and can be demonstrated with code examples:
long * new_entry;
long check_entry;
long * found_entry;
new_entry = (long *)malloc(sizeof(long));
*new_entry = 3.14159;
check_entry = 2.7;
add_hash_entry(long_hash, new_entry);
found_entry = (long *)find_hash_entry(long_hash, &check_entry);
if (found_entry == NULL) {
printf("Hey, I couldn't find it!\n");
} else {
*found_entry = 22/7;
}
init_hash_walk(long_hash);
while (found_entry = next_hash_walk(long_hash)) {
printf("Found this entry: %d\n", *found_entry);
}
dump_hashtab_stats(long_hash);
clear_hash_entry(long_hash, found_entry);
clear_hash_table(long_hash);
free_hash_table(long_hash);
Notes:
add_hash_entry() does NOT copy the entry, so make sure not
to pass in pointers to local variables.find_hash_entry() returns the pointer to the actual data in
the hashtable, so any modifications are made in the hashtable.dump_hashtab_stats() dumps to stdout.Problems? Write us: coral-bugs@caida.org

