return ht; } /* delete a HashTable instance */ voidhash_table_delete(HashTable* ht) { if (ht) { if (ht->table) { int i = 0; for (i = 0; i<TABLE_SIZE; i++) { structkv* p = ht->table[i]; structkv* q = NULL; while (p) { q = p->next; free_kv(p); p = q; } } free(ht->table); ht->table = NULL; } free(ht); } }
/* insert or update a value indexed by key */ int hash_table_put(HashTable* ht, char* key, void* value, void(*free_value)(void*)) { int i = hash_33(key) % TABLE_SIZE; structkv* p = ht->table[i]; structkv* prep = p;
while (p) { /* if key is already stroed, update its value */ if (strcmp(p->key, key) == 0) { if (p->free_value) { p->free_value(p->value); } p->value = value; p->free_value = free_value; break; } prep = p; p = p->next; }
if (p == NULL) {/* if key has not been stored, then add it */ char* kstr = malloc(strlen(key) + 1); if (kstr == NULL) { return-1; } structkv * kv = malloc(sizeof(structkv)); if (NULL == kv) { free(kstr); kstr = NULL; return-1; } init_kv(kv); kv->next = NULL; strcpy(kstr, key); kv->key = kstr; kv->value = value; kv->free_value = free_value;
/* get a value indexed by key */ void* hash_table_get(HashTable* ht, char* key) { int i = hash_33(key) % TABLE_SIZE; structkv* p = ht->table[i]; while (p) { if (strcmp(key, p->key) == 0) { return p->value; } p = p->next; } returnNULL; }
/* remove a value indexed by key */ voidhash_table_rm(HashTable* ht, char* key) { int i = hash_33(key) % TABLE_SIZE;
structkv* p = ht->table[i]; structkv* prep = p; while (p) { if (strcmp(key, p->key) == 0) { free_kv(p); if (p == prep) { ht->table[i] = NULL; } else { prep->next = p->next; } } prep = p; p = p->next; } }