// I didn't take the effort to clean up this file as I did with // hashtable.c and hashtable.h. It's not really important, tho. // Instead of this "console hashtable" I should make some test cases // (which I probably won't be motivated enough to do anyway). #include #include #include #include "hashtable.h" void print_pair(const char *key, const char *val, void *dummy){ printf("key: %s val: %s\n", key, val); } void free_pair(void *key, void *val, void *dummy){ free(key); free(val); } int main(int argc, char **argv){ hashtable_t ht; if (ht_string_init(&ht)) // HT_NO_MEM { fprintf(stderr, "ERROR, couldn't allocate memory!\n"); exit(-1); } char buf[100]; while (scanf("%99s", buf) != EOF) { if (!strcmp(buf, "add")) { if (scanf("%99s", buf) == EOF) break; size_t len = strlen(buf) + 1; char *key = malloc(len); if (key == NULL) { fprintf(stderr, "ERROR, couldn't allocate memory!\n"); exit(1); } memcpy(key, buf, len); if (scanf("%99s", buf) == EOF) { free(key); break; } len = strlen(buf) + 1; char *val = malloc(len); if (val == NULL) { free(key); fprintf(stderr, "ERROR, couldn't allocate memory!\n"); exit(1); } memcpy(val, buf, len); switch (ht_add(&ht, key, val)) { case HT_OK: break; case HT_NO_MEM: fprintf(stderr, "ERROR, couldn't allocate memory!\n"); free(key); free(val); exit(1); default: // case HT_KEY_PRESENT printf("Key already present!\n"); } } else if (!strcmp(buf, "set")) { if (scanf("%99s", buf) == EOF) break; size_t len = strlen(buf) + 1; char *key = malloc(len); if (key == NULL) { fprintf(stderr, "ERROR, couldn't allocate memory!\n"); exit(1); } memcpy(key, buf, len); if (scanf("%99s", buf) == EOF) break; len = strlen(buf) + 1; char *val = malloc(len); if (val == NULL) { free(key); fprintf(stderr, "ERROR, couldn't allocate memory!\n"); exit(1); } memcpy(val, buf, len); void *oldkey = NULL, *oldval = NULL; if (ht_set(&ht, key, val, &oldkey, &oldval) != 0) { free(key); free(val); fprintf(stderr, "ERROR, couldn't allocate memory!\n"); exit(1); } if (oldval != NULL) { printf("Replaced: %s\n", (char*) oldval); free(oldval); free(oldkey); } } else if (!strcmp(buf, "get")) { if (scanf("%99s", buf) == EOF) break; void *val; if (ht_get(&ht, buf, NULL, &val)) printf("No such entry!\n"); else printf("%s\n", (char*) val); } else if (!strcmp(buf, "rem")) { if (scanf("%99s", buf) == EOF) break; void *storedkey, *val; if (ht_rem(&ht, buf, &storedkey, &val)) printf("No such entry!\n"); else { printf("%s\n", (char*) val); free(val); free(storedkey); } } else if(!strcmp(buf, "entries")) printf("%zu\n", ht.entries); else if(!strcmp(buf, "print")) ht_map(&ht, NULL, (void (*)(void*, void*, void*)) &print_pair); else printf("I have no idea what you're talking about...\n"); } ht_map_destroy(&ht, NULL, (void (*)(void*, void*, void*)) &free_pair); }