45 lines
1.1 KiB
C
45 lines
1.1 KiB
C
|
#define AOC_HASHMAP_RADIX 1024
|
||
|
|
||
|
int aoc_hash(const char *string) {
|
||
|
int len = strlen(string);
|
||
|
int hash = 1;
|
||
|
for (int i = 0; i < len; i++) {
|
||
|
hash *= 7;
|
||
|
hash += string[i] * 13;
|
||
|
hash %= AOC_HASHMAP_RADIX;
|
||
|
}
|
||
|
|
||
|
return hash;
|
||
|
}
|
||
|
|
||
|
typedef struct AocHashmapNode AocHashmapNode;
|
||
|
|
||
|
typedef struct AocHashmapNode {
|
||
|
char *key;
|
||
|
long value;
|
||
|
AocHashmapNode *next;
|
||
|
} AocHashmapNode;
|
||
|
|
||
|
typedef struct AocHashmap {
|
||
|
AocHashmapNode* buckets[AOC_HASHMAP_RADIX];
|
||
|
} AocHashmap;
|
||
|
|
||
|
AocHashmapNode *aoc_hashmap_get(AocHashmap *map, char *key) {
|
||
|
int hash = aoc_hash(key);
|
||
|
AocHashmapNode *node = map->buckets[hash];
|
||
|
while (node != NULL && strcmp(node->key, key) != 0) node = node->next;
|
||
|
return node;
|
||
|
}
|
||
|
|
||
|
void *aoc_hashmap_put(AocHashmap *map, char *key, long value) {
|
||
|
int hash = aoc_hash(key);
|
||
|
AocHashmapNode *node = map->buckets[hash];
|
||
|
while (node != NULL) node = node->next;
|
||
|
map->buckets[hash] = malloc(sizeof(AocHashmapNode));
|
||
|
node = map->buckets[hash];
|
||
|
node->key = malloc(strlen(key) + 1);
|
||
|
strcpy(node->key, key);
|
||
|
node->value = value;
|
||
|
node->next = NULL;
|
||
|
}
|