💾 Archived View for gmi.noulin.net › gitRepositories › heartbeat › file › shpPackages › termbox › by… captured on 2024-06-20 at 11:56:03. Gemini links have been rewritten to link to archived content
-=-=-=-=-=-=-
bytebuffer.h (1371B)
1 struct bytebuffer { 2 char *buf; 3 int len; 4 int cap; 5 }; 6 7 static void bytebuffer_reserve(struct bytebuffer *b, int cap) { 8 if (b->cap >= cap) { 9 return; 10 } 11 12 // prefer doubling capacity 13 if (b->cap * 2 >= cap) { 14 cap = b->cap * 2; 15 } 16 17 char *newbuf = realloc(b->buf, cap); 18 b->buf = newbuf; 19 b->cap = cap; 20 } 21 22 static void bytebuffer_init(struct bytebuffer *b, int cap) { 23 b->cap = 0; 24 b->len = 0; 25 b->buf = 0; 26 27 if (cap > 0) { 28 b->cap = cap; 29 b->buf = malloc(cap); // just assume malloc works always 30 } 31 } 32 33 static void bytebuffer_free(struct bytebuffer *b) { 34 if (b->buf) 35 free(b->buf); 36 } 37 38 static void bytebuffer_clear(struct bytebuffer *b) { 39 b->len = 0; 40 } 41 42 static void bytebuffer_append(struct bytebuffer *b, const char *data, int len) { 43 bytebuffer_reserve(b, b->len + len); 44 memcpy(b->buf + b->len, data, len); 45 b->len += len; 46 } 47 48 static void bytebuffer_puts(struct bytebuffer *b, const char *str) { 49 bytebuffer_append(b, str, strlen(str)); 50 } 51 52 static void bytebuffer_resize(struct bytebuffer *b, int len) { 53 bytebuffer_reserve(b, len); 54 b->len = len; 55 } 56 57 static void bytebuffer_flush(struct bytebuffer *b, int fd) { 58 write(fd, b->buf, b->len); 59 bytebuffer_clear(b); 60 } 61 62 static void bytebuffer_truncate(struct bytebuffer *b, int n) { 63 if (n <= 0) 64 return; 65 if (n > b->len) 66 n = b->len; 67 const int nmove = b->len - n; 68 memmove(b->buf, b->buf+n, nmove); 69 b->len -= n; 70 }