-
Notifications
You must be signed in to change notification settings - Fork 255
/
string_builder.c
74 lines (64 loc) · 1.3 KB
/
string_builder.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "string_builder.h"
void *
StringBuilder_malloc(size_t size)
{
void *p = malloc(size);
if (p == NULL) {
fprintf(stderr, "StringBuilder: OUT OF MEMORY\n");
exit(EXIT_FAILURE);
}
return p;
}
StringBuilder *
StringBuilder_new(void)
{
StringBuilder *sb = StringBuilder_malloc(sizeof(StringBuilder));
sb->size = 1;
sb->cap = INITIAL_CAPACITY;
char *s = StringBuilder_malloc(sizeof(char) * INITIAL_CAPACITY);
s[0] = '\0';
sb->s = s;
return sb;
}
void
StringBuilder_free(StringBuilder *sb)
{
free(sb->s);
free(sb);
}
void
StringBuilder_resize(StringBuilder *sb, size_t capacity)
{
char *s = StringBuilder_malloc(sizeof(char) * capacity);
strncpy(s, sb->s, sb->size);
free(sb->s);
sb->s = s;
sb->cap = capacity;
}
char *
StringBuilder_str(StringBuilder *sb)
{
return sb->s;
}
void
StringBuilder_write_char(StringBuilder *sb, char c)
{
size_t size = sb->size;
if (size >= sb->cap) {
StringBuilder_resize(sb, sb->cap * 2);
}
sb->s[size - 1] = c;
sb->s[size - 0] = '\0';
sb->size++;
}
void
StringBuilder_write(StringBuilder *sb, const char *s)
{
int i;
for (i = 0; s[i] != '\0'; i++) {
StringBuilder_write_char(sb, s[i]);
}
}