#include #include #include #include "hashtable.h" const unsigned int fnvPrime = 16777619; const unsigned int fnvOffset = 2166136261U; pair_t init_pair(char* key, void* value) { pair_t p; if (key != NULL) { char* kp = malloc((strlen(key) + 1) * sizeof(char)); strcpy(kp, key); p.key = kp; } else { p.key = NULL; } p.value = value; return p; } 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->capacity = capacity; ht->parent = 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); } } free(hashtable->pairs); free(hashtable); } //FNV-1a hash unsigned int get_hash(char* str) { unsigned int hash = fnvOffset; while (*str != '\0') { hash = (hash ^ *str) * fnvPrime; str++; } return hash; } 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]; if (p.key == NULL || p.key == pair.key) { hashtable->pairs[hash % hashtable->capacity] = pair; return hash; } } return 0; } 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]; if (p.key == key) { return p; } else if (p.key == NULL) { return init_pair(NULL, NULL); } } 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; }