summaryrefslogtreecommitdiff
path: root/src/memory.cc
diff options
context:
space:
mode:
authorFabrice <fabrice@schaub-dev.xyz>2026-03-01 22:03:55 +0100
committerFabrice <fabrice@schaub-dev.xyz>2026-03-01 22:03:55 +0100
commitffa09db5138dea853c910a0307fe5063511abb9f (patch)
treef3bfc548c126fb8280fc44262d265d44eb0fb3c4 /src/memory.cc
parentc638003e8aa684bae60e8b3736c6d9db8571e727 (diff)
fixing type errors working on strings
Diffstat (limited to 'src/memory.cc')
-rw-r--r--src/memory.cc63
1 files changed, 63 insertions, 0 deletions
diff --git a/src/memory.cc b/src/memory.cc
new file mode 100644
index 0000000..27504f0
--- /dev/null
+++ b/src/memory.cc
@@ -0,0 +1,63 @@
+#ifndef MEMORY_CC
+#define MEMORY_CC
+
+#include "common.cc"
+#include <cstdlib>
+#include <cstring>
+
+typedef u8* (*Allocator_Allocate)(u8* self, usize length, usize align);
+typedef void (*Allocator_Deallocate)(u8* self, u8* ptr);
+
+struct Allocator {
+ u8* self;
+ Allocator_Allocate allocate;
+ Allocator_Deallocate deallocate;
+};
+
+u8* allocate(Allocator* allocator, usize size, usize align) {
+ return allocator->allocate(allocator->self, size, align);
+}
+
+void deallocate(Allocator* allocator, u8* ptr) {
+ allocator->deallocate(allocator->self, ptr);
+}
+
+static inline u8* heap_allocate(u8* self, usize size, usize align) {
+ (void)self;
+ return (u8*)aligned_alloc(size, align);
+}
+
+static inline void heap_deallocate(u8* self, u8* ptr) {
+ (void)self;
+ free(ptr);
+}
+
+Allocator* heap_allocator() {
+ thread_local Allocator HEAP_ALLOCATOR = {nullptr, heap_allocate, heap_deallocate};
+ return &HEAP_ALLOCATOR;
+}
+
+template<typename T>
+bool slice_copy(Allocator* allocator, const Slice<T> *source, Slice<T> *out) {
+ T* new_ptr = allocate(allocator, source->size(), alignof(T));
+ if(new_ptr == nullptr) return false;
+
+ memcpy((u8*)new_ptr, (u8*)source->ptr, source->length);
+
+ out->length = source->length;
+ out->ptr = new_ptr;
+ return true;
+}
+
+template<typename T>
+void slice_deallocate(Allocator* allocator, Slice<T> *slice) {
+ if(slice->ptr == nullptr) return;
+
+ deallocate(allocator, (u8*)slice->ptr);
+
+ slice->ptr = nullptr;
+ slice->length = 0;
+}
+
+#endif
+