Update README.md
[sm64pc.git] / tools / hashtable.c
blob2c881c267252c21a4d233411cf4d1471ee836bde
1 #include <stdint.h>
2 #include <stdlib.h>
3 #include <string.h>
4 #include <stdio.h>
6 #include "hashtable.h"
8 struct HashNode
10 struct HashNode *next;
11 uint8_t value[];
14 struct HashTable
16 HashFunc func;
17 HashValueCmpFunc cmp;
18 int size;
19 int elemSize;
20 struct HashNode *table[];
23 struct HashTable *hashtable_new(HashFunc func, HashValueCmpFunc cmp, int size,
24 int elemSize)
26 struct HashTable *ht = malloc(sizeof(*ht) + size * sizeof(ht->table[0]));
28 ht->func = func;
29 ht->cmp = cmp;
30 ht->size = size;
31 ht->elemSize = elemSize;
32 memset(ht->table, 0, ht->size * sizeof(ht->table[0]));
33 return ht;
36 void hashtable_free(struct HashTable *ht)
38 int i;
40 for (i = 0; i < ht->size; i++)
42 struct HashNode *node = ht->table[i];
44 while (node != NULL)
46 struct HashNode *next = node->next;
48 free(node);
49 node = next;
52 free(ht);
55 void hashtable_insert(struct HashTable *ht, const void *value)
57 unsigned int key = ht->func(value) % ht->size;
58 struct HashNode *node = malloc(sizeof(*node) + ht->elemSize);
60 node->next = NULL;
61 memcpy(node->value, value, ht->elemSize);
63 if (ht->table[key] == NULL)
65 ht->table[key] = node;
67 else
69 struct HashNode *parent = ht->table[key];
71 while (parent->next != NULL)
72 parent = parent->next;
73 parent->next = node;
77 void *hashtable_query(struct HashTable *ht, const void *value)
79 unsigned int key = ht->func(value) % ht->size;
80 struct HashNode *node = ht->table[key];
82 while (node != NULL)
84 if (ht->cmp(node->value, value))
85 return node->value;
86 node = node->next;
88 return NULL;