Skip to content

multi-writer: test with a non-comptime stream #15770

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 19, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 13 additions & 12 deletions lib/std/io/multi_writer.zig
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
const std = @import("../std.zig");
const io = std.io;
const testing = std.testing;

/// Takes a tuple of streams, and constructs a new stream that writes to all of them
pub fn MultiWriter(comptime Writers: type) type {
Expand All @@ -23,14 +22,8 @@ pub fn MultiWriter(comptime Writers: type) type {
}

pub fn write(self: *Self, bytes: []const u8) Error!usize {
var batch = std.event.Batch(Error!void, self.streams.len, .auto_async).init();
comptime var i = 0;
inline while (i < self.streams.len) : (i += 1) {
const stream = self.streams[i];
// TODO: remove ptrCast: https://github.com/ziglang/zig/issues/5258
batch.add(@ptrCast(anyframe->Error!void, &async stream.writeAll(bytes)));
}
try batch.wait();
inline for (self.streams) |stream|
try stream.writeAll(bytes);
return bytes.len;
}
};
Expand All @@ -40,13 +33,21 @@ pub fn multiWriter(streams: anytype) MultiWriter(@TypeOf(streams)) {
return .{ .streams = streams };
}

const testing = std.testing;

test "MultiWriter" {
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var f = try tmp.dir.createFile("t.txt", .{});

var buf1: [255]u8 = undefined;
var fbs1 = io.fixedBufferStream(&buf1);
var buf2: [255]u8 = undefined;
var fbs2 = io.fixedBufferStream(&buf2);
var stream = multiWriter(.{ fbs1.writer(), fbs2.writer() });
var stream = multiWriter(.{ fbs1.writer(), f.writer() });

try stream.writer().print("HI", .{});
f.close();

try testing.expectEqualSlices(u8, "HI", fbs1.getWritten());
try testing.expectEqualSlices(u8, "HI", fbs2.getWritten());
try testing.expectEqualSlices(u8, "HI", try tmp.dir.readFile("t.txt", &buf2));
}