From 336af879aaa1794ffbaccf9ae52b655f54e832ac Mon Sep 17 00:00:00 2001 From: zach Date: Thu, 22 Feb 2024 15:56:43 -0800 Subject: [PATCH] feat: add Memory.loadAlloc (#29) --- src/Memory.zig | 6 ++++++ src/main.zig | 9 +++------ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/Memory.zig b/src/Memory.zig index cb94eb8..e29a4a7 100644 --- a/src/Memory.zig +++ b/src/Memory.zig @@ -30,6 +30,12 @@ pub fn load(self: Self, buf: []u8) void { } } +pub fn loadAlloc(self: Self, allocator: std.mem.Allocator) ![]u8 { + const out = try allocator.alloc(u8, @intCast(self.length)); + self.load(out); + return out; +} + pub fn store(self: Self, buf: []const u8) void { const len = buf.len; var i: usize = 0; diff --git a/src/main.zig b/src/main.zig index e849070..991b8ed 100644 --- a/src/main.zig +++ b/src/main.zig @@ -133,9 +133,7 @@ pub const Plugin = struct { } const memory = Memory.init(offset, c_len); defer memory.free(); - const value = try self.allocator.alloc(u8, @intCast(c_len)); - errdefer self.allocator.free(value); - memory.load(value); + const value = try memory.loadAlloc(self.allocator); return value; } @@ -166,9 +164,8 @@ pub const Plugin = struct { } const memory = Memory.init(offset, c_len); defer memory.free(); - const value = try self.allocator.alloc(u8, @intCast(c_len)); - errdefer self.allocator.free(value); - memory.load(value); + defer memory.free(); + const value = try memory.loadAlloc(self.allocator); return value; }