all repos — mgba @ e0b05403f4183d4ff3916412fd7341439bdbd6b4

mGBA Game Boy Advance Emulator

Util: Pull basic table struct from another branch
Jeffrey Pfau jeffrey@endrift.com
Sun, 12 Oct 2014 00:44:45 -0700
commit

e0b05403f4183d4ff3916412fd7341439bdbd6b4

parent

bd9fae146631a5fc6514b1c607e1c6ee8f50963f

2 files changed, 79 insertions(+), 0 deletions(-)

jump to
A 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; +}
A 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