Hashmap implementation in C using linked list for collision resolution.
To create a hashmap call the hashmap_create
function:
hashmap *map = hashmap_create(12, NULL, NULL);
If you use a string type key, just pass NULL
to use the default hash algorithm and compare function. Otherwise, you can also use your own algorithm and function.
To set an entry in the hashmap use the hashmap_set
function:
hashmap_set(map, "k1", "v1");
char *pre = hashmap_set(map, "k1", "v2"); // return "v1"
To get an entry from a hashmap use the hashmap_get
function:
void *value = hashmap_get(map, "k1");
To remove an entry from a hashmap use the hashmap_remove
function:
char *removed = hashmap_remove(map, "k1");
You can iterate over all the entries stored in the hashmap with the hashmap_iterate
function:
static bool iterator(void *key, void *value, void *context) {
printf("k: %s, v: %s\n", key, value);
if (strcmp(key, "k3") == 0) {
*(bool *)context = true;
// Stop here
return false;
}
return true;
}
bool found;
hashmap_iterate(map, iterator, &found);
You can early exit from the iteration of the hashmap by returning false
from your callback function.
To get the number of entries stored in the hashmap use the hashmap_count
function:
size_t count = hashmap_count(map);
To Free a hashmap when you are finished with it use the hashmap_free
function:
hashmap_free(map);
map = NULL;
This does not free the keys or values themselves.
For thread safety when getting and setting, use the hashmap_lock
and hashmap_unlock
functions:
hashmap_lock(map);
hashmap_set(map, "k1", "v1");
hashmap_unlock(map);