aboutsummaryrefslogtreecommitdiff
path: root/test/tree.c
blob: aef4061b0bc56aec3e6e730eb3483c90c4727cad (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

#include "kpl_test.h"

typedef struct _c_string_test_node {
    KPL_TREE_HEADER(_c_string_test_node);
    const char *c_string;
} c_string_test_node;

static int32_t c_string_test_compare(const void *node_a, const void *node_b) {
    const c_string_test_node *a = node_a, *b = node_b;
    return strcmp(a->c_string, b->c_string);
}

KPL_TEST(c_string_trees) {
    const char *c_strings[] = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", NULL };
    const int32_t c_string_counter[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
    kpl_tree c_string_tree = {};
    kpl_tree_init(&c_string_tree, c_string_test_compare, free);
    const char **c_strings_iterator = c_strings;
    const int32_t *c_string_counter_iterator = c_string_counter;
    while (*c_strings_iterator && *c_string_counter_iterator) {
        for (int32_t inserts = 0; inserts < *c_string_counter_iterator; inserts++) {
            c_string_test_node *node = calloc(1, sizeof(c_string_test_node));
            node->c_string = *c_strings_iterator;
            kpl_tree_insert(&c_string_tree, node);
        }
        c_strings_iterator++;
        c_string_counter_iterator++;
    }
    c_strings_iterator = c_strings;
    c_string_counter_iterator = c_string_counter;
    c_string_test_node find = {}, *found;
    while (*c_strings_iterator && *c_string_counter_iterator) {
        int32_t count = *c_string_counter_iterator;
        find.c_string = *c_strings_iterator;
        KPL_ASSERT(found = kpl_tree_find(&c_string_tree, &find), "c string node not found");
        while (count) {
            KPL_ASSERT(strcmp(found->c_string, *c_strings_iterator) == 0, "c string does not match");
            found = found->tree_duplicates;
            count--;
        }
        KPL_ASSERT(!found, "found pointer should be null on last duplicate");
        c_strings_iterator++;
        c_string_counter_iterator++;
    }
    kpl_tree_free(&c_string_tree);
}