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