Util: Pull basic table struct from another branch

This commit is contained in:
Jeffrey Pfau 2014-10-12 00:44:45 -07:00
parent bd9fae1466
commit e0b05403f4
2 changed files with 79 additions and 0 deletions

60
src/util/table.c Normal file
View File

@ -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;
}

19
src/util/table.h Normal file
View File

@ -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