diff --git a/primitives.zig b/primitives.zig index 49ca297..1197a54 100644 --- a/primitives.zig +++ b/primitives.zig @@ -31,17 +31,19 @@ pub fn LinkedList() type { const Node = struct { point: Point, next: ?*Node }; head: ?*Node, length: u32, + allocator: std.mem.Allocator, - pub fn new() Self { + pub fn new(allocator: std.mem.Allocator) Self { return .{ .head = null, .length = 0, + .allocator = allocator, }; } - pub fn add(self: *Self, allocator: std.mem.Allocator, point: Point) void { + pub fn add(self: *Self, allocator: std.mem.Allocator, point: Point) !void { var newNode = allocator.create(Node) catch |err| { std.debug.print("error allocation, {}", .{err}); - return; + return err; }; newNode.point = point; @@ -51,7 +53,7 @@ pub fn LinkedList() type { self.length += 1; } pub fn dump(self: *Self) ![]Point { - const allocator = std.heap.page_allocator; + const allocator = self.allocator; var node = self.head; var point: []Point = &.{}; //empty slice var i: usize = 0; @@ -70,20 +72,24 @@ pub fn LinkedList() type { }; } test "test linked list" { - var polygon = LinkedList().new(); - polygon.add(std.heap.page_allocator, .{ .x = 10, .y = 11, .z = 0 }); - polygon.add(std.heap.page_allocator, .{ .x = 11, .y = 12, .z = 0 }); - polygon.add(std.heap.page_allocator, .{ .x = 12, .y = 13, .z = 0 }); - polygon.add(std.heap.page_allocator, .{ .x = 12, .y = 14, .z = 0 }); - polygon.add(std.heap.page_allocator, .{ .x = 12, .y = 15, .z = 0 }); - polygon.add(std.heap.page_allocator, .{ .x = 12, .y = 16, .z = 0 }); + var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + const allocator = arena.allocator(); + defer arena.deinit(); + + var polygon = LinkedList().new(allocator); + try polygon.add(allocator, .{ .x = 10, .y = 11, .z = 0 }); + try polygon.add(allocator, .{ .x = 11, .y = 12, .z = 0 }); + try polygon.add(allocator, .{ .x = 12, .y = 13, .z = 0 }); + try polygon.add(allocator, .{ .x = 12, .y = 14, .z = 0 }); + try polygon.add(allocator, .{ .x = 12, .y = 15, .z = 0 }); + try polygon.add(allocator, .{ .x = 12, .y = 16, .z = 0 }); + const points: []Point = try polygon.dump(); for (points) |point| { std.debug.print("x:{}\n", .{point.x}); std.debug.print("y:{}\n", .{point.y}); std.debug.print("z:{}\n", .{point.z}); } - std.heap.page_allocator.free(points); } pub fn pixel(buffer: []u8, w: Winsize, x: i64, y: i64, symbol: u21) !void {