Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include "compat.h"
19 #include <stdlib.h>
21 #include "kamid.h"
22 #include "utils.h"
24 static void *hash_alloc(size_t, void *);
25 static void *hash_calloc(size_t, size_t, void *);
26 static void hash_free(void *, void *);
28 static int table_static_open(struct table *);
29 static int table_static_add(struct table *, const char *, const char *);
30 static int table_static_lookup(struct table *, const char *, char **);
31 static void table_static_close(struct table *);
33 struct table_backend table_static = {
34 "static",
35 table_static_open,
36 table_static_add,
37 table_static_lookup,
38 table_static_close,
39 };
41 struct kp {
42 char *key;
43 char *val;
44 };
46 static void *
47 hash_alloc(size_t len, void *d)
48 {
49 return xmalloc(len);
50 }
52 static void *
53 hash_calloc(size_t nmemb, size_t size, void *d)
54 {
55 return xcalloc(nmemb, size);
56 }
58 static void
59 hash_free(void *ptr, void *d)
60 {
61 free(ptr);
62 }
64 static int
65 table_static_open(struct table *t)
66 {
67 struct ohash_info info = {
68 .key_offset = offsetof(struct kp, key),
69 .calloc = hash_calloc,
70 .free = hash_free,
71 .alloc = hash_alloc,
72 };
74 t->t_handle = xmalloc(sizeof(struct ohash));
75 ohash_init(t->t_handle, 5, &info);
76 return 0;
77 }
79 int
80 table_static_add(struct table *t, const char *key, const char *val)
81 {
82 struct kp *kp;
83 unsigned int slot;
85 kp = xcalloc(1, sizeof(*kp));
86 kp->key = xstrdup(key);
87 if (val != NULL)
88 kp->val = xstrdup(val);
90 slot = ohash_qlookup(t->t_handle, kp->key);
91 ohash_insert(t->t_handle, slot, kp);
93 return 0;
94 }
96 int
97 table_static_lookup(struct table *t, const char *key, char **ret_val)
98 {
99 struct kp *kp;
100 unsigned int slot;
102 slot = ohash_qlookup(t->t_handle, key);
103 if ((kp = ohash_find(t->t_handle, slot)) == NULL)
104 return -1;
106 *ret_val = xstrdup(kp->val);
107 return 0;
110 static void
111 table_static_close(struct table *t)
113 struct kp *kp;
114 unsigned int i;
116 for (kp = ohash_first(t->t_handle, &i);
117 kp != NULL;
118 kp = ohash_next(t->t_handle, &i)) {
119 ohash_remove(t->t_handle, i);
120 free(kp->key);
121 free(kp->val);
122 free(kp);
125 free(t->t_handle);