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 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "str.h"
enum
{
MIN_CAPACITY = 4, // required to be greater than zero
};
void
makeEmptyStr(struct Str *str)
{
str->capacity = MIN_CAPACITY;
str->cstr = str->end = malloc(str->capacity);
if (!str->cstr) {
fprintf(stderr, "in appendToStr: out of memory.\n");
abort();
}
*str->cstr = 0;
}
void
destroyStr(struct Str *str)
{
str->capacity = 0;
free(str->cstr);
str->cstr = str->end = 0;
}
void
clearStr(struct Str *str)
{
if (!str->capacity) {
makeEmptyStr(str);
} else {
str->end = str->cstr;
*str->cstr = 0;
}
}
void
appendCharToStr(struct Str *str, char c)
{
size_t len = str->end - str->cstr; // length without terminating 0
if (len + 2 > str->capacity) {
str->capacity = len + 2;
if (str->capacity < MIN_CAPACITY) {
str->capacity = MIN_CAPACITY;
} else {
str->capacity *= 2;
}
str->cstr = realloc(str->cstr, str->capacity);
if (!str->cstr) {
fprintf(stderr, "in appendToStr: out of memory.\n");
abort();
}
str->end = str->cstr + len;
}
*str->end++ = c;
*str->end = 0;
}
void
appendStrToStr(struct Str *str, struct Str *append)
{
// lengths of 'str' and 'append' without terminating 0
size_t len0 = str->end - str->cstr;
size_t len1 = append->end - append->cstr;
if (len0 + len1 + 1 > str->capacity) {
str->capacity = len0 + len1 + 1;
if (str->capacity < MIN_CAPACITY) {
str->capacity = MIN_CAPACITY;
} else {
str->capacity *= 2;
}
str->cstr = realloc(str->cstr, str->capacity);
if (!str->cstr) {
fprintf(stderr, "in appendToStr: out of memory.\n");
abort();
}
str->end = str->cstr + len0;
}
strcpy(str->end, append->cstr);
str->end += len1;
}
void
copyCStrToStr(struct Str *str, const char *cstr)
{
size_t len = strlen(cstr);
if (len + 1 > str->capacity) {
str->capacity = len + 1;
str->cstr = realloc(str->cstr, str->capacity);
if (!str->cstr) {
fprintf(stderr, "in copyToStr: out of memory.\n");
abort();
}
}
strcpy(str->cstr, cstr);
str->end = str->cstr + len;
}
void
appendCStrToStr(struct Str *str, const char *cstr)
{
// lengths of 'str' and 'append' without terminating 0
size_t len0 = str->end - str->cstr;
size_t len1 = strlen(cstr);
if (len0 + len1 + 1 > str->capacity) {
str->capacity = len0 + len1 + 1;
if (str->capacity < MIN_CAPACITY) {
str->capacity = MIN_CAPACITY;
} else {
str->capacity *= 2;
}
str->cstr = realloc(str->cstr, str->capacity);
if (!str->cstr) {
fprintf(stderr, "in appendToStr: out of memory.\n");
abort();
}
str->end = str->cstr + len0;
}
strcpy(str->end, cstr);
str->end += len1;
}
|