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