summaryrefslogtreecommitdiff
path: root/src/hashtable.c
diff options
context:
space:
mode:
authorKai Stevenson <kai@kaistevenson.com>2023-02-20 22:07:59 -0800
committerKai Stevenson <kai@kaistevenson.com>2023-02-20 22:07:59 -0800
commit84ba393f95aa85d975b4bb9f816be4babd1d50d5 (patch)
tree1d2ef4b3f75b44ba1b21a75d09fcdcb95097f59c /src/hashtable.c
parent7cd204152e388e3462294aafbea4adb626ba9547 (diff)
optimized hashtable and fixed a bug
Diffstat (limited to 'src/hashtable.c')
-rw-r--r--src/hashtable.c11
1 files changed, 7 insertions, 4 deletions
diff --git a/src/hashtable.c b/src/hashtable.c
index 2ec766d..84676a9 100644
--- a/src/hashtable.c
+++ b/src/hashtable.c
@@ -27,7 +27,6 @@ hashtable_t* init_hashtable(unsigned int capacity, hashtable_t* parent) {
return ht;
}
void destroy_hashtable(hashtable_t* hashtable) {
- /* TODO: optimize this */
for (int i = 0; i < hashtable->capacity; i++) {
if (hashtable->pairs[i].key != NULL) {
free(hashtable->pairs[i].key);
@@ -48,9 +47,11 @@ unsigned int get_hash(char* str) {
unsigned int hashtable_add_pair(hashtable_t* hashtable, pair_t pair) {
unsigned int hash = get_hash(pair.key);
for (int i = 0; i < hashtable->capacity; i++) {
- pair_t p = hashtable->pairs[hash % hashtable->capacity];
+ unsigned int ha = hash + i;
+ unsigned int ia = ha % hashtable->capacity;
+ pair_t p = hashtable->pairs[ia];
if (p.key == NULL || strcmp(p.key, pair.key) == 0) {
- hashtable->pairs[hash % hashtable->capacity] = pair;
+ hashtable->pairs[ia] = pair;
return hash;
}
}
@@ -69,7 +70,9 @@ unsigned int hashtable_update_pair_recurse(hashtable_t* origin, pair_t pair) {
pair_t hashtable_get_pair(hashtable_t* hashtable, char* key) {
unsigned int hash = get_hash(key);
for (int i = 0; i < hashtable->capacity; i++) {
- pair_t p = hashtable->pairs[hash % hashtable->capacity];
+ unsigned int ha = hash + i;
+ unsigned int ia = ha % hashtable->capacity;
+ pair_t p = hashtable->pairs[ia];
if (p.key != NULL && strcmp(p.key, key) == 0) {
return p;
}