index.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include "index.h"
  2. struct IndexEntry {
  3. LSUP_Key key;
  4. LSUP_SerTerm *val;
  5. };
  6. struct Index {
  7. size_t free_i;
  8. size_t capacity;
  9. struct IndexEntry *entries;
  10. };
  11. LSUP_Index *LSUP_index_new(size_t capacity)
  12. {
  13. LSUP_Index *idx = malloc(sizeof(struct Index));
  14. if (capacity == 0) return NULL;
  15. CRITICAL (idx->entries = malloc(sizeof(struct IndexEntry) * capacity));
  16. idx->free_i = 0;
  17. idx->capacity = capacity;
  18. return idx;
  19. }
  20. void LSUP_index_resize(LSUP_Index *idx, size_t capacity)
  21. {
  22. CRITICAL (idx->entries = (struct IndexEntry*)realloc(
  23. idx->entries,
  24. sizeof(struct IndexEntry) * capacity));
  25. idx->capacity = capacity;
  26. }
  27. int LSUP_index_add(LSUP_Index *idx, LSUP_SerTerm *sterm)
  28. {
  29. LSUP_Key key = LSUP_sterm_to_key(sterm);
  30. return LSUP_index_add_pair(idx, key, sterm);
  31. }
  32. int LSUP_index_add_pair(LSUP_Index *idx, LSUP_Key key, LSUP_SerTerm *sterm)
  33. {
  34. // Fail quietly if key exists already.
  35. if (LSUP_index_lookup(idx, key) == NULL) {
  36. if (idx->free_i >= idx->capacity) {
  37. LSUP_index_resize(idx, idx->capacity * 1.5);
  38. TRACE("Capacity now at %lu\n", idx->capacity);
  39. }
  40. struct IndexEntry *entry = idx->entries + idx->free_i;
  41. entry->key = key;
  42. entry->val = LSUP_buffer_new(sterm->size);
  43. memcpy(entry->val->addr, sterm->addr, sterm->size);
  44. idx->free_i ++;
  45. TRACE("Size now at %lu\n", idx->free_i);
  46. }
  47. return 0;
  48. }
  49. LSUP_SerTerm *LSUP_index_lookup(LSUP_Index *idx, LSUP_Key key)
  50. {
  51. LSUP_SerTerm *match = NULL;
  52. for (size_t i = 0; i < idx->free_i; i++) {
  53. if (idx->entries[i].key == key) {
  54. match = idx->entries[i].val;
  55. break;
  56. }
  57. }
  58. return match;
  59. }
  60. void LSUP_index_free(LSUP_Index *idx)
  61. {
  62. for (size_t i = 0; i < idx->free_i; i++) {
  63. LSUP_buffer_done(idx->entries[i].val);
  64. }
  65. free(idx->entries);
  66. free(idx);
  67. }