#include #include #include #include #include "hashmap.h" bool keys_eq_impl(void *opaque, const void *_a, const void *_b) { (void)opaque; const char * const *a = _a; const char * const *b = _b; return strcmp(*a, *b) == 0; } apfl_hash calc_hash_impl(void *opaque, const void *_key) { (void)opaque; const char * const *key = _key; return apfl_hash_fnv1a(*key, strlen(*key)); } void destroy_kv_impl(void *opaque, void *_data) { (void)opaque; char **data = _data; free(*data); } bool copy_kv_impl(void *opaque, void *_dest, const void *_src) { (void)opaque; char **dest = _dest; const char * const *src = _src; *dest = malloc(strlen(*src) + 1); if (*dest == NULL) { return false; } strcpy(*dest, *src); return true; } #define BUFSIZE 10000 int main(int argc, char **argv) { (void)argc; (void)argv; struct apfl_hashmap_callbacks callbacks = { .opaque = NULL, .keys_eq = keys_eq_impl, .calc_hash = calc_hash_impl, .destroy_key = destroy_kv_impl, .destroy_value = destroy_kv_impl, .copy_key = copy_kv_impl, .copy_value = copy_kv_impl, }; apfl_hashmap map = apfl_hashmap_new(callbacks, sizeof(char *), sizeof(char *)); if (map == NULL) { return 1; } char line[BUFSIZE]; char key[BUFSIZE]; char *keyp = &key[0]; char value[BUFSIZE]; char *valuep = &value[0]; char *retreived = NULL; for (;;) { if (fgets(line, BUFSIZE, stdin) == NULL) { break; } char *tok = strtok(line, " "); if (tok == NULL) { continue; } if (strcmp(tok, "set") == 0) { tok = strtok(NULL, " \n"); strcpy(key, tok); tok = strtok(NULL, " \n"); strcpy(value, tok); if (!apfl_hashmap_set(map, &keyp, &valuep)) { return 2; } } else if (strcmp(tok, "get") == 0 ) { tok = strtok(NULL, " \n"); strcpy(key, tok); if (apfl_hashmap_get(map, &keyp, &retreived)) { printf("%s => %s\n", key, retreived); free(retreived); continue; } } else if (strcmp(tok, "del") == 0 ) { tok = strtok(NULL, " \n"); strcpy(key, tok); apfl_hashmap_delete(map, &keyp); } else if (strcmp(tok, "list") == 0) { apfl_hashmap_cursor cur = apfl_hashmap_get_cursor(map); if (cur == NULL) { return 3; } for (; !apfl_hashmap_cursor_is_end(cur); apfl_hashmap_cursor_next(cur)) { char *k = NULL; char *v = NULL; if ( apfl_hashmap_cursor_get_key(cur, &k) && apfl_hashmap_cursor_get_value(cur, &v) ) { printf("%s => %s\n", k, v); } free(k); free(v); } apfl_hashmap_cursor_destroy(cur); } } apfl_hashmap_destroy(map); return 0; }