]> begriffs open source - libderp/blob - test/t_hashmap.c
Adequate hashmap test coverage
[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         assert(hm_length(h) == 0);
37         assert(hm_is_empty(h));
38
39         assert(!hm_at(h, "zero"));
40         hm_insert(h, "zero", ivals);
41         assert(hm_length(h) == 1);
42         assert(*(int*)hm_at(h, "zero") == 0);
43
44         /* change it */
45         hm_insert(h, "zero", ivals+1);
46         assert(hm_length(h) == 1);
47         assert(*(int*)hm_at(h, "zero") == 1);
48         /* set it back */
49         hm_insert(h, "zero", ivals);
50         assert(*(int*)hm_at(h, "zero") == 0);
51
52         hm_insert(h, "one", ivals+1);
53         assert(hm_length(h) == 2);
54         assert(*(int*)hm_at(h, "zero") == 0);
55         assert(*(int*)hm_at(h, "one") == 1);
56         assert(!hm_at(h, "flurgle"));
57
58         hm_remove(h, "one");
59         assert(!hm_at(h, "one"));
60
61         hm_clear(h);
62         assert(hm_length(h) == 0);
63         assert(!hm_at(h, "zero"));
64
65         /* test for memory leak */
66         hm_dtor(h, myfree, myfree, NULL);
67         char *key = malloc(5);
68         int  *val1 = malloc(sizeof *val1),
69              *val2 = malloc(sizeof *val2);
70         strcpy(key, "life");
71         *val1 = 42;
72         *val2 = 13;
73         hm_insert(h, key, val1);
74         hm_insert(h, key, val2);
75
76         hm_free(h);
77
78         return 0;
79 }