Commit 42b1b6be90

Mark Barbone <mark.l.barbone@gmail.com>
2020-09-08 05:24:35
Add resize for arena allocator
1 parent 5bf3e54
Changed files (1)
lib
lib/std/heap/arena_allocator.zig
@@ -26,7 +26,7 @@ pub const ArenaAllocator = struct {
             return .{
                 .allocator = Allocator{
                     .allocFn = alloc,
-                    .resizeFn = Allocator.noResize,
+                    .resizeFn = resize,
                 },
                 .child_allocator = child_allocator,
                 .state = self,
@@ -84,4 +84,26 @@ pub const ArenaAllocator = struct {
             return result;
         }
     }
+
+    fn resize(allocator: *Allocator, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ret_addr: usize) Allocator.Error!usize {
+        const self = @fieldParentPtr(ArenaAllocator, "allocator", allocator);
+
+        const cur_node = self.state.buffer_list.first orelse return error.OutOfMemory;
+        const cur_buf = cur_node.data[@sizeOf(BufNode)..];
+        if (@ptrToInt(cur_buf.ptr) + self.state.end_index != @ptrToInt(buf.ptr) + buf.len) {
+            if (new_len > buf.len)
+                return error.OutOfMemory;
+            return new_len;
+        }
+
+        if (buf.len >= new_len) {
+            self.state.end_index -= buf.len - new_len;
+            return new_len;
+        } else if (cur_buf.len - self.state.end_index >= new_len - buf.len) {
+            self.state.end_index += new_len - buf.len;
+            return new_len;
+        } else {
+            return error.OutOfMemory;
+        }
+    }
 };