Skip to content
Closed
Show file tree
Hide file tree
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
3 changes: 3 additions & 0 deletions lib/std/io.zig
Original file line number Diff line number Diff line change
Expand Up @@ -340,6 +340,9 @@ pub const Reader = GenericReader;
pub const AnyReader = @import("io/Reader.zig");

pub const Writer = @import("io/writer.zig").Writer;
pub const AnyWriter = @import("io/writer.zig").AnyWriter;
pub const WriterInterface = @import("io/writer.zig").WriterInterface;

pub const SeekableStream = @import("io/seekable_stream.zig").SeekableStream;

pub const BufferedWriter = @import("io/buffered_writer.zig").BufferedWriter;
Expand Down
9 changes: 9 additions & 0 deletions lib/std/io/test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -190,3 +190,12 @@ test "GenericReader methods can return error.EndOfStream" {
fbs.reader().isBytes("foo"),
);
}

test "AnyWriter write to buffer" {
var buffer = std.ArrayList(u8).init(std.testing.allocator);
defer buffer.deinit();
const writer = buffer.writer().any();

try writer.print("{s}", .{"greetings"});
try std.testing.expectEqualStrings("greetings", buffer.items);
}
38 changes: 36 additions & 2 deletions lib/std/io/writer.zig
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,46 @@ pub fn Writer(
context: Context,

const Self = @This();
pub const Error = WriteError;

pub fn write(self: Self, bytes: []const u8) Error!usize {
pub fn write(self: Self, bytes: []const u8) Self.Error!usize {
return writeFn(self.context, bytes);
}

pub inline fn any(self: *const Self) AnyWriter {
return .{
.context = @ptrCast(self),
.writeFn = typeErasedWriteFn,
};
}

fn typeErasedWriteFn(context: *const anyopaque, bytes: []const u8) anyerror!usize {
const self: *const Self = @ptrCast(@alignCast(context));
return self.write(bytes);
}

pub usingnamespace WriterInterface(Self, WriteError);
};
}

pub const AnyWriter = struct {
context: *const anyopaque,
writeFn: *const fn (context: *const anyopaque, bytes: []const u8) AnyWriter.Error!usize,

pub fn write(self: AnyWriter, bytes: []const u8) AnyWriter.Error!usize {
return self.writeFn(self.context, bytes);
}

pub inline fn any(self: AnyWriter) AnyWriter {
return self;
}

pub usingnamespace WriterInterface(AnyWriter, anyerror);
};

pub fn WriterInterface(comptime Self: type, comptime ErrSet: type) type {
return struct {
pub const Error = ErrSet;

pub fn writeAll(self: Self, bytes: []const u8) Error!void {
var index: usize = 0;
while (index != bytes.len) {
Expand Down