summaryrefslogtreecommitdiff
path: root/src/allocator.h
diff options
context:
space:
mode:
authorAlbert Cervin <albert@acervin.com>2023-01-26 13:07:07 +0100
committerAlbert Cervin <albert@acervin.com>2023-01-26 13:07:07 +0100
commite65158a0326108d1fc724ee683b7fa900ef2671a (patch)
tree9bad30b377a326e0d0e3101c4f96228ae7a41673 /src/allocator.h
parent9a2b138a03e27d0f04101fe6ae3977d79518c513 (diff)
downloaddged-e65158a0326108d1fc724ee683b7fa900ef2671a.tar.gz
dged-e65158a0326108d1fc724ee683b7fa900ef2671a.tar.xz
dged-e65158a0326108d1fc724ee683b7fa900ef2671a.zip
More tests and documentation
Also, split out platform-specific parts and add mocks for tests.
Diffstat (limited to 'src/allocator.h')
-rw-r--r--src/allocator.h51
1 files changed, 51 insertions, 0 deletions
diff --git a/src/allocator.h b/src/allocator.h
new file mode 100644
index 0000000..d89bd29
--- /dev/null
+++ b/src/allocator.h
@@ -0,0 +1,51 @@
+#include <stddef.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+/**
+ * Simple bump allocator that can be used for
+ * allocations with a frame lifetime.
+ */
+struct frame_allocator {
+ uint8_t *buf;
+ size_t offset;
+ size_t capacity;
+};
+
+/**
+ * Create a new frame allocator
+ *
+ * @param capacity The capacity in bytes of the frame allocator
+ * @returns The frame allocator
+ */
+struct frame_allocator frame_allocator_create(size_t capacity) {
+ return (struct frame_allocator){
+ .capacity = capacity, .offset = 0, .buf = (uint8_t *)malloc(capacity)};
+}
+
+/**
+ * Allocate memory in this @ref frame_allocator "frame allocator"
+ *
+ * @param alloc The allocator to allocate in
+ * @param sz The size in bytes to allocate.
+ * @returns void* representing the start of the allocated region on success,
+ * NULL on failure.
+ */
+void *frame_allocator_alloc(struct frame_allocator *alloc, size_t sz) {
+ if (alloc->offset + sz > alloc->capacity) {
+ return NULL;
+ }
+
+ void *mem = alloc->buf + alloc->offset;
+ alloc->offset += sz;
+
+ return mem;
+}
+
+/**
+ * Clear this @ref frame_allocator "frame allocator".
+ *
+ * This does not free any memory, but simply resets the offset to 0.
+ * @param alloc The frame allocator to clear
+ */
+void frame_allocator_clear(struct frame_allocator *alloc) { alloc->offset = 0; }