From 086bad260a4cf52e8b4c261d42a36eae5014c795 Mon Sep 17 00:00:00 2001 From: Travis Staloch <1562827+travisstaloch@users.noreply.github.com> Date: Sun, 31 Aug 2025 12:38:35 -0700 Subject: [PATCH] Io.Writer.Allocating: test new *Aligned methods * added initAligned() * added missing @alignCast in toArrayListAligned() --- lib/std/Io/Writer.zig | 32 ++++++++++++++++++++++++++++---- 1 file changed, 28 insertions(+), 4 deletions(-) diff --git a/lib/std/Io/Writer.zig b/lib/std/Io/Writer.zig index 8bfb1bb75e89..1c34a124aef9 100644 --- a/lib/std/Io/Writer.zig +++ b/lib/std/Io/Writer.zig @@ -2541,13 +2541,17 @@ pub const Allocating = struct { alignment: std.mem.Alignment, pub fn init(allocator: Allocator) Allocating { + return .initAligned(allocator, .of(u8)); + } + + pub fn initAligned(allocator: Allocator, alignment: std.mem.Alignment) Allocating { return .{ .allocator = allocator, .writer = .{ .buffer = &.{}, .vtable = &vtable, }, - .alignment = .of(u8), + .alignment = alignment, }; } @@ -2775,16 +2779,36 @@ pub const Allocating = struct { a.ensureUnusedCapacity(minimum_len) catch return error.WriteFailed; } - test Allocating { - var a: Allocating = .init(testing.allocator); + fn testAllocating(comptime alignment: std.mem.Alignment) !void { + var a: Allocating = .initAligned(testing.allocator, alignment); defer a.deinit(); const w = &a.writer; const x: i32 = 42; const y: i32 = 1234; try w.print("x: {}\ny: {}\n", .{ x, y }); + const expected = "x: 42\ny: 1234\n"; + try testing.expectEqualSlices(u8, expected, a.written()); + + // exercise *Aligned methods + var l = a.toArrayListAligned(alignment); + defer l.deinit(testing.allocator); + try testing.expectEqualSlices(u8, expected, l.items); + a = .fromArrayListAligned(testing.allocator, alignment, &l); + try testing.expectEqualSlices(u8, expected, a.written()); + const slice: []align(alignment.toByteUnits()) u8 = @alignCast(try a.toOwnedSlice()); + try testing.expectEqualSlices(u8, expected, slice); + a = .initOwnedSliceAligned(testing.allocator, alignment, slice); + try testing.expectEqualSlices(u8, expected, a.writer.buffer); + } - try testing.expectEqualSlices(u8, "x: 42\ny: 1234\n", a.written()); + test Allocating { + try testAllocating(.fromByteUnits(1)); + try testAllocating(.fromByteUnits(4)); + try testAllocating(.fromByteUnits(8)); + try testAllocating(.fromByteUnits(16)); + try testAllocating(.fromByteUnits(32)); + try testAllocating(.fromByteUnits(64)); } };