Import upstream sources.
[cparse] / dict.c
1 #include "cparse.h"
2
3 #define MODULUS 256
4
5 struct node {
6 struct node *next;
7 char *key;
8 void *data;
9 };
10
11 struct dict {
12 struct node *nodes[MODULUS];
13 };
14
15 static unsigned hash(const char *s) {
16 unsigned h = 5381;
17 unsigned char c;
18
19 while((c = *s++))
20 h = 33 * h + c;
21 return h % MODULUS;
22 }
23
24 struct dict *dict_new(void) {
25 return xmalloc(sizeof (struct dict));
26 }
27
28 int dict_add(struct dict *d, const char *key, void *data) {
29 unsigned h = hash(key);
30 struct node *n;
31
32 for(n = d->nodes[h]; n; n = n->next)
33 if(!strcmp(key, n->key))
34 return -1;
35 n = xmalloc(sizeof *n);
36 n->next = d->nodes[h];
37 n->key = xstrdup(key);
38 n->data = data;
39 d->nodes[h] = n;
40 return 0;
41 }
42
43 void *dict_get(struct dict *d, const char *key) {
44 unsigned h = hash(key);
45 struct node *n;
46
47 for(n = d->nodes[h]; n; n = n->next)
48 if(!strcmp(key, n->key))
49 return n->data;
50 return 0;
51 }
52
53 /*
54 Local Variables:
55 c-basic-offset:2
56 comment-column:40
57 End:
58 */