summaryrefslogtreecommitdiff
path: root/src/hashtable.c
diff options
context:
space:
mode:
authorKai Stevenson <kai@kaistevenson.com>2023-02-16 19:24:20 -0800
committerKai Stevenson <kai@kaistevenson.com>2023-02-16 19:24:20 -0800
commitdeeb6aa4aa60e22190087a9615447e742c84a19c (patch)
tree11d8ae0e6c684ed5a14657a0fb048a28d45be945 /src/hashtable.c
parent7410d984ae270528ea4f3f16d3473acf807ef92c (diff)
added scoping and a lot of memory leaks
Diffstat (limited to 'src/hashtable.c')
-rw-r--r--src/hashtable.c33
1 files changed, 24 insertions, 9 deletions
diff --git a/src/hashtable.c b/src/hashtable.c
index 7cb253c..2f4ca64 100644
--- a/src/hashtable.c
+++ b/src/hashtable.c
@@ -5,18 +5,23 @@
const unsigned int fnvPrime = 16777619;
const unsigned int fnvOffset = 2166136261U;
-pair_t* init_pair(char* key, void* value) {
- pair_t* p = malloc(sizeof(pair_t));
- p->key = key;
- p->value = value;
+pair_t init_pair(char* key, void* value) {
+ pair_t p;
+ p.key = key;
+ p.value = value;
return p;
}
-hashtable_t* init_hashtable(unsigned int capacity) {
+hashtable_t* init_hashtable(unsigned int capacity, hashtable_t* parent) {
hashtable_t* ht = malloc(sizeof(hashtable_t));
- ht->pairs = calloc(capacity, sizeof(pair_t*));
+ ht->pairs = calloc(capacity, sizeof(pair_t));
ht->capacity = capacity;
+ ht->parent = parent;
return ht;
}
+void destroy_hashtable(hashtable_t* hashtable) {
+ free(hashtable->pairs);
+ free(hashtable);
+}
//FNV-1a hash
unsigned int get_hash(char* str) {
unsigned int hash = fnvOffset;
@@ -28,12 +33,22 @@ unsigned int get_hash(char* str) {
}
/* TODO: handle collision
TODO: return 0 if something goes wrong */
-unsigned int hashtable_add_pair(hashtable_t* hashtable, pair_t* pair) {
- unsigned int hash = get_hash(pair->key);
+unsigned int hashtable_add_pair(hashtable_t* hashtable, pair_t pair) {
+ unsigned int hash = get_hash(pair.key);
hashtable->pairs[hash % hashtable->capacity] = pair;
return hash;
}
-pair_t* hashtable_get_pair(hashtable_t* hashtable, char* key) {
+pair_t hashtable_get_pair(hashtable_t* hashtable, char* key) {
unsigned int hash = get_hash(key);
return hashtable->pairs[hash % hashtable->capacity];
}
+pair_t hashtable_get_pair_recurse(hashtable_t* origin, char* key) {
+ pair_t pair = hashtable_get_pair(origin, key);
+ if (pair.key != NULL) {
+ return pair;
+ }
+ if (origin->parent != NULL) {
+ return hashtable_get_pair_recurse(origin->parent, key);
+ }
+ return pair;
+}