mirror of
https://github.com/ziglang/zig.git
synced 2024-11-27 23:52:31 +00:00
ba0e3be5cf
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.
57 lines
1.8 KiB
Zig
57 lines
1.8 KiB
Zig
const std = @import("../std.zig");
|
|
const io = std.io;
|
|
|
|
pub fn BufferedOutStream(comptime OutStreamType: type) type {
|
|
return BufferedOutStreamCustom(4096, OutStreamType);
|
|
}
|
|
|
|
pub fn BufferedOutStreamCustom(comptime buffer_size: usize, comptime OutStreamType: type) type {
|
|
return struct {
|
|
unbuffered_out_stream: OutStreamType,
|
|
fifo: FifoType,
|
|
|
|
pub const Error = OutStreamType.Error;
|
|
pub const OutStream = io.OutStream(*Self, Error, write);
|
|
|
|
const Self = @This();
|
|
const FifoType = std.fifo.LinearFifo(u8, std.fifo.LinearFifoBufferType{ .Static = buffer_size });
|
|
|
|
pub fn init(unbuffered_out_stream: OutStreamType) Self {
|
|
return Self{
|
|
.unbuffered_out_stream = unbuffered_out_stream,
|
|
.fifo = FifoType.init(),
|
|
};
|
|
}
|
|
|
|
pub fn flush(self: *Self) !void {
|
|
while (true) {
|
|
const slice = self.fifo.readableSlice(0);
|
|
if (slice.len == 0) break;
|
|
try self.unbuffered_out_stream.writeAll(slice);
|
|
self.fifo.discard(slice.len);
|
|
}
|
|
}
|
|
|
|
pub fn outStream(self: *Self) OutStream {
|
|
return .{ .context = self };
|
|
}
|
|
|
|
pub fn write(self: *Self, bytes: []const u8) Error!usize {
|
|
if (bytes.len >= self.fifo.writableLength()) {
|
|
try self.flush();
|
|
return self.unbuffered_out_stream.write(bytes);
|
|
}
|
|
self.fifo.writeAssumeCapacity(bytes);
|
|
return bytes.len;
|
|
}
|
|
};
|
|
}
|
|
|
|
pub fn bufferedOutStream(
|
|
comptime buffer_size: usize,
|
|
underlying_stream: var,
|
|
) BufferedOutStreamCustom(buffer_size, @TypeOf(underlying_stream)) {
|
|
return BufferedOutStreamCustom(buffer_size, @TypeOf(underlying_stream)).init(underlying_stream);
|
|
}
|
|
|