]> git.lizzy.rs Git - dragonstd.git/blob - test/test_tree.c
7267162c60be4dca4357822c6749429fd203afbf
[dragonstd.git] / test / test_tree.c
1 #include <assert.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <time.h>
5 #include "../tree.h"
6
7 #define NUM_ELEMENTS 1e5
8
9 int cmp_int(const void *ia, const void *ib)
10 {
11         return *(const int *) ia - *(const int *) ib;
12 }
13
14 void clear_callback(int *ia, int *ib)
15 {
16         assert(*ia >= *ib);
17         *ib = *ia;
18         free(ia);
19 }
20
21 int main()
22 {
23         srand(time(NULL));
24
25         printf("------------\n");
26         printf("Testing Tree\n");
27         printf("------------\n");
28
29         Tree tree;
30
31         printf("testing ini\n");
32         tree_ini(&tree);
33
34         int a = 0;
35         int b = 1;
36         int c = 2;
37         int d = 2;
38         int e = 3;
39
40         printf("testing add\n");
41         assert(tree_add(&tree, &a, &cmp_int, NULL));
42         assert(tree_add(&tree, &b, &cmp_int, NULL));
43         assert(tree_add(&tree, &c, &cmp_int, NULL));
44         assert(!tree_add(&tree, &d, &cmp_int, NULL));
45
46         printf("testing get\n");
47         assert(tree_get(&tree, &a, &cmp_int, NULL) == &a);
48         assert(tree_get(&tree, &b, &cmp_int, NULL) == &b);
49         assert(tree_get(&tree, &c, &cmp_int, NULL) == &c);
50         assert(tree_get(&tree, &d, &cmp_int, NULL) == &c);
51         assert(tree_get(&tree, &e, &cmp_int, NULL) == NULL);
52
53         printf("testing del\n");
54         assert(tree_del(&tree, &a, &cmp_int, NULL));
55         assert(tree_get(&tree, &a, &cmp_int, NULL) == NULL);
56
57         printf("testing clr\n");
58         tree_clr(&tree, NULL, NULL, NULL, 0);
59         assert(tree_get(&tree, &b, &cmp_int, NULL) == NULL);
60
61         printf("testing order and speed with %d elements\n", (int) NUM_ELEMENTS);
62         for (int i = 0; i < NUM_ELEMENTS; i++) {
63                 int *n = malloc(sizeof *n);
64                 *n = rand();
65
66                 if (!tree_add(&tree, n, &cmp_int, NULL))
67                         free(n);
68         }
69
70         int last = -1;
71         tree_clr(&tree, (void *) &clear_callback, &last, NULL, TRAVERSION_INORDER);
72 }