Added managed heap allocation to bh.h
authorBrendan Hansen <brendan.f.hansen@gmail.com>
Sun, 28 Jun 2020 03:43:03 +0000 (22:43 -0500)
committerBrendan Hansen <brendan.f.hansen@gmail.com>
Sun, 28 Jun 2020 03:43:03 +0000 (22:43 -0500)
This will simplify some of the allocations in the compiler

include/bh.h
onyx

index 455c79635d27ecb046a5a7448df99d1a1514a4c9..482ef21737ebcde4bc4451a04db843df5ea74343 100644 (file)
@@ -191,6 +191,16 @@ BH_ALLOCATOR_PROC(bh_heap_allocator_proc);
 
 
 
+// MANAGED HEAP ALLOCATOR
+typedef struct bh_managed_heap {
+    ptr* pointers; // Actually a bh_arr
+} bh_managed_heap;
+
+void bh_managed_heap_init(bh_managed_heap* mh);
+void bh_managed_heap_free(bh_managed_heap* mh);
+bh_allocator bh_managed_heap_allocator(bh_managed_heap* mh);
+BH_ALLOCATOR_PROC(bh_managed_heap_allocator_proc);
+
 
 
 // ARENA ALLOCATOR
@@ -795,6 +805,88 @@ BH_ALLOCATOR_PROC(bh_heap_allocator_proc) {
 
 
 
+// MANAGED HEAP ALLOCATOR IMPLEMENTATION
+void bh_managed_heap_init(bh_managed_heap* mh) {
+    mh->pointers = NULL;
+
+    bh_arr_new(bh_heap_allocator(), mh->pointers, 4);
+}
+
+void bh_managed_heap_free(bh_managed_heap* mh) {
+    bh_arr_each(ptr, p, mh->pointers) {
+        free(*p);
+    }
+
+    bh_arr_free(mh->pointers);
+}
+
+bh_allocator bh_managed_heap_allocator(bh_managed_heap* mh) {
+    return (bh_allocator) {
+        .proc = bh_managed_heap_allocator_proc,
+        .data = mh
+    };
+}
+
+BH_ALLOCATOR_PROC(bh_managed_heap_allocator_proc) {
+    bh_managed_heap* mh = (bh_managed_heap *) data;
+    ptr retval = NULL;
+
+    switch (action) {
+    case bh_allocator_action_alloc: {
+        retval = aligned_alloc(alignment, size);
+
+        if (flags & bh_allocator_flag_clear && retval != NULL) {
+            memset(retval, 0, size);
+        }
+
+        if (retval != NULL)
+            bh_arr_push(mh->pointers, retval);
+    } break;
+
+    case bh_allocator_action_resize: {
+        i32 replace_idx = 0;
+        b32 found = 0;
+
+        bh_arr_each(ptr, p, mh->pointers) {
+            if (*p == prev_memory) {
+                found = 1;
+                break;
+            }
+
+            replace_idx++;
+        }
+
+        retval = realloc(prev_memory, size);
+        mh->pointers[replace_idx] = retval;
+    } break;
+
+    case bh_allocator_action_free: {
+        i32 free_idx = 0;
+        b32 found = 0;
+
+        bh_arr_each(ptr, p, mh->pointers) {
+            if (*p == prev_memory) {
+                found = 1;
+                break;
+            }
+
+            free_idx++;
+        }
+
+        bh_arr_fastdelete(mh->pointers, free_idx);
+        free(prev_memory);
+    } break;
+    }
+
+    return retval;
+}
+
+
+
+
+
+
+
 
 // ARENA ALLOCATOR IMPLEMENTATION
 void bh_arena_init(bh_arena* alloc, bh_allocator backing, isize arena_size) {
diff --git a/onyx b/onyx
index 1342320070f7dec55390d54d1e1f8bfc7d38de45..d5be33e57d0629b73bd995d573b0bccb0f1d44a8 100755 (executable)
Binary files a/onyx and b/onyx differ