-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathtext.c
133 lines (116 loc) · 2.61 KB
/
text.c
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
122
123
124
125
126
127
128
129
130
131
132
133
/**
* @file text.c
* @author hutusi (hutusi@outlook.com)
* @brief Refer to text.h
* @date 2019-08-15
*
* @copyright Copyright (c) 2019, hutusi.com
*
*/
#include "text.h"
#include "def.h"
#include <stdlib.h>
#include <string.h>
/**
* @brief All ways append '\0' to text, for dapat c string.
*
*/
/**
* @brief Definition of a @ref Text.
*
*/
struct _Text {
char *data;
unsigned int length;
unsigned int _allocated;
};
static inline Text *text_new_with_size(unsigned int size)
{
Text *text = (Text *)malloc(sizeof(Text));
text->_allocated = size;
text->length = 0;
text->data = (char *)malloc(text->_allocated * sizeof(char));
return text;
}
Text *text_new()
{
return text_new_with_size(16); /** initial default. */
}
Text *text_from(const char *string)
{
size_t len = strlen(string);
Text *text = text_new_with_size(len + 1);
strcpy(text->data, string);
text->length = len;
return text;
}
Text *text_n_from(const char *string, int length)
{
Text *text = text_new_with_size(length + 1);
strncpy(text->data, string, length);
text->data[length] = '\0';
text->length = length;
return text;
}
void text_free(Text *text)
{
free(text->data);
free(text);
}
Text *text_clone(const Text *text)
{
Text *clone = text_new_with_size(text->_allocated);
strncpy(clone->data, text->data, text->length + 1);
clone->length = text->length;
return clone;
}
const char *text_char_string(const Text *text)
{
return text->data;
}
unsigned int text_length(const Text *text)
{
return text->length;
}
char text_char_at(const Text *text, unsigned int index)
{
if (index >= text->length) {
return CHAR_NIL;
} else {
return text->data[index];
}
}
int text_compare(const Text *text1, const Text *text2)
{
for (unsigned int i = 0; i < text1->length; ++i) {
if (text1->data[i] > text2->data[i]) {
return 1;
} else if (text1->data[i] < text2->data[i]) {
return -1;
} else {
continue;
}
}
if (text1->length > text2->length) {
return 1;
} else if (text1->length < text2->length) {
return -1;
} else {
return 0;
}
}
int text_equal(const Text *text1, const Text *text2)
{
return text_compare(text1, text2) == 0;
}
Text *text_append(Text *text, char ch)
{
if ((text->length + 1) >= text->_allocated) {
text->_allocated += 16;
text->data = (char *)realloc(text->data, text->_allocated);
}
text->data[text->length] = ch;
++(text->length);
text->data[text->length] = '\0';
return text;
}