aboutsummaryrefslogtreecommitdiff
path: root/src/std/memory.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/std/memory.c')
-rw-r--r--src/std/memory.c33
1 files changed, 33 insertions, 0 deletions
diff --git a/src/std/memory.c b/src/std/memory.c
new file mode 100644
index 0000000..3448819
--- /dev/null
+++ b/src/std/memory.c
@@ -0,0 +1,33 @@
+#include <stdint.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "assert.h"
+#include "memory.h"
+#include "types.h"
+
+Arena Arena_new(size cap) {
+ Arena a = {0};
+ a.cap = cap;
+ a.beg = malloc(cap);
+ a.end = a.beg ? a.beg + cap : 0;
+ return a;
+}
+
+// Magic to allow optimisation __attribute((malloc, alloc_size(2, 4),
+// alloc_align(3)))
+void *alloc(Arena *a, size count, size tsize, size align) {
+ size padding = -(uptr)a->beg & (align - 1);
+ byte *beg = a->beg + padding;
+ size alloc_size = count * tsize;
+ assert(beg + alloc_size < a->end, "out of memory");
+ a->beg = beg + alloc_size;
+ return beg;
+}
+
+void Arena_reset(Arena *a) {
+ a->beg = a->end - a->cap;
+ memset(a->beg, 0, a->end - a->beg);
+}
+
+size Arena_get_used(Arena a) { return a.cap - (a.end - a.beg); }