aboutsummaryrefslogtreecommitdiff
path: root/composed.c
blob: f969c8f123a1f1c3e958f45f1b33e3ced3e87539 (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include "composed.h"

#include <stdlib.h>
#include <stdbool.h>

#include "debug.h"

struct composed *
composed_lookup(struct composed *root, uint32_t key)
{
    struct composed *node = root;

    while (node != NULL) {
        if (key == node->key)
            return node;

        node = key < node->key ? node->left : node->right;
    }

    return NULL;
}

uint32_t
composed_insert(struct composed **root, struct composed *node)
{
    node->left = node->right = NULL;

    if (*root == NULL) {
        *root = node;
        return node->key;
    }

    uint32_t key = node->key;

    struct composed *prev = NULL;
    struct composed *n = *root;

    while (n != NULL) {
        if (n->key == node->key) {
            /* TODO: wrap around at (CELL_COMB_CHARS_HI - CELL_COMB_CHARS_LO) */
            key++;
        }

        prev = n;
        n = key < n->key ? n->left : n->right;
    }

    xassert(prev != NULL);
    xassert(n == NULL);

    /* May have been changed */
    node->key = key;

    if (key < prev->key) {
        xassert(prev->left == NULL);
        prev->left = node;
    } else {
        xassert(prev->right == NULL);
        prev->right = node;
    }

    return key;
}

void
composed_free(struct composed *root)
{
    if (root == NULL)
        return;

    composed_free(root->left);
    composed_free(root->right);

    free(root->chars);
    free(root);
}