Paparazzi UAS v7.0_unstable
Paparazzi is a free software Unmanned Aircraft System.
Loading...
Searching...
No Matches
kv_store.c
Go to the documentation of this file.
1/*
2 * General purpose key-value store.
3 * Copyright (C) 2026 Fabien-B <fabien-b@github.com>
4 * This file is part of paparazzi. See LICENCE file.
5 */
6
7#include "kv_store.h"
8#include "string.h"
9
20void kv_init(kv_store_t *kv, size_t capacity, size_t esize,
21 uint32_t *keys, void *values, uint8_t *used) {
22
23 kv->capacity = capacity;
24 kv->esize = esize;
25 kv->keys = keys;
26 kv->values = (uint8_t *)values;
27 kv->used = used;
28
29 for (size_t i = 0; i < capacity; i++) {
30 kv->used[i] = 0;
31 }
32}
33
42static int kv_find(const kv_store_t *kv, uint32_t key, size_t *index) {
43 for (size_t i = 0; i < kv->capacity; i++)
44 {
45 if (kv->used[i] && kv->keys[i] == key)
46 {
47 if (index)
48 {
49 *index = i;
50 }
51 return 1; // found
52 }
53 }
54 return 0; // not found
55}
56
64int kv_exists(const kv_store_t *kv, uint32_t key) {
65 return kv_find(kv, key, NULL);
66}
67
79int kv_set(kv_store_t *kv, uint32_t key, const void *value) {
80 size_t index;
81
82 // Update existing
83 if (kv_find(kv, key, &index))
84 {
85 memcpy(&kv->values[index * kv->esize], value, kv->esize);
86 return 0;
87 }
88
89 // Insert new
90 for (size_t i = 0; i < kv->capacity; i++)
91 {
92 if (!kv->used[i])
93 {
94 kv->used[i] = 1;
95 kv->keys[i] = key;
96 memcpy(&kv->values[i * kv->esize], value, kv->esize);
97 return 0;
98 }
99 }
100
101 return -1; // store full
102}
103
111void* kv_get(const kv_store_t *kv, uint32_t key) {
112 size_t index;
113
114 if (!kv_find(kv, key, &index))
115 return NULL;
116
117 return &kv->values[index * kv->esize];
118}
119
128 size_t index;
129
130 if (!kv_find(kv, key, &index))
131 return -1;
132
133 kv->used[index] = 0;
134 return 0;
135}
int kv_set(kv_store_t *kv, uint32_t key, const void *value)
Sets a value for a given key.
Definition kv_store.c:79
void * kv_get(const kv_store_t *kv, uint32_t key)
Retrieves the value associated with a given key.
Definition kv_store.c:111
static int kv_find(const kv_store_t *kv, uint32_t key, size_t *index)
Finds the index of a given key in the store.
Definition kv_store.c:42
void kv_init(kv_store_t *kv, size_t capacity, size_t esize, uint32_t *keys, void *values, uint8_t *used)
Initializes a key-value store.
Definition kv_store.c:20
int kv_exists(const kv_store_t *kv, uint32_t key)
Checks if a key exists in the store.
Definition kv_store.c:64
int kv_remove(kv_store_t *kv, uint32_t key)
Removes a key-value pair from the store.
Definition kv_store.c:127
uint16_t foo
Definition main_demo5.c:58
float kv
unsigned int uint32_t
Typedef defining 32 bit unsigned int type.
unsigned char uint8_t
Typedef defining 8 bit unsigned char type.