7 static void bytebuffer_reserve(struct bytebuffer *b, int cap) {
12 // prefer doubling capacity
13 if (b->cap * 2 >= cap) {
17 char *newbuf = malloc(cap);
19 // copy what was there, b->len > 0 assumes b->buf != null
20 memcpy(newbuf, b->buf, b->len);
23 // in case there was an allocated buffer, free it
30 static void bytebuffer_init(struct bytebuffer *b, int cap) {
37 b->buf = malloc(cap); // just assume malloc works always
41 static void bytebuffer_free(struct bytebuffer *b) {
46 static void bytebuffer_clear(struct bytebuffer *b) {
50 static void bytebuffer_append(struct bytebuffer *b, const char *data, int len) {
51 bytebuffer_reserve(b, b->len + len);
52 memcpy(b->buf + b->len, data, len);
56 static void bytebuffer_puts(struct bytebuffer *b, const char *str) {
57 bytebuffer_append(b, str, strlen(str));
60 static void bytebuffer_resize(struct bytebuffer *b, int len) {
61 bytebuffer_reserve(b, len);
65 static void bytebuffer_flush(struct bytebuffer *b, int fd) {
66 int yyy = write(fd, b->buf, b->len);
71 static void bytebuffer_truncate(struct bytebuffer *b, int n) {
76 const int nmove = b->len - n;
77 memmove(b->buf, b->buf+n, nmove);