lander/lsm/src/store/lsm_store_entry.c

109 lines
2.3 KiB
C
Raw Normal View History

#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include "lsm.h"
#include "lsm/store_internal.h"
lsm_error lsm_entry_init(lsm_entry **ptr) {
lsm_entry *entry = calloc(1, sizeof(lsm_entry));
if (entry == NULL) {
return lsm_error_failed_alloc;
}
*ptr = entry;
return lsm_error_ok;
}
bool lsm_entry_attr_present(lsm_entry *entry, lsm_attr_type type) {
return (entry->attrs.bitmap & type) != 0;
}
lsm_error lsm_entry_attr_get(lsm_str **out, lsm_entry *entry,
lsm_attr_type type) {
if (!lsm_entry_attr_present(entry, type)) {
return lsm_error_not_found;
}
uint64_t i = 0;
while (entry->attrs.items[i].type != type) {
i++;
}
*out = entry->attrs.items[i].str;
return lsm_error_ok;
}
lsm_error lsm_entry_attr_remove(lsm_str **out, lsm_entry *entry,
lsm_attr_type type) {
if (!lsm_entry_attr_present(entry, type)) {
return lsm_error_not_found;
}
if (entry->attrs.count == 1) {
*out = entry->attrs.items[0].str;
free(entry->attrs.items);
entry->attrs.items = NULL;
entry->attrs.count = 0;
entry->attrs.bitmap = 0;
return lsm_error_ok;
}
uint64_t i = 0;
while (entry->attrs.items[i].type != type) {
i++;
}
lsm_attr *new_attrs = malloc((entry->attrs.count - 1) * sizeof(lsm_attr));
if (new_attrs == NULL) {
return lsm_error_failed_alloc;
}
if (out != NULL) {
*out = entry->attrs.items[i].str;
}
memcpy(new_attrs, entry->attrs.items, i * sizeof(lsm_attr));
memcpy(&new_attrs[i], &entry->attrs.items[i + 1],
(entry->attrs.count - i - 1) * sizeof(lsm_attr));
free(entry->attrs.items);
entry->attrs.items = new_attrs;
entry->attrs.count--;
entry->attrs.bitmap &= ~type;
return lsm_error_ok;
}
lsm_error lsm_entry_attr_insert(lsm_entry *entry, lsm_attr_type type,
lsm_str *data) {
if (lsm_entry_attr_present(entry, type)) {
return lsm_error_already_present;
}
lsm_attr *new_attrs =
realloc(entry->attrs.items, (entry->attrs.count + 1) * sizeof(lsm_attr));
if (new_attrs == NULL) {
return lsm_error_failed_alloc;
}
new_attrs[entry->attrs.count].type = type;
new_attrs[entry->attrs.count].str = data;
entry->attrs.items = new_attrs;
entry->attrs.count++;
entry->attrs.bitmap |= type;
return lsm_error_ok;
}