blob: fb3af829b54151e715d0186ed4823fb99d6b5c36 (
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
|
#include <stdlib.h>
#include <string.h>
#include "buf.h"
#include "err.h"
void buf_init(buf_t *b, size_t n) {
b->buf = calloc(1, n);
if (!b->buf) {
efatal("buf_init");
}
b->cap = n;
b->sz = 0;
}
/* does NOT change sz! just makes room */
void buf_grow(buf_t *b, size_t n) {
size_t sz = b->sz + n;
size_t c = b->cap;
if (sz > c) {
while (sz > c) c <<= 1;
char *p = realloc(b->buf, c);
if (!p) efatal("buf_grow");
b->buf = p;
b->cap = c;
}
}
void buf_cat(buf_t *b, const char *src, size_t n) {
buf_grow(b, n);
memcpy(&b->buf[b->sz], src, n);
b->sz += n;
}
void buf_catc(buf_t *b, char c) {
buf_grow(b, 1);
b->buf[b->sz++] = c;
}
void buf_free(buf_t *b) {
free(b->buf);
}
|