From e0b05403f4183d4ff3916412fd7341439bdbd6b4 Mon Sep 17 00:00:00 2001 From: Jeffrey Pfau Date: Sun, 12 Oct 2014 00:44:45 -0700 Subject: [PATCH] Util: Pull basic table struct from another branch --- src/util/table.c | 60 ++++++++++++++++++++++++++++++++++++++++++++++++ src/util/table.h | 19 +++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 src/util/table.c create mode 100644 src/util/table.h diff --git a/src/util/table.c b/src/util/table.c new file mode 100644 index 000000000..1ce8dfe11 --- /dev/null +++ b/src/util/table.c @@ -0,0 +1,60 @@ +#include "table.h" + +#define LIST_INITIAL_SIZE 8 + +struct TableTuple { + uint32_t key; + void* value; +}; + +struct TableList { + struct TableTuple* list; + size_t nEntries; + size_t listSize; +}; + +void TableInit(struct Table* table, size_t initialSize) { + table->tableSize = initialSize; + table->table = calloc(table->tableSize, sizeof(struct TableList)); + + size_t i; + for (i = 0; i < table->tableSize; ++i) { + table->table[i].listSize = LIST_INITIAL_SIZE; + table->table[i].list = calloc(LIST_INITIAL_SIZE, sizeof(struct TableTuple)); + } +} + +void TableDeinit(struct Table* table) { + size_t i; + for (i = 0; i < table->tableSize; ++i) { + // TODO: Don't leak entries + free(table->table[i].list); + } + free(table->table); + table->table = 0; + table->tableSize = 0; +} + +void* TableLookup(struct Table* table, uint32_t key) { + uint32_t entry = key & (table->tableSize - 1); + struct TableList* list = &table->table[entry]; + size_t i; + for (i = 0; i < list->nEntries; ++i) { + if (list->list[i].key == key) { + return list->list[i].value; + } + } + return 0; +} + +void TableInsert(struct Table* table, uint32_t key, void* value) { + uint32_t entry = key & (table->tableSize - 1); + struct TableList* list = &table->table[entry]; + if (list->nEntries + 1 == list->listSize) { + list->listSize *= 2; + list->list = realloc(list->list, list->listSize * sizeof(struct TableTuple)); + } + list->list[list->nEntries].key = key; + list->list[list->nEntries].value = value; + ++list->nEntries; +} diff --git a/src/util/table.h b/src/util/table.h new file mode 100644 index 000000000..d769efdea --- /dev/null +++ b/src/util/table.h @@ -0,0 +1,19 @@ +#ifndef TABLE_H +#define TABLE_H + +#include "util/common.h" + +struct TableList; + +struct Table { + struct TableList* table; + size_t tableSize; +}; + +void TableInit(struct Table*, size_t initialSize); +void TableDeinit(struct Table*); + +void* TableLookup(struct Table*, uint32_t key); +void TableInsert(struct Table*, uint32_t key, void* value); + +#endif