configure: probe for size optimizing flags (disabled for now)
[vis.git] / buffer.c
blobc4830d629c83c4d3fe0b23580eb7235b07b52b8e
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 /* ensure minimal buffer size, to avoid repeated realloc(3) calls */
15 if (size < BUF_SIZE)
16 size = BUF_SIZE;
17 if (buf->size < size) {
18 size = MAX(size, buf->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 void buffer_clear(Buffer *buf) {
40 buf->len = 0;
43 bool buffer_put(Buffer *buf, const void *data, size_t len) {
44 if (!buffer_grow(buf, len))
45 return false;
46 memmove(buf->data, data, len);
47 buf->len = len;
48 return true;
51 bool buffer_put0(Buffer *buf, const char *data) {
52 return buffer_put(buf, data, strlen(data)+1);
55 bool buffer_insert(Buffer *buf, size_t pos, const void *data, size_t len) {
56 if (pos > buf->len)
57 return false;
58 if (!buffer_grow(buf, buf->len + len))
59 return false;
60 memmove(buf->data + pos + len, buf->data + pos, buf->len - pos);
61 memcpy(buf->data + pos, data, len);
62 buf->len += len;
63 return true;
66 bool buffer_insert0(Buffer *buf, size_t pos, const char *data) {
67 if (pos == 0)
68 return buffer_prepend0(buf, data);
69 if (pos == buf->len)
70 return buffer_append0(buf, data);
71 return buffer_insert(buf, pos, data, strlen(data));
74 bool buffer_append(Buffer *buf, const void *data, size_t len) {
75 return buffer_insert(buf, buf->len, data, len);
78 bool buffer_append0(Buffer *buf, const char *data) {
79 if (buf->len > 0 && buf->data[buf->len-1] == '\0')
80 buf->len--;
81 return buffer_append(buf, data, strlen(data)) && buffer_append(buf, "\0", 1);
84 bool buffer_prepend(Buffer *buf, const void *data, size_t len) {
85 return buffer_insert(buf, 0, data, len);
88 bool buffer_prepend0(Buffer *buf, const char *data) {
89 return buffer_prepend(buf, data, strlen(data) + (buf->len == 0));
92 size_t buffer_length0(Buffer *buf) {
93 size_t len = buf->len;
94 if (len > 0 && buf->data[len-1] == '\0')
95 len--;
96 return len;