5 #include "derp/common.h"
6 #include "derp/treemap.h"
12 #define malloc(x) GC_malloc(x)
14 #define realloc(x,y) GC_realloc(x,y)
16 #define free(x) GC_free(x)
19 int ivals[] = {0,1,2,3,4,5,6,7,8,9};
21 int icmp(const void *a, const void *b, void *aux)
24 return *(int*)a - *(int*)b;
31 derp_use_alloc_funcs(GC_malloc, GC_realloc, GC_free);
34 treemap *t = tm_new(derp_strcmp, NULL);
35 assert(tm_length(t) == 0);
36 assert(tm_is_empty(t));
38 assert(!tm_at(t, "zero"));
39 tm_insert(t, "zero", ivals);
40 assert(tm_length(t) == 1);
41 assert(*(int*)tm_at(t, "zero") == 0);
44 tm_insert(t, "zero", ivals+1);
45 assert(tm_length(t) == 1);
46 assert(*(int*)tm_at(t, "zero") == 1);
48 tm_insert(t, "zero", ivals);
49 assert(*(int*)tm_at(t, "zero") == 0);
51 tm_insert(t, "one", ivals+1);
52 assert(tm_length(t) == 2);
53 assert(*(int*)tm_at(t, "zero") == 0);
54 assert(*(int*)tm_at(t, "one") == 1);
55 assert(!tm_at(t, "flurgle"));
58 assert(!tm_at(t, "one"));
61 assert(tm_length(t) == 0);
62 assert(!tm_at(t, "zero"));
64 /* iterator should sort */
65 tm_insert(t, "d", NULL);
66 tm_insert(t, "a", NULL);
67 tm_insert(t, "e", NULL);
68 tm_insert(t, "c", NULL);
69 tm_insert(t, "b", NULL);
71 tm_iter *i = tm_iter_begin(t);
72 assert(*(char*)tm_iter_next(i)->k == 'a');
73 assert(*(char*)tm_iter_next(i)->k == 'b');
74 assert(*(char*)tm_iter_next(i)->k == 'c');
75 assert(*(char*)tm_iter_next(i)->k == 'd');
76 assert(*(char*)tm_iter_next(i)->k == 'e');
77 assert(!tm_iter_next(i));
81 /* test for memory leak */
82 tm_dtor(t, derp_free, derp_free, NULL);
83 char *key = malloc(5),
85 *otherkey = malloc(3);
86 int *val1 = malloc(sizeof *val1),
87 *val2 = malloc(sizeof *val2),
88 *val3 = malloc(sizeof *val3);
90 strcpy(dupkey, "life");
93 tm_insert(t, key, val1);
94 /* will free key, since dupkey is the same */
95 tm_insert(t, dupkey, val2);
96 /* safe to double-insert same key */
97 tm_insert(t, dupkey, val2);
99 /* tm_remove should free as needed */
101 strcpy(otherkey, "hi");
102 tm_insert(t, otherkey, val3);
103 tm_remove(t, otherkey);
107 treemap *t2 = tm_new(icmp, NULL);
108 /* insert in ascending order, inherently unbalanced,
109 * to exercise split/skew */
110 for (size_t i = 0; i < 10; i++)
111 tm_insert(t2, ivals+i, ivals+i);
112 assert(tm_length(t2) == 10);
115 for (size_t i = 0; i < 10; i++)
116 assert(*(int*)tm_at(t2, ivals+i) == (int)i);
118 /* remove odd ones */
119 for (size_t i = 1; i < 10; i+=2)
120 tm_remove(t2, ivals+i);
121 assert(tm_length(t2) == 5);
123 /* evens should still be there */
124 for (size_t i = 0; i < 10; i+=2)
125 assert((int)i == *(int*)tm_at(t2, ivals+i));
128 for (size_t i = 0; i < 10; i+=2)
129 tm_remove(t2, ivals+i);
130 assert(tm_is_empty(t2));