Import upstream sources.
[cparse] / dict.c
CommitLineData
3cd4b0f8
MW
1#include "cparse.h"
2
3#define MODULUS 256
4
5struct node {
6 struct node *next;
7 char *key;
8 void *data;
9};
10
11struct dict {
12 struct node *nodes[MODULUS];
13};
14
15static 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
24struct dict *dict_new(void) {
25 return xmalloc(sizeof (struct dict));
26}
27
28int 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
43void *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/*
54Local Variables:
55c-basic-offset:2
56comment-column:40
57End:
58*/