Coming from Go (where there is io.Copy
), there appears to be no way in Zig to chain streams together without manually reading into a buffer, then writing the buffer to the Writer in a loop.
Obviously, this would need to happen under the hood regardless, but I am curious as to the reasoning behind not having a function which would lightly abstract it.
Is it just a lack of implementation due to not being sought after enough or has this been discussed before and denied? I can’t find any info on it.
In a recent project of mine, I’ve noticed a block of code that bugs me for one reason or another:
var bytes_read: usize = 1;
while (bytes_read > 0) {
bytes_read = try reader.read(buf);
_ = try writer.write(buf[0..bytes_read]);
}
Is this the intended way to read data into a Writer? I’ve looked at the Zig io source code and can’t find any other way. An option I find appealing would be something like this potential method being added to io.Reader:
try reader.readAllIntoWriter(
buf,
writer,
);
Or an alternative name, such as io.copy, which would also take the reader as a param:
try std.io.copy(
buf,
writer,
reader,
);
The proposed function would just be a light wrapper over the first example block, reading into and writing from buf
, until the Reader no longer has data left to read. I’d be happy to send a PR but I figured some discussion would be good first.