Simplify put code and make free leave table in clean state.
This commit is contained in:
parent
b1a7c21caa
commit
2bf3f32bed
34
src/ht.c
34
src/ht.c
|
@ -35,40 +35,36 @@ void ht_init(ht* ht) {
|
|||
void ht_free(ht* ht) {
|
||||
int index = 0;
|
||||
for (; index < LIBDS_HT_SIZE; index++) {
|
||||
ht_node* head = ht->data[index];
|
||||
while (head) {
|
||||
ht_node* to_delete = head;
|
||||
head = head->next;
|
||||
while (ht->data[index]) {
|
||||
ht_node* to_delete = ht->data[index];
|
||||
ht->data[index] = to_delete->next;
|
||||
ht->free_func(to_delete->key);
|
||||
free(to_delete);
|
||||
}
|
||||
}
|
||||
ht->cmp_func = NULL;
|
||||
ht->copy_func = NULL;
|
||||
ht->free_func = NULL;
|
||||
ht->hash_func = NULL;
|
||||
}
|
||||
|
||||
libds_result ht_put(ht* ht, void* key, void* data) {
|
||||
libds_result result = LIBDS_SUCCESS;
|
||||
ht_node* new_node = NULL;
|
||||
void* new_key = NULL;
|
||||
unsigned long key_int = ht->hash_func(key) % LIBDS_HT_SIZE;
|
||||
|
||||
new_node = malloc(sizeof(*new_node));
|
||||
if (new_node) {
|
||||
new_key = ht->copy_func(key);
|
||||
if (new_node && new_key) {
|
||||
new_node->data = data;
|
||||
new_node->key = ht->copy_func(key);
|
||||
if (new_node->key == NULL) {
|
||||
result = LIBDS_MALLOC;
|
||||
}
|
||||
} else {
|
||||
result = LIBDS_MALLOC;
|
||||
}
|
||||
|
||||
if (result != LIBDS_SUCCESS) {
|
||||
if (new_node) {
|
||||
free(new_node);
|
||||
new_node = NULL;
|
||||
}
|
||||
} else {
|
||||
new_node->key = new_key;
|
||||
new_node->next = ht->data[key_int];
|
||||
ht->data[key_int] = new_node;
|
||||
} else {
|
||||
free(new_node);
|
||||
free(new_key);
|
||||
result = LIBDS_MALLOC;
|
||||
}
|
||||
|
||||
return result;
|
||||
|
|
Loading…
Reference in New Issue
Block a user