HashTable Class

Overview

The HashTable class stores an object pointer with a particular key name. The (null-terminated) key string is automatically allocated in all instances. The object pointer can be anything you like.

The HashTable_new() is used to create a new HashTable object. You specify the size of the underlying array, which should be a prime number to avoid uneven distribution of hash elements. The options are specified as two bools: specify "true" for autoDupData if you want the store function to automatically strdup() the object data; specify "true" for autoFreeData if you want deleted or superseded data to be automatically freed by the HashTable routines.

The HashTable_delete() deletes all the hash data associated with the indicated table. If you have malloc'ed the object pointers and have not specified the autoFreeData option (if, for instance, your data is more complex than a single free can handle), you should first walk through the entire hash will a function that frees all the allocated objects before you destroy the hash structure.

The HashTable_store() function takes a key string and an object pointer and associates the latter with the former. If there was previously an object with the same key name already stored in the hash, the previous value is superseded, and its object pointer is the return value of the function. If the autoFreeData option was specified, this pointer will have already been freed, so you should not the value as more than a bool indicator in such a case.

The HashTable_fetch() function looks up the object associated with a particular key name and returns it or a NULL.

The HashTable_remove() function removes a key name item from the hash. The object pointer is returned (or NULL if not found), and it will have already been freed if you have specified the autoFreeData option.

The HashTable_walk() function walks through the entire hash and calls a user-supplied callback function for each and every entry. If the callback function returns a negative number, the just-walked entry is removed from the hash. If the value is 0, the walking stops. A positive value causes the walking to continue on to the next hash entry.

The HashTable_keys() function returns a newly allocated array of characters pointers, pointing to the key names that are contained in the hash. The key names themselves are shared with the hash data, so do not free them or disturb them in any way (you may free the array data, of course). If you remove a HashTable entry from the hash, its key name will be also be freed, so you must make sure that you don't access the list of keys names after the data is no longer valid. To determine how many entries are in the list, see HashTable_itemCnt().

The HashTable_itemCnt() function returns the count of how many items are in the hash table.