summaryrefslogtreecommitdiff
path: root/source/fitz/tree.c
blob: bdd042dcb81479a7047898cf417993097154fd44 (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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include "mupdf/fitz.h"

#include <string.h>

/* AA-tree */

struct fz_tree_s
{
	char *key;
	void *value;
	fz_tree *left, *right;
	int level;
};

static fz_tree tree_sentinel = { "", NULL, &tree_sentinel, &tree_sentinel, 0 };

static fz_tree *fz_tree_new_node(fz_context *ctx, const char *key, void *value)
{
	fz_tree *node = fz_malloc_struct(ctx, fz_tree);
	node->key = fz_strdup(ctx, key);
	node->value = value;
	node->left = node->right = &tree_sentinel;
	node->level = 1;
	return node;
}

void *fz_tree_lookup(fz_context *ctx, fz_tree *node, const char *key)
{
	if (node)
	{
		while (node != &tree_sentinel)
		{
			int c = strcmp(key, node->key);
			if (c == 0)
				return node->value;
			else if (c < 0)
				node = node->left;
			else
				node = node->right;
		}
	}
	return NULL;
}

static fz_tree *fz_tree_skew(fz_tree *node)
{
	if (node->level != 0)
	{
		if (node->left->level == node->level)
		{
			fz_tree *save = node;
			node = node->left;
			save->left = node->right;
			node->right = save;
		}
		node->right = fz_tree_skew(node->right);
	}
	return node;
}

static fz_tree *fz_tree_split(fz_tree *node)
{
	if (node->level != 0 && node->right->right->level == node->level)
	{
		fz_tree *save = node;
		node = node->right;
		save->right = node->left;
		node->left = save;
		node->level++;
		node->right = fz_tree_split(node->right);
	}
	return node;
}

fz_tree *fz_tree_insert(fz_context *ctx, fz_tree *node, const char *key, void *value)
{
	if (node && node != &tree_sentinel)
	{
		int c = strcmp(key, node->key);
		if (c < 0)
			node->left = fz_tree_insert(ctx, node->left, key, value);
		else
			node->right = fz_tree_insert(ctx, node->right, key, value);
		node = fz_tree_skew(node);
		node = fz_tree_split(node);
		return node;
	}
	else
	{
		return fz_tree_new_node(ctx, key, value);
	}
}

void fz_drop_tree(fz_context *ctx, fz_tree *node, void (*dropfunc)(fz_context *ctx, void *value))
{
	if (node)
	{
		if (node->left != &tree_sentinel)
			fz_drop_tree(ctx, node->left, dropfunc);
		if (node->right != &tree_sentinel)
			fz_drop_tree(ctx, node->right, dropfunc);
		fz_free(ctx, node->key);
		if (dropfunc)
			dropfunc(ctx, node->value);
		fz_free(ctx, node);
	}
}