4223
|
1 #include "config.h"
|
|
2 #include "Str.h"
|
|
3 #include "strhash.h"
|
|
4 #include "variable.h"
|
|
5 #include "xmalloc.h"
|
|
6
|
|
7 #include <assert.h>
|
|
8
|
|
9 enum {MAGIC = 23};
|
|
10
|
|
11 static void delcookie(void *c) {
|
|
12 xfree(c);
|
|
13 }
|
|
14
|
|
15 t_vr_container *vr_new(void (*del)(void *)) {
|
|
16 t_vr_container *v = xmalloc(1, sizeof *v);
|
|
17 v->data = xmalloc(v->size = MAGIC, sizeof *v->data);
|
|
18 v->length = 0;
|
|
19 v->del = del;
|
|
20 v->hash = sh_new(delcookie);
|
|
21 return v;
|
|
22 }
|
|
23
|
|
24 void vr_delete(t_vr_container *v) {
|
|
25 assert(v != NULL);
|
|
26 if (v->hash) {
|
|
27 vr_freeze(v);
|
|
28 }
|
|
29 while (v->length) {
|
|
30 --v->length;
|
|
31 if (v->del) {
|
|
32 v->del(v->data[v->length]);
|
|
33 }
|
|
34 }
|
|
35 xfree(v->data);
|
|
36 xfree(v);
|
|
37 }
|
|
38
|
|
39 t_vr_cookie vr_exists(const t_vr_container *v, const char *key, size_t len) {
|
|
40 t_vr_cookie *c;
|
|
41 assert(v->hash != NULL);
|
|
42 return (c = sh_get(v->hash, key, len)) ? *c : VR_NO_COOKIE;
|
|
43 }
|
|
44
|
|
45 t_vr_cookie vr_register(t_vr_container *v, const char *key, size_t len, void *val) {
|
|
46 t_vr_cookie *cookie;
|
|
47
|
|
48 assert(v->hash != NULL);
|
|
49 assert(sh_get(v->hash, key, len) == NULL);
|
|
50
|
|
51 if (v->length >= v->size) {
|
|
52 v->data = xrealloc(v->data, v->size *= 2);
|
|
53 }
|
|
54
|
|
55 cookie = xmalloc(1, sizeof *cookie);
|
|
56 v->data[*cookie = v->length++] = val;
|
|
57 sh_put(v->hash, key, len, cookie);
|
|
58
|
|
59 return *cookie;
|
|
60 }
|
|
61
|
|
62 void vr_freeze(t_vr_container *v) {
|
|
63 assert(v->hash != NULL);
|
|
64 sh_delete(v->hash);
|
|
65 v->hash = NULL;
|
|
66 }
|
|
67
|
|
68 void *(vr_data)(const t_vr_container *v, t_vr_cookie c) {
|
|
69 assert(v->hash == NULL);
|
|
70 assert(c < v->length);
|
|
71 return v->data[c];
|
|
72 }
|