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 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32
33 #include <cx/string.h>
34
35 #include "strbuf.h"
36
37
38 sbuf_t* sbuf_new(
size_t size) {
39 sbuf_t *buf = malloc(
sizeof(
sbuf_t));
40
41 buf->ptr = malloc(size);
42 buf->ptr[
0] =
0;
43 buf->size = size;
44 buf->length =
0;
45
46 return buf;
47 }
48
49 void sbuf_puts(
sbuf_t *buf,
char *str) {
50 sbuf_append(buf, cx_str(str));
51 }
52
53 void sbuf_put(
sbuf_t *buf,
char chr) {
54 sbuf_append(buf, (cxstring){&chr,
1});
55 }
56
57 void sbuf_append(
sbuf_t *buf, cxstring str) {
58 if (buf->length + str.length >= buf->size) {
59 buf->size *=
2;
60 buf->ptr = realloc(buf->ptr, buf->size);
61 sbuf_append(buf, str);
62 return;
63 }
64
65 memcpy(&buf->ptr[buf->length], str.ptr, str.length);
66 buf->length += str.length;
67 buf->ptr[buf->length] =
0;
68 }
69
70 void sbuf_free(
sbuf_t *buf) {
71 free(buf->ptr);
72 free(buf);
73 }
74