| ... | ... | @@ -0,0 +1,51 @@ |
| 1 | const std = @import("../std.zig"); |
| 2 | const io = std.io; |
| 3 | const testing = std.testing; |
| 4 | |
| 5 | /// Takes a tuple of streams, and constructs a new stream that writes to all of them |
| 6 | pub fn MultiOutStream(comptime OutStreams: type) type { |
| 7 | comptime var ErrSet = error{}; |
| 8 | inline for (@typeInfo(OutStreams).Struct.fields) |field| { |
| 9 | const StreamType = field.field_type; |
| 10 | ErrSet = ErrSet || StreamType.Error; |
| 11 | } |
| 12 | |
| 13 | return struct { |
| 14 | const Self = @This(); |
| 15 | |
| 16 | streams: OutStreams, |
| 17 | |
| 18 | pub const Error = ErrSet; |
| 19 | pub const OutStream = io.OutStream(*Self, Error, write); |
| 20 | pub fn outStream(self: *Self) OutStream { |
| 21 | return .{ .context = self }; |
| 22 | } |
| 23 | |
| 24 | pub fn write(self: *Self, bytes: []const u8) Error!usize { |
| 25 | var batch = std.event.Batch(Error!void, self.streams.len, .auto_async).init(); |
| 26 | comptime var i = 0; |
| 27 | inline while (i < self.streams.len) : (i += 1) { |
| 28 | const stream = self.streams[i]; |
| 29 | // TODO: remove ptrCast: https://github.com/ziglang/zig/issues/5258 |
| 30 | batch.add(@ptrCast(anyframe->Error!void, &async stream.writeAll(bytes))); |
| 31 | } |
| 32 | try batch.wait(); |
| 33 | return bytes.len; |
| 34 | } |
| 35 | }; |
| 36 | } |
| 37 | |
| 38 | pub fn multiOutStream(streams: var) MultiOutStream(@TypeOf(streams)) { |
| 39 | return .{ .streams = streams }; |
| 40 | } |
| 41 | |
| 42 | test "MultiOutStream" { |
| 43 | var buf1: [255]u8 = undefined; |
| 44 | var fbs1 = io.fixedBufferStream(&buf1); |
| 45 | var buf2: [255]u8 = undefined; |
| 46 | var fbs2 = io.fixedBufferStream(&buf2); |
| 47 | var stream = multiOutStream(.{fbs1.outStream(), fbs2.outStream()}); |
| 48 | try stream.outStream().print("HI", .{}); |
| 49 | testing.expectEqualSlices(u8, "HI", fbs1.getWritten()); |
| 50 | testing.expectEqualSlices(u8, "HI", fbs2.getWritten()); |
| 51 | } |