upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/main/negentropy_adapter.c
diff options
context:
space:
mode:
Diffstat (limited to 'main/negentropy_adapter.c')
-rw-r--r--main/negentropy_adapter.c78
1 files changed, 78 insertions, 0 deletions
diff --git a/main/negentropy_adapter.c b/main/negentropy_adapter.c
new file mode 100644
index 0000000..2939289
--- /dev/null
+++ b/main/negentropy_adapter.c
@@ -0,0 +1,78 @@
1#include "negentropy_adapter.h"
2#include "storage_engine.h"
3#include <stdlib.h>
4#include <string.h>
5#include "esp_log.h"
6
7static const char *TAG = "negentropy_adapter";
8
9struct negentropy_adapter {
10 void *storage;
11 negentropy_item_t *items;
12 size_t count;
13 size_t capacity;
14};
15
16negentropy_adapter_t *negentropy_adapter_from_storage(void *storage_engine)
17{
18 if (!storage_engine) return NULL;
19
20 negentropy_adapter_t *adapter = calloc(1, sizeof(negentropy_adapter_t));
21 if (!adapter) return NULL;
22
23 adapter->storage = storage_engine;
24 adapter->items = NULL;
25 adapter->count = 0;
26 adapter->capacity = 0;
27
28 return adapter;
29}
30
31esp_err_t negentropy_adapter_get_items(negentropy_adapter_t *adapter,
32 negentropy_item_t **items,
33 size_t *count)
34{
35 if (!adapter || !items || !count) return ESP_ERR_INVALID_ARG;
36
37 if (adapter->items) {
38 free(adapter->items);
39 adapter->items = NULL;
40 }
41 adapter->count = 0;
42 adapter->capacity = 0;
43
44 *items = adapter->items;
45 *count = adapter->count;
46
47 ESP_LOGI(TAG, "Adapter has %zu items", adapter->count);
48 return ESP_OK;
49}
50
51esp_err_t negentropy_adapter_insert_item(negentropy_adapter_t *adapter,
52 uint64_t created_at,
53 const uint8_t *id)
54{
55 if (!adapter || !id) return ESP_ERR_INVALID_ARG;
56
57 if (adapter->count >= adapter->capacity) {
58 size_t new_cap = adapter->capacity == 0 ? 64 : adapter->capacity * 2;
59 negentropy_item_t *new_items = realloc(adapter->items, new_cap * sizeof(negentropy_item_t));
60 if (!new_items) return ESP_ERR_NO_MEM;
61 adapter->items = new_items;
62 adapter->capacity = new_cap;
63 }
64
65 negentropy_item_t *item = &adapter->items[adapter->count];
66 item->created_at = created_at;
67 memcpy(item->id, id, 32);
68 adapter->count++;
69
70 return ESP_OK;
71}
72
73void negentropy_adapter_destroy(negentropy_adapter_t *adapter)
74{
75 if (!adapter) return;
76 if (adapter->items) free(adapter->items);
77 free(adapter);
78}