12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394 |
- #include "index.h"
- struct IndexEntry {
- LSUP_Key key;
- LSUP_SerTerm *val;
- };
- struct Index {
- size_t free_i;
- size_t capacity;
- struct IndexEntry *entries;
- };
- LSUP_Index *LSUP_index_new(size_t capacity)
- {
- LSUP_Index *idx = malloc(sizeof(struct Index));
- if (capacity == 0) return NULL;
- CRITICAL (idx->entries = malloc(sizeof(struct IndexEntry) * capacity));
- idx->free_i = 0;
- idx->capacity = capacity;
- return idx;
- }
- void LSUP_index_resize(LSUP_Index *idx, size_t capacity)
- {
- CRITICAL (idx->entries = (struct IndexEntry*)realloc(
- idx->entries,
- sizeof(struct IndexEntry) * capacity));
- idx->capacity = capacity;
- }
- int LSUP_index_add(LSUP_Index *idx, LSUP_SerTerm *sterm)
- {
- LSUP_Key key = LSUP_sterm_to_key(sterm);
- return LSUP_index_add_pair(idx, key, sterm);
- }
- int LSUP_index_add_pair(LSUP_Index *idx, LSUP_Key key, LSUP_SerTerm *sterm)
- {
- // Fail quietly if key exists already.
- if (LSUP_index_lookup(idx, key) == NULL) {
- if (idx->free_i >= idx->capacity) {
- LSUP_index_resize(idx, idx->capacity * 1.5);
- TRACE("Capacity now at %lu\n", idx->capacity);
- }
- struct IndexEntry *entry = idx->entries + idx->free_i;
- entry->key = key;
- entry->val = LSUP_buffer_new(sterm->size);
- memcpy(entry->val->addr, sterm->addr, sterm->size);
- idx->free_i ++;
- TRACE("Size now at %lu\n", idx->free_i);
- }
- return 0;
- }
- LSUP_SerTerm *LSUP_index_lookup(LSUP_Index *idx, LSUP_Key key)
- {
- LSUP_SerTerm *match = NULL;
- for (size_t i = 0; i < idx->free_i; i++) {
- if (idx->entries[i].key == key) {
- match = idx->entries[i].val;
- break;
- }
- }
- return match;
- }
- void LSUP_index_free(LSUP_Index *idx)
- {
- for (size_t i = 0; i < idx->free_i; i++) {
- LSUP_buffer_done(idx->entries[i].val);
- }
- free(idx->entries);
- free(idx);
- }
|