diff --git a/src/backend/Assembly.zig b/src/backend/Assembly.zig index 914bffb033bfff5923a987cb6e997a23973c3155..d5514aefba12b8d57caaa9e5fdbdec7bd87b5dd7 100644 --- a/src/backend/Assembly.zig +++ b/src/backend/Assembly.zig @@ -1,5 +1,6 @@ const std = @import("std"); const Allocator = std.mem.Allocator; +const testing = std.testing; data: []const u8, text: []const u8, @@ -18,3 +19,82 @@ pub fn writeToAllFile(self: Assembly, file: std.fs.File) !void { }; return file.writevAll(&vec); } + +test "Assembly writeToAllFile with empty data and text" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const gpa = arena.allocator(); + + const asm = Assembly{ + .data = try gpa.dupe(u8, ""), + .text = try gpa.dupe(u8, ""), + }; + defer asm.deinit(gpa); + + var file = std.io.FixedBufferStream([]u8).init(try gpa.alloc(u8, 0)); + try asm.writeToAllFile(file.writer()); + try testing.expectEqualStrings("", file.getWritten()); +} + +test "Assembly writeToAllFile with data only" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const gpa = arena.allocator(); + + const asm = Assembly{ + .data = try gpa.dupe(u8, ".data section"), + .text = try gpa.dupe(u8, ""), + }; + defer asm.deinit(gpa); + + var buf: [100]u8 = undefined; + var file = std.io.FixedBufferStream([]u8).init(&buf); + try asm.writeToAllFile(file.writer()); + try testing.expectEqualStrings(".data section", file.getWritten()); +} + +test "Assembly writeToAllFile with text only" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const gpa = arena.allocator(); + + const asm = Assembly{ + .data = try gpa.dupe(u8, ""), + .text = try gpa.dupe(u8, ".text section"), + }; + defer asm.deinit(gpa); + + var buf: [100]u8 = undefined; + var file = std.io.FixedBufferStream([]u8).init(&buf); + try asm.writeToAllFile(file.writer()); + try testing.expectEqualStrings(".text section", file.getWritten()); +} + +test "Assembly writeToAllFile with both data and text" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const gpa = arena.allocator(); + + const asm = Assembly{ + .data = try gpa.dupe(u8, "DATA"), + .text = try gpa.dupe(u8, "TEXT"), + }; + defer asm.deinit(gpa); + + var buf: [100]u8 = undefined; + var file = std.io.FixedBufferStream([]u8).init(&buf); + try asm.writeToAllFile(file.writer()); + try testing.expectEqualStrings("DATATEXT", file.getWritten()); +} + +test "Assembly deinit frees memory" { + var arena = std.heap.ArenaAllocator.init(testing.allocator); + defer arena.deinit(); + const gpa = arena.allocator(); + + const asm = Assembly{ + .data = try gpa.dupe(u8, "test data"), + .text = try gpa.dupe(u8, "test text"), + }; + asm.deinit(gpa); +}