summaryrefslogtreecommitdiff
path: root/src/memory.c
diff options
context:
space:
mode:
authoronelin <oscar@nelin.dk>2025-10-31 23:55:42 +0000
committeronelin <oscar@nelin.dk>2025-11-02 22:07:17 +0000
commitd38deeef3af2316a666f8fc0173940bd769b748e (patch)
tree6e30d4a9eea18daa5705c894f28cd99ff047e8f9 /src/memory.c
parent6c077751982ea2c7bd2d9262b01b9f8602f80dc8 (diff)
Flatten project structure
This will make it easier to break up the code into smaller chunks again later. One would think doing this seems fun to me at this point.
Diffstat (limited to 'src/memory.c')
-rw-r--r--src/memory.c61
1 files changed, 61 insertions, 0 deletions
diff --git a/src/memory.c b/src/memory.c
new file mode 100644
index 0000000..8dc14eb
--- /dev/null
+++ b/src/memory.c
@@ -0,0 +1,61 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include <daw/logging.h>
+#include <daw/memory.h>
+
+memory* memory_new(usize max_size) {
+ memory* m = malloc(sizeof(memory));
+ m->data = malloc(max_size);
+ m->size = max_size;
+ m->pos = 0;
+ m->free = max_size;
+
+ memset(m->data, 0, max_size);
+
+ return m;
+}
+
+/* Returns a pointer to the allocated data */
+void* memory_allocate(memory* mem, usize size) {
+ void* data = NULL;
+
+ if (mem->pos + size <= mem->size) {
+ data = (void*)((usize)mem->data + mem->pos);
+ mem->pos += size;
+ mem->free -= size;
+ } else {
+ ERROR("Trying to allocate %lu in a %lu sized memory block", size,
+ mem->size);
+ ERROR("No more room!");
+ exit(EXIT_FAILURE);
+ }
+
+ return data;
+}
+
+memory memory_init(void* data, usize size) {
+ memory m = {0};
+ m.data = data;
+ m.size = size;
+ m.free = 0;
+ return m;
+}
+
+void memory_free(memory* mem, usize size) {
+ if (size > mem->pos) {
+ perror("Freeing too much memory!");
+ exit(EXIT_FAILURE);
+ } else {
+ mem->pos -= size;
+ mem->free += size;
+ }
+}
+
+void memory_clear(memory* mem) {
+ mem->pos = 0;
+ mem->free = mem->size;
+ /* Reset the memory? */
+ memset(mem->data, 0, mem->size);
+}