blob: baa433f4dc80dde61b9fc3c853dd6c680785e306 (
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
|
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include "strings.h"
// new String pointers must be zeroed before being handed to this function
void init_string(struct String *str, size_t initial_capacity)
{
if (str->data) free(str->data);
str->data = malloc(initial_capacity);
if (str->data == NULL) {
perror("malloc() failed");
exit(errno);
}
str->cap = initial_capacity;
str->len = 0;
*(str->data) = 0;
}
void resize_string(struct String *str)
{
str->data = realloc((void*)str->data, str->cap * 2);
if (str->data == NULL) {
perror("realloc() failed");
exit(errno);
}
str->cap = str->cap * 2;
}
void append_str(char *input_str, size_t len, struct String *str)
{
while (str->len + len >= str->cap - 1) {
resize_string(str);
}
strcpy(str->data + str->len, input_str);
str->len += len;
}
void append_char(char c, struct String *str)
{
if (str->len >= str->cap - 1) {
resize_string(str);
}
str->data[str->len] = c;
str->len += 1;
str->data[str->len] = '\0';
}
void delete_char(struct String *str)
{
str->len -= 1;
str->data[str->len] = '\0';
}
|