aboutsummaryrefslogtreecommitdiff
path: root/structures/rope/rope.c
blob: aed104b4d085f5034609792d6b35da16adc6e208 (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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "rope.h"

struct rope_s {
	size_t len;
	char *str;

	struct rope_s *left, *right, *parent;
};


rope* rope_new()
{
	rope *tmp;

	tmp = malloc(sizeof(rope));
	assert(tmp);

	tmp->len = 0;
	tmp->str = NULL;
	tmp->left = NULL;
	tmp->right = NULL;
	tmp->parent = NULL;

	return tmp;
}

void rope_debug_print_aux(root, s)
rope *root;
int s;
{
	int i;

	for (i = 0; i < s; i++)
		printf("|    ");

	if (!root) {
		printf("\n");
		return;
	}

#ifdef ROPE_DEBUG_PARENT
	printf("[%p]\n", root->parent);
#endif

	printf("{len:%d,str:\'%s\'}[%p]\n", root->len, root->str, root);

	if (root->str)
		return;

	rope_debug_print_aux(root->left, ++s);
	rope_debug_print_aux(root->right, s);

}

void rope_debug_print(root)
rope *root;
{
	rope_debug_print_aux(root, 0);
}

void rope_print(root)
rope *root;
{
	if (!root)
		return;

	if (root->str)
		printf("%s", root->str);

	rope_print(root->left);
	rope_print(root->right);
}

size_t rope_len(root)
rope *root;
{
	if (!root)
		return 0;

	if (root->str)
		return strlen(root->str);

	return rope_len(root->left) + rope_len(root->right);
}

rope* str_to_rope(str)
char *str;
{
	rope *tmp;

	if (!str)
		return NULL;

	tmp = rope_new();
	tmp->len = strlen(str);
	tmp->str = strdup(str);

	return tmp;
}

rope* rope_concat(node1, node2)
rope *node1, *node2;
{
	rope *tmp;

	if (!node1 || !node2)
		return node1 ? node1 : node2;

	tmp = rope_new();
	tmp->len = rope_len(node1);
	tmp->left = node1;
	tmp->right = node2;
	node1->parent = tmp;
	node2->parent = tmp;

	return tmp;
}