zig/lib/std/io/counting_out_stream.zig
Andrew Kelley ba0e3be5cf
(breaking) rework stream abstractions
The main goal here is to make the function pointers comptime, so that we
don't have to do the crazy stuff with async function frames.

Since InStream, OutStream, and SeekableStream are already generic
across error sets, it's not really worse to make them generic across the
vtable as well.

See #764 for the open issue acknowledging that using generics for these
abstractions is a design flaw.

See #130 for the efforts to make these abstractions non-generic.

This commit also changes the OutStream API so that `write` returns
number of bytes written, and `writeAll` is the one that loops until the
whole buffer is written.
2020-03-10 15:32:32 -04:00

43 lines
1.2 KiB
Zig

const std = @import("../std.zig");
const io = std.io;
/// An OutStream that counts how many bytes has been written to it.
pub fn CountingOutStream(comptime OutStreamType: type) type {
return struct {
bytes_written: u64,
child_stream: OutStreamType,
pub const Error = OutStreamType.Error;
pub const OutStream = io.OutStream(*Self, Error, write);
const Self = @This();
pub fn init(child_stream: OutStreamType) Self {
return Self{
.bytes_written = 0,
.child_stream = child_stream,
};
}
pub fn write(self: *Self, bytes: []const u8) Error!usize {
const amt = try self.child_stream.write(bytes);
self.bytes_written += amt;
return amt;
}
pub fn outStream(self: *Self) OutStream {
return .{ .context = self };
}
};
}
test "io.CountingOutStream" {
var counting_stream = CountingOutStream(NullOutStream.Error).init(std.io.null_out_stream);
const stream = &counting_stream.stream;
const bytes = "yay" ** 10000;
stream.write(bytes) catch unreachable;
testing.expect(counting_stream.bytes_written == bytes.len);
}