| 1 | const std = @import("std"); |
| 2 | const builtin = @import("builtin"); |
| 3 | const extras = @import("extras"); |
| 4 | const nio = @import("./nio.zig"); |
| 5 | |
| 6 | const sys = switch (builtin.target.os.tag) { |
| 7 | .linux => @import("sys-linux"), |
| 8 | .macos => @import("sys-darwin"), |
| 9 | else => unreachable, |
| 10 | }; |
| 11 | |
| 12 | pub fn CountingWriter(WriterType: type) type { |
| 13 | return struct { |
| 14 | backing_writer: WriterType, |
| 15 | bytes_written: u64, |
| 16 | |
| 17 | const Self = @This(); |
| 18 | |
| 19 | pub fn init(backing_writer: WriterType) Self { |
| 20 | return .{ |
| 21 | .backing_writer = backing_writer, |
| 22 | .bytes_written = 0, |
| 23 | }; |
| 24 | } |
| 25 | |
| 26 | const W = nio.Writable(@This(), ._var); |
| 27 | pub const writeAll = W.writeAll; |
| 28 | pub const writevAll = W.writevAll; |
| 29 | pub const writeByteNTimes = W.writeByteNTimes; |
| 30 | pub const writeNTimes = W.writeNTimes; |
| 31 | pub const writeInt = W.writeInt; |
| 32 | pub const writeStruct = W.writeStruct; |
| 33 | pub const writeIntPretty = W.writeIntPretty; |
| 34 | pub const print = W.print; |
| 35 | |
| 36 | pub const WriteError = extras.Pointee(WriterType).WriteError; |
| 37 | pub fn write(self: *Self, bytes: []const u8) WriteError!usize { |
| 38 | const len = try self.backing_writer.write(bytes); |
| 39 | self.bytes_written += len; |
| 40 | return len; |
| 41 | } |
| 42 | pub fn writev(self: *Self, iovec: []const sys.struct_iovec) WriteError!usize { |
| 43 | const len = try self.backing_writer.writev(iovec); |
| 44 | self.bytes_written += len; |
| 45 | return len; |
| 46 | } |
| 47 | |
| 48 | pub fn anyWritable(self: *Self) nio.AnyWritable { |
| 49 | const S = struct { |
| 50 | fn write(s: *allowzero anyopaque, buffer: []const u8) anyerror!usize { |
| 51 | const cw: *Self = @ptrCast(@alignCast(s)); |
| 52 | return cw.write(buffer); |
| 53 | } |
| 54 | }; |
| 55 | return .{ |
| 56 | .vtable = &.{ .write = S.write }, |
| 57 | .state = @ptrCast(self), |
| 58 | }; |
| 59 | } |
| 60 | }; |
| 61 | } |