Overhaul build system
[vis.git] / buffer.c
blob6a16a7b1adcc275d9ca99902717d934cf7ad0a9c
1 #include <stdlib.h>
2 #include <string.h>
4 #include "buffer.h"
5 #include "util.h"
7 #define BUF_SIZE 1024
9 void buffer_init(Buffer *buf) {
10 memset(buf, 0, sizeof *buf);
13 bool buffer_grow(Buffer *buf, size_t size) {
14 if (size < BUF_SIZE)
15 size = BUF_SIZE;
16 if (buf->size < size) {
17 if (buf->size > 0)
18 size *= 2;
19 char *data = realloc(buf->data, size);
20 if (!data)
21 return false;
22 buf->size = size;
23 buf->data = data;
25 return true;
28 void buffer_truncate(Buffer *buf) {
29 buf->len = 0;
32 void buffer_release(Buffer *buf) {
33 if (!buf)
34 return;
35 free(buf->data);
36 buffer_init(buf);
39 bool buffer_put(Buffer *buf, const void *data, size_t len) {
40 if (!buffer_grow(buf, len))
41 return false;
42 memmove(buf->data, data, len);
43 buf->len = len;
44 return true;
47 bool buffer_put0(Buffer *buf, const char *data) {
48 return buffer_put(buf, data, strlen(data)+1);
51 bool buffer_insert(Buffer *buf, size_t pos, const void *data, size_t len) {
52 if (pos > buf->len)
53 return false;
54 if (!buffer_grow(buf, buf->len + len))
55 return false;
56 memmove(buf->data + pos + len, buf->data + pos, buf->len - pos);
57 memcpy(buf->data + pos, data, len);
58 buf->len += len;
59 return true;
62 bool buffer_insert0(Buffer *buf, size_t pos, const char *data) {
63 if (pos == 0)
64 return buffer_prepend0(buf, data);
65 if (pos == buf->len)
66 return buffer_append0(buf, data);
67 return buffer_insert(buf, pos, data, strlen(data));
70 bool buffer_append(Buffer *buf, const void *data, size_t len) {
71 return buffer_insert(buf, buf->len, data, len);
74 bool buffer_append0(Buffer *buf, const char *data) {
75 if (buf->len > 0 && buf->data[buf->len-1] == '\0')
76 buf->len--;
77 return buffer_append(buf, data, strlen(data)) && buffer_append(buf, "\0", 1);
80 bool buffer_prepend(Buffer *buf, const void *data, size_t len) {
81 return buffer_insert(buf, 0, data, len);
84 bool buffer_prepend0(Buffer *buf, const char *data) {
85 return buffer_prepend(buf, data, strlen(data) + (buf->len == 0));