libubox: Plug a small memory leak.
[project/libubox.git] / kvlist.h
1 /*
2  * kvlist - simple key/value store
3  *
4  * Copyright (C) 2014 Felix Fietkau <nbd@openwrt.org>
5  *
6  * Permission to use, copy, modify, and/or distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 #ifndef __LIBUBOX_KVLIST_H
19 #define __LIBUBOX_KVLIST_H
20
21 #include "avl-cmp.h"
22 #include "avl.h"
23
24 struct kvlist {
25         struct avl_tree avl;
26
27         int (*get_len)(struct kvlist *kv, const void *data);
28 };
29
30 struct kvlist_node {
31         struct avl_node avl;
32
33         char data[0] __attribute__((aligned(4)));
34 };
35
36 #define KVLIST_INIT(_name, _get_len)                                            \
37         {                                                                       \
38                 .avl = AVL_TREE_INIT(_name.avl, avl_strcmp, false, NULL),       \
39                 .get_len = _get_len                                             \
40         }
41
42 #define KVLIST(_name, _get_len)                                                 \
43         struct kvlist _name = KVLIST_INIT(_name, _get_len)
44
45 #define __ptr_to_kv(_ptr) container_of(((char *) (_ptr)), struct kvlist_node, data[0])
46 #define __avl_list_to_kv(_l) container_of(_l, struct kvlist_node, avl.list)
47
48 #define kvlist_for_each(kv, name, value) \
49         for (value = (void *) __avl_list_to_kv((kv)->avl.list_head.next)->data,                 \
50              name = (const char *) __ptr_to_kv(value)->avl.key, (void) name;                    \
51              &__ptr_to_kv(value)->avl.list != &(kv)->avl.list_head;                             \
52              value = (void *) (__avl_list_to_kv(__ptr_to_kv(value)->avl.list.next))->data,      \
53              name = (const char *) __ptr_to_kv(value)->avl.key)
54
55 void kvlist_init(struct kvlist *kv, int (*get_len)(struct kvlist *kv, const void *data));
56 void kvlist_free(struct kvlist *kv);
57 void *kvlist_get(struct kvlist *kv, const char *name);
58 bool kvlist_set(struct kvlist *kv, const char *name, const void *data);
59 bool kvlist_delete(struct kvlist *kv, const char *name);
60
61 int kvlist_strlen(struct kvlist *kv, const void *data);
62 int kvlist_blob_len(struct kvlist *kv, const void *data);
63
64 #endif