-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_buffer.c
More file actions
50 lines (38 loc) · 818 Bytes
/
string_buffer.c
File metadata and controls
50 lines (38 loc) · 818 Bytes
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
#include "ynicc.h"
struct string_buffer {
char *buf;
int str_len;
int buf_len;
};
static void expand_buffer(string_buffer *sb) {
assert(sb);
sb->buf_len *= 2;
sb->buf = realloc(sb->buf, sb->buf_len);
}
static void ensure_buffer(string_buffer *sb) {
if (sb->str_len >= sb->buf_len) {
expand_buffer(sb);
}
}
string_buffer *sb_init() {
string_buffer *sb = calloc(1, sizeof(string_buffer));
sb->str_len = 0;
sb->buf_len = 16;
sb->buf = calloc(sb->buf_len, sizeof(char));
return sb;
}
void sb_append_char(string_buffer *sb, int ch) {
ensure_buffer(sb);
sb->buf[sb->str_len++] = ch;
}
void sb_free(string_buffer *sb) {
assert(sb);
free(sb->buf);
free(sb);
}
char *sb_str(string_buffer *sb) {
return sb->buf;
}
int sb_str_len(string_buffer *sb) {
return sb->str_len;
}