Implement Hashtable_clear to empty an existing Hashtable

This commit is contained in:
Benny Baumann 2020-11-29 14:54:10 +01:00
parent 9549ca8c88
commit c1563337ae
2 changed files with 17 additions and 7 deletions

View File

@ -98,23 +98,31 @@ Hashtable* Hashtable_new(unsigned int size, bool owner) {
this->size = size ? nextPrime(size) : 13;
this->buckets = (HashtableItem*) xCalloc(this->size, sizeof(HashtableItem));
this->owner = owner;
assert(Hashtable_isConsistent(this));
return this;
}
void Hashtable_delete(Hashtable* this) {
assert(Hashtable_isConsistent(this));
if (this->owner) {
for (unsigned int i = 0; i < this->size; i++)
free(this->buckets[i].value);
}
Hashtable_clear(this);
free(this->buckets);
free(this);
}
void Hashtable_clear(Hashtable* this) {
assert(Hashtable_isConsistent(this));
if (this->owner)
for (unsigned int i = 0; i < this->size; i++)
free(this->buckets[i].value);
memset(this->buckets, 0, this->size * sizeof(HashtableItem));
this->items = 0;
assert(Hashtable_isConsistent(this));
}
static void insert(Hashtable* this, hkey_t key, void* value) {
unsigned int index = key % this->size;
unsigned int probe = 0;

View File

@ -37,6 +37,8 @@ Hashtable* Hashtable_new(unsigned int size, bool owner);
void Hashtable_delete(Hashtable* this);
void Hashtable_clear(Hashtable* this);
void Hashtable_setSize(Hashtable* this, unsigned int size);
void Hashtable_put(Hashtable* this, hkey_t key, void* value);