src/util/table.c (view raw)
1#include "table.h"
2
3#define LIST_INITIAL_SIZE 8
4
5struct TableTuple {
6 uint32_t key;
7 void* value;
8};
9
10struct TableList {
11 struct TableTuple* list;
12 size_t nEntries;
13 size_t listSize;
14};
15
16void TableInit(struct Table* table, size_t initialSize) {
17 table->tableSize = initialSize;
18 table->table = calloc(table->tableSize, sizeof(struct TableList));
19
20 size_t i;
21 for (i = 0; i < table->tableSize; ++i) {
22 table->table[i].listSize = LIST_INITIAL_SIZE;
23 table->table[i].list = calloc(LIST_INITIAL_SIZE, sizeof(struct TableTuple));
24 }
25}
26
27void TableDeinit(struct Table* table) {
28 size_t i;
29 for (i = 0; i < table->tableSize; ++i) {
30 // TODO: Don't leak entries
31 free(table->table[i].list);
32 }
33 free(table->table);
34 table->table = 0;
35 table->tableSize = 0;
36}
37
38void* TableLookup(struct Table* table, uint32_t key) {
39 uint32_t entry = key & (table->tableSize - 1);
40 struct TableList* list = &table->table[entry];
41 size_t i;
42 for (i = 0; i < list->nEntries; ++i) {
43 if (list->list[i].key == key) {
44 return list->list[i].value;
45 }
46 }
47 return 0;
48}
49
50void TableInsert(struct Table* table, uint32_t key, void* value) {
51 uint32_t entry = key & (table->tableSize - 1);
52 struct TableList* list = &table->table[entry];
53 if (list->nEntries + 1 == list->listSize) {
54 list->listSize *= 2;
55 list->list = realloc(list->list, list->listSize * sizeof(struct TableTuple));
56 }
57 list->list[list->nEntries].key = key;
58 list->list[list->nEntries].value = value;
59 ++list->nEntries;
60}