aboutsummaryrefslogtreecommitdiff
path: root/buffer.c
diff options
context:
space:
mode:
authorMarc André Tanner <mat@brain-dump.org>2014-12-18 13:50:19 +0100
committerMarc André Tanner <mat@brain-dump.org>2014-12-18 16:57:18 +0100
commitb8456fa2615480fa242c6992ca89481a8370fe5f (patch)
tree4836c8561242182ea5d13d735fe6432e9d5624c4 /buffer.c
parent46ffdc3dff7a8bf87f3b1004c3c12a7f6fcd8d6c (diff)
downloadvis-b8456fa2615480fa242c6992ca89481a8370fe5f.tar.gz
vis-b8456fa2615480fa242c6992ca89481a8370fe5f.tar.xz
Macro support
At some point this should be optimized further at the moment there is some 20 byte overhead for each entered key.
Diffstat (limited to 'buffer.c')
-rw-r--r--buffer.c54
1 files changed, 54 insertions, 0 deletions
diff --git a/buffer.c b/buffer.c
new file mode 100644
index 0000000..9722101
--- /dev/null
+++ b/buffer.c
@@ -0,0 +1,54 @@
+#include <stdlib.h>
+#include <string.h>
+
+#include "buffer.h"
+#include "util.h"
+
+#define BUF_SIZE 1024
+
+bool buffer_alloc(Buffer *buf, size_t size) {
+ if (size < BUF_SIZE)
+ size = BUF_SIZE;
+ if (buf->size < size) {
+ if (buf->size > 0)
+ size *= 2;
+ buf->data = realloc(buf->data, size);
+ if (!buf->data) {
+ buf->size = 0;
+ buf->len = 0;
+ return false;
+ }
+ buf->size = size;
+ }
+ return true;
+}
+
+void buffer_truncate(Buffer *buf) {
+ buf->len = 0;
+}
+
+void buffer_free(Buffer *buf) {
+ if (!buf)
+ return;
+ free(buf->data);
+ buf->data = NULL;
+ buf->len = 0;
+ buf->size = 0;
+}
+
+bool buffer_put(Buffer *buf, void *data, size_t len) {
+ if (!buffer_alloc(buf, len))
+ return false;
+ memcpy(buf->data, data, len);
+ buf->len = len;
+ return true;
+}
+
+bool buffer_append(Buffer *buf, void *data, size_t len) {
+ size_t rem = buf->size - buf->len;
+ if (len > rem && !buffer_alloc(buf, buf->size + len - rem))
+ return false;
+ memcpy(buf->data + buf->len, data, len);
+ buf->len += len;
+ return true;
+}