Dictionary is a key-value storage useful for different purposes.
The key is always of type char * (string) and the value can be any type.
Since we don't know the type of the value in advance, (it can be a pointer to char or int or a custom structure), We have to know how to copy the value and how to free the allocated memory for the value.
Therefore, the cdict_init() function will accept two parameters:
- cdict_free_func: A pointer to the user provided function to free the memory for the value.
- cdict_copy_func: A pointer to the user provided function to copy the
value.
Other things are easy to use and understand.
There are currently four functions available for the dictionary structure:
- Adding a key-value pair to the dictionary
- Removing a key-value pair from a dictionary
- Getting a value from the dictionary by providing the key
- Lists all the keys
Example
Check the examples in test directory.
Here is a small example:
Compile this with:
# inside the test directory
gcc -O2 ./test_1.c ../src/cdict.c ../include/cdict.h -o test
# and then run ./test
#include <cdict.h>
#include <cunittest.h>
#include <stdlib.h>
void dict_free_func(void * value){
free(value);
}
void* dict_copy_func(void * value){
return (void*) strdup((char*)value);
}
int main(int argc, char ** argv){
srand(1);
ABORT_ON_FAIL(1);
int COUNT = 500000;
int random_val = 0;
char key[50] = {0};
for (int i=0; i< COUNT; ++i){
random_val = rand();
sprintf(key, "key_%d", random_val);
fprintf(stdout, "We already have this key: %s\n", key);
continue;
}
cdict_set(new_dict, key, (
void *)
"John Doe");
}
fprintf(stdout, "We have %d keys\n", klst->len);
for (unsigned long int i=0; i< klst->len; ++i){
}
return 0;
}
void cdict_free_keylist(cdict_keylist *klst, int clone_keys)
This function free the keylist structure returned by cdict_keys()
void cdict_free(cdict_ctx *ctx)
Frees the memory allocated for the dictionary.
int cdict_has_key(cdict_ctx *ctx, char *key)
Checks if the key exists in the dictionary.
cdict_ctx * cdict_init(void(*free_func)(void *), void *(*copy_func)(void *))
Initializes the Dictionary in the memory.
int cdict_set(cdict_ctx *ctx, char *key, void *value)
Sets the new value for a given key.
cdict_keylist * cdict_keys(cdict_ctx *ctx, int clone_keys)
Get the list of keys from the dictionary.
test_1.c: shows how to insert key-value pairs to the dictionary and check if a key exists.
if values are of type char *, then I use
to initialize the dictionary.
However, if I want to store a custom structure in the dictionary, I have to provide two custom functions to free and copy the structure for me.
Look at test_2.c in the test directory for more info.
test_remove.c in test directory shows how to remove the key in a for-loop.
test_2.c in test directory shows how to store custom structure as values in the dictionary.
Documentation
Use Doxygen to generate the documents