mirror of
https://codeberg.org/ziglang/zig.git
synced 2025-12-06 13:54:21 +00:00
Looking at the BufferedWriter assembly generated, one can see that is has to do a lot of work, just to copy over some bytes and increase an offset. This is because the LinearFifo is a much more general construct than what BufferedWriter needs and the optimizer cannot prove that we don't need to do this extra work.
42 lines
1.2 KiB
Zig
42 lines
1.2 KiB
Zig
const std = @import("../std.zig");
|
|
|
|
const io = std.io;
|
|
const mem = std.mem;
|
|
|
|
pub fn BufferedWriter(comptime buffer_size: usize, comptime WriterType: type) type {
|
|
return struct {
|
|
unbuffered_writer: WriterType,
|
|
buf: [buffer_size]u8 = undefined,
|
|
end: usize = 0,
|
|
|
|
pub const Error = WriterType.Error;
|
|
pub const Writer = io.Writer(*Self, Error, write);
|
|
|
|
const Self = @This();
|
|
|
|
pub fn flush(self: *Self) !void {
|
|
try self.unbuffered_writer.writeAll(self.buf[0..self.end]);
|
|
self.end = 0;
|
|
}
|
|
|
|
pub fn writer(self: *Self) Writer {
|
|
return .{ .context = self };
|
|
}
|
|
|
|
pub fn write(self: *Self, bytes: []const u8) Error!usize {
|
|
if (self.end + bytes.len > self.buf.len) {
|
|
try self.flush();
|
|
if (bytes.len > self.buf.len)
|
|
return self.unbuffered_writer.write(bytes);
|
|
}
|
|
|
|
mem.copy(u8, self.buf[self.end..], bytes);
|
|
self.end += bytes.len;
|
|
return bytes.len;
|
|
}
|
|
};
|
|
}
|
|
|
|
pub fn bufferedWriter(underlying_stream: anytype) BufferedWriter(4096, @TypeOf(underlying_stream)) {
|
|
return .{ .unbuffered_writer = underlying_stream };
|
|
}
|