zig/lib/std/io/buffered_writer.zig
Andrew Kelley d29871977f remove redundant license headers from zig standard library
We already have a LICENSE file that covers the Zig Standard Library. We
no longer need to remind everyone that the license is MIT in every single
file.

Previously this was introduced to clarify the situation for a fork of
Zig that made Zig's LICENSE file harder to find, and replaced it with
their own license that required annual payments to their company.
However that fork now appears to be dead. So there is no need to
reinforce the copyright notice in every single file.
2021-08-24 12:25:09 -07:00

42 lines
1.3 KiB
Zig

const std = @import("../std.zig");
const io = std.io;
pub fn BufferedWriter(comptime buffer_size: usize, comptime WriterType: type) type {
return struct {
unbuffered_writer: WriterType,
fifo: FifoType = FifoType.init(),
pub const Error = WriterType.Error;
pub const Writer = io.Writer(*Self, Error, write);
const Self = @This();
const FifoType = std.fifo.LinearFifo(u8, std.fifo.LinearFifoBufferType{ .Static = buffer_size });
pub fn flush(self: *Self) !void {
while (true) {
const slice = self.fifo.readableSlice(0);
if (slice.len == 0) break;
try self.unbuffered_writer.writeAll(slice);
self.fifo.discard(slice.len);
}
}
pub fn writer(self: *Self) Writer {
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_writer.write(bytes);
}
self.fifo.writeAssumeCapacity(bytes);
return bytes.len;
}
};
}
pub fn bufferedWriter(underlying_stream: anytype) BufferedWriter(4096, @TypeOf(underlying_stream)) {
return .{ .unbuffered_writer = underlying_stream };
}