blob: 7cb253c87ea3fd9d40900f8e321275e821844974 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
#include <stdlib.h>
#include <stdio.h>
#include "hashtable.h"
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;
return p;
}
hashtable_t* init_hashtable(unsigned int capacity) {
hashtable_t* ht = malloc(sizeof(hashtable_t));
ht->pairs = calloc(capacity, sizeof(pair_t*));
ht->capacity = capacity;
return ht;
}
//FNV-1a hash
unsigned int get_hash(char* str) {
unsigned int hash = fnvOffset;
while (*str != '\0') {
hash = (hash ^ *str) * fnvPrime;
str++;
}
return hash;
}
/* 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);
hashtable->pairs[hash % hashtable->capacity] = pair;
return hash;
}
pair_t* hashtable_get_pair(hashtable_t* hashtable, char* key) {
unsigned int hash = get_hash(key);
return hashtable->pairs[hash % hashtable->capacity];
}
|