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 #include <stdlib.h> 19 #include <string.h> 20 21 #include "utils.h" 22 #include "avl-cmp.h" 23 #include "blob.h" 24 25 #include "kvlist.h" 26 27 int kvlist_strlen(struct kvlist *kv, const void *data) 28 { 29 return strlen(data) + 1; 30 } 31 32 int kvlist_blob_len(struct kvlist *kv, const void *data) 33 { 34 return blob_pad_len(data); 35 } 36 37 void kvlist_init(struct kvlist *kv, int (*get_len)(struct kvlist *kv, const void *data)) 38 { 39 avl_init(&kv->avl, avl_strcmp, false, NULL); 40 kv->get_len = get_len; 41 } 42 43 static struct kvlist_node *__kvlist_get(struct kvlist *kv, const char *name) 44 { 45 struct kvlist_node *node; 46 47 return avl_find_element(&kv->avl, name, node, avl); 48 } 49 50 void *kvlist_get(struct kvlist *kv, const char *name) 51 { 52 struct kvlist_node *node; 53 54 node = __kvlist_get(kv, name); 55 if (!node) 56 return NULL; 57 58 return node->data; 59 } 60 61 bool kvlist_delete(struct kvlist *kv, const char *name) 62 { 63 struct kvlist_node *node; 64 65 node = __kvlist_get(kv, name); 66 if (node) { 67 avl_delete(&kv->avl, &node->avl); 68 free(node); 69 } 70 71 return !!node; 72 } 73 74 bool kvlist_set(struct kvlist *kv, const char *name, const void *data) 75 { 76 struct kvlist_node *node; 77 char *name_buf; 78 int len = kv->get_len(kv, data); 79 80 node = calloc_a(sizeof(struct kvlist_node) + len, 81 &name_buf, strlen(name) + 1); 82 if (!node) 83 return false; 84 85 kvlist_delete(kv, name); 86 87 memcpy(node->data, data, len); 88 89 node->avl.key = strcpy(name_buf, name); 90 avl_insert(&kv->avl, &node->avl); 91 92 return true; 93 } 94 95 void kvlist_free(struct kvlist *kv) 96 { 97 struct kvlist_node *node, *tmp; 98 99 avl_remove_all_elements(&kv->avl, node, avl, tmp) 100 free(node); 101 } 102
This page was automatically generated by LXR 0.3.1. • OpenWrt