add blobmsg list helpers
[project/procd.git] / utils.c
1 #include <libubox/avl.h>
2 #include <libubox/avl-cmp.h>
3 #include "utils.h"
4
5 void
6 __blobmsg_list_init(struct blobmsg_list *list, int offset, int len)
7 {
8 avl_init(&list->avl, avl_strcmp, false, NULL);
9 list->node_offset = offset;
10 list->node_len = len;
11 }
12
13 int
14 blobmsg_list_fill(struct blobmsg_list *list, void *data, int len)
15 {
16 struct avl_tree *tree = &list->avl;
17 struct blobmsg_list_node *node;
18 struct blob_attr *cur;
19 void *ptr;
20 int count = 0;
21 int rem = len;
22
23 __blob_for_each_attr(cur, data, rem) {
24 if (!blobmsg_check_attr(cur, true))
25 continue;
26
27 ptr = calloc(1, list->node_len);
28 if (!ptr)
29 return -1;
30
31 node = (void *) ((char *)ptr + list->node_offset);
32 node->avl.key = blobmsg_name(cur);
33 node->data = cur;
34 if (avl_insert(tree, &node->avl)) {
35 free(ptr);
36 continue;
37 }
38
39 count++;
40 }
41
42 return count;
43 }
44
45 void
46 blobmsg_list_free(struct blobmsg_list *list)
47 {
48 struct blobmsg_list_node *node, *tmp;
49 void *ptr;
50
51 avl_remove_all_elements(&list->avl, node, avl, tmp) {
52 ptr = ((char *) node - list->node_offset);
53 free(ptr);
54 }
55 }