From c1563337ae366ca66f25ed71a2f462a486df1337 Mon Sep 17 00:00:00 2001 From: Benny Baumann Date: Sun, 29 Nov 2020 14:54:10 +0100 Subject: [PATCH] Implement Hashtable_clear to empty an existing Hashtable --- Hashtable.c | 22 +++++++++++++++------- Hashtable.h | 2 ++ 2 files changed, 17 insertions(+), 7 deletions(-) diff --git a/Hashtable.c b/Hashtable.c index c03723a1..cd48fc46 100644 --- a/Hashtable.c +++ b/Hashtable.c @@ -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; diff --git a/Hashtable.h b/Hashtable.h index f7d1aae2..6d934784 100644 --- a/Hashtable.h +++ b/Hashtable.h @@ -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);