aboutsummaryrefslogtreecommitdiff
path: root/src/utils.c
diff options
context:
space:
mode:
authorMistivia <i@mistivia.com>2025-03-16 20:01:42 +0800
committerMistivia <i@mistivia.com>2025-03-16 20:01:42 +0800
commitb83187f66175d93a0dba45f6d110ed94badac7c5 (patch)
tree22710b7a5278ac8a254ead30109f1dd9084d1022 /src/utils.c
parent1ce0d45242097a07b7a4ee539a074ec812851a58 (diff)
refactor using allocator pattern
Diffstat (limited to 'src/utils.c')
-rw-r--r--src/utils.c37
1 files changed, 37 insertions, 0 deletions
diff --git a/src/utils.c b/src/utils.c
new file mode 100644
index 0000000..354159b
--- /dev/null
+++ b/src/utils.c
@@ -0,0 +1,37 @@
+#include "utils.h"
+
+struct allocator {
+ void** bufs;
+ size_t cap;
+ size_t len;
+};
+
+Allocator newAllocator() {
+ Allocator alct = malloc(sizeof(struct allocator));
+ alct->bufs = malloc(sizeof(void*) * 16);
+ alct->cap = 16;
+ alct->len = 0;
+ alct->bufs[0] = NULL;
+ return alct;
+}
+
+void deleteAllocator(Allocator alct) {
+ for (size_t i = 0; i < alct->len; i++) {
+ free(alct->bufs[i]);
+ }
+ free(alct);
+}
+
+void * allocate(Allocator alct, size_t size) {
+ if (alct->len >= alct->cap) {
+ alct->cap = alct->cap * 2; // Doubling the capacity
+ alct->bufs = realloc(alct->bufs, sizeof(void*) * alct->cap);
+ }
+
+ void* ptr = malloc(size); // Allocate requested size
+ alct->bufs[alct->len] = ptr; // Store pointer in array
+ alct->len++;
+ return ptr;
+}
+
+