]> begriffs open source - libderp/blob - test/t_hashmap.c
WIP: treemap
[libderp] / test / t_hashmap.c
1 #include "hashmap.h"
2
3 #include <assert.h>
4 #include <stdlib.h>
5 #include <string.h>
6
7 int ivals[] = {0,1,2,3,4,5,6,7,8,9};
8
9 unsigned long djb2hash(const void *x)
10 {
11         const char *str = x;
12         unsigned long hash = 5381;
13         int c;
14
15         if (str)
16                 while ( (c = *str++) )
17                         hash = hash * 33 + c;
18         return hash;
19 }
20
21 int scmp(const void *a, const void *b, void *aux)
22 {
23         (void)aux;
24         return strcmp(a, b);
25 }
26
27 void myfree(void *a, void *aux)
28 {
29         (void)aux;
30         free(a);
31 }
32
33 int main(void)
34 {
35         hashmap *h = hm_new(0, djb2hash, scmp, NULL);
36         hm_iter i;
37         assert(hm_length(h) == 0);
38         assert(hm_is_empty(h));
39         hm_iter_begin(h, &i);
40         assert(!hm_iter_next(&i));
41
42         assert(!hm_at(h, "zero"));
43         hm_insert(h, "zero", ivals);
44         assert(hm_length(h) == 1);
45         assert(*(int*)hm_at(h, "zero") == 0);
46
47         /* change it */
48         hm_insert(h, "zero", ivals+1);
49         assert(hm_length(h) == 1);
50         assert(*(int*)hm_at(h, "zero") == 1);
51         /* set it back */
52         hm_insert(h, "zero", ivals);
53         assert(*(int*)hm_at(h, "zero") == 0);
54
55         hm_insert(h, "one", ivals+1);
56         assert(hm_length(h) == 2);
57         assert(*(int*)hm_at(h, "zero") == 0);
58         assert(*(int*)hm_at(h, "one") == 1);
59         assert(!hm_at(h, "flurgle"));
60
61         struct map_pair *p;
62         int n_keys = 0;
63         for (hm_iter_begin(h, &i); (p = hm_iter_next(&i)); n_keys++)
64                 assert(strcmp((char*)p->k, "zero") == 0 ||
65                        strcmp((char*)p->k, "one") == 0);
66         assert(n_keys == 2);
67
68         hm_remove(h, "one");
69         assert(!hm_at(h, "one"));
70
71         hm_clear(h);
72         assert(hm_length(h) == 0);
73         assert(!hm_at(h, "zero"));
74
75         /* test for memory leak */
76         hm_dtor(h, myfree, myfree, NULL);
77         char *key = malloc(5);
78         int  *val1 = malloc(sizeof *val1),
79              *val2 = malloc(sizeof *val2);
80         strcpy(key, "life");
81         *val1 = 42;
82         *val2 = 13;
83         hm_insert(h, key, val1);
84         hm_insert(h, key, val2);
85
86         hm_free(h);
87
88         return 0;
89 }