4223
|
1 #include "hash.h"
|
|
2 #include "strhash.h"
|
|
3 #include "strutil.h"
|
|
4 #include "xmalloc.h"
|
|
5
|
|
6 #include <string.h>
|
|
7
|
|
8 struct strx {
|
|
9 char *ptr;
|
|
10 size_t length;
|
|
11 };
|
|
12
|
|
13 struct strx_const {
|
|
14 const char *ptr;
|
|
15 size_t length;
|
|
16 };
|
|
17
|
|
18 struct strhash {
|
|
19 Hash hash;
|
|
20 };
|
|
21
|
|
22 static size_t hash(const void *p, size_t h) {
|
|
23 const struct strx *const s = p;
|
|
24 return u_hash(s->ptr, s->length, h);
|
|
25 }
|
|
26
|
|
27 static int compar(const void *ap, const void *bp) {
|
|
28 const struct strx *const a = ap, *const b = bp;
|
|
29 return u_cmp(a->ptr, a->length, b->ptr, b->length);
|
|
30 }
|
|
31
|
|
32 static void delk(void *p) {
|
|
33 struct strx *const s = p;
|
|
34 xfree(s->ptr);
|
|
35 xfree(s);
|
|
36 }
|
|
37
|
|
38 t_strhash *sh_new(void (*delv)(void *)) {
|
|
39 t_strhash *sh = xmalloc(1, sizeof *sh);
|
|
40 h_init(&sh->hash, hash, compar, delk, delv);
|
|
41 return sh;
|
|
42 }
|
|
43
|
|
44 void sh_delete(t_strhash *sh) {
|
|
45 h_end(&sh->hash);
|
|
46 xfree(sh);
|
|
47 }
|
|
48
|
|
49 void sh_put(t_strhash *sh, const char *key, size_t keylen, void *val) {
|
|
50 struct strx *dup = xmalloc(1, sizeof *dup);
|
|
51 dup->ptr = xmalloc(dup->length = keylen, sizeof *dup->ptr);
|
|
52 memcpy(dup->ptr, key, keylen);
|
|
53 h_put(&sh->hash, dup, val, 1);
|
|
54 }
|
|
55
|
|
56 void *sh_get(t_strhash *sh, const char *key, size_t keylen) {
|
|
57 void *p;
|
|
58 struct strx_const tmp;
|
|
59 tmp.ptr = key;
|
|
60 tmp.length = keylen;
|
|
61 if (h_get(&sh->hash, &tmp, &p) == H_OK) {
|
|
62 return p;
|
|
63 }
|
|
64 return NULL;
|
|
65 }
|