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 */
17 if (buf
->size
< size
) {
18 size
= MAX(size
, buf
->size
*2);
19 char *data
= realloc(buf
->data
, size
);
28 void buffer_truncate(Buffer
*buf
) {
32 void buffer_release(Buffer
*buf
) {
39 void buffer_clear(Buffer
*buf
) {
43 bool buffer_put(Buffer
*buf
, const void *data
, size_t len
) {
44 if (!buffer_grow(buf
, len
))
46 memmove(buf
->data
, data
, len
);
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
) {
58 if (!buffer_grow(buf
, buf
->len
+ len
))
60 memmove(buf
->data
+ pos
+ len
, buf
->data
+ pos
, buf
->len
- pos
);
61 memcpy(buf
->data
+ pos
, data
, len
);
66 bool buffer_insert0(Buffer
*buf
, size_t pos
, const char *data
) {
68 return buffer_prepend0(buf
, data
);
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')
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')