summaryrefslogtreecommitdiff
path: root/src/util/membuf.c
diff options
context:
space:
mode:
authorJari Vetoniemi <mailroxas@gmail.com>2018-02-01 08:31:01 +0200
committerJari Vetoniemi <mailroxas@gmail.com>2018-02-12 03:34:18 +0200
commitf54e7e8c2aeb4fafebf0d5bd5570b060462c9ecf (patch)
treeb3bcc7ca21cda7d655bfcc0d9ec26d4a6668f27f /src/util/membuf.c
Initial commit
Diffstat (limited to 'src/util/membuf.c')
-rw-r--r--src/util/membuf.c31
1 files changed, 31 insertions, 0 deletions
diff --git a/src/util/membuf.c b/src/util/membuf.c
new file mode 100644
index 0000000..0602679
--- /dev/null
+++ b/src/util/membuf.c
@@ -0,0 +1,31 @@
+#include "membuf.h"
+
+#include <stdlib.h>
+#include <assert.h>
+#include <memory.h>
+#include <err.h>
+
+static void
+membuf_bounds_check(const struct membuf *buf, const size_t nmemb)
+{
+ assert(buf);
+
+ if (buf->mem.len < nmemb || buf->written > buf->mem.len - nmemb)
+ errx(EXIT_FAILURE, "%s: %zu bytes exceeds the maximum storage size of %zu bytes", __func__, buf->written + nmemb, buf->mem.len);
+}
+
+void
+membuf_terminate(struct membuf *buf, const void *data, const size_t data_sz)
+{
+ assert(data || !data_sz);
+ membuf_bounds_check(buf, data_sz);
+ memcpy((char*)buf->mem.data + buf->written, data, data_sz);
+}
+
+void
+membuf_append(struct membuf *buf, const void *data, const size_t data_sz)
+{
+ membuf_terminate(buf, data, data_sz);
+ buf->written += data_sz;
+ assert(buf->written <= buf->mem.len);
+}