1const std = @import("std");
2const builtin = @import("builtin");
3const extras = @import("extras");
4const nio = @import("./nio.zig");
5
6const sys = switch (builtin.target.os.tag) {
7 .linux => @import("sys-linux"),
8 .macos => @import("sys-darwin"),
9 else => unreachable,
10};
11
12pub fn CountingReader(ReaderType: type) type {
13 return struct {
14 backing_reader: ReaderType,
15 bytes_read: u64,
16
17 const Self = @This();
18
19 pub fn init(backing_reader: ReaderType) Self {
20 return .{
21 .backing_reader = backing_reader,
22 .bytes_read = 0,
23 };
24 }
25
26 const R = nio.Readable(@This(), ._var);
27 pub const readAll = R.readAll;
28 pub const readAtLeast = R.readAtLeast;
29 pub const readNoEof = R.readNoEof;
30 pub const readAllAlloc = R.readAllAlloc;
31 pub const readArray = R.readArray;
32 pub const readByte = R.readByte;
33 pub const readUntilDelimiterArrayList = R.readUntilDelimiterArrayList;
34 pub const readUntilDelimiterAlloc = R.readUntilDelimiterAlloc;
35 pub const readUntilDelimiterOrEofAlloc = R.readUntilDelimiterOrEofAlloc;
36 pub const readUntilDelimitersBuf = R.readUntilDelimitersBuf;
37 pub const readUntilDelimitersArrayList = R.readUntilDelimitersArrayList;
38 pub const readAlloc = R.readAlloc;
39 pub const readInt = R.readInt;
40 pub const readUntilDelimitersAlloc = R.readUntilDelimitersAlloc;
41 pub const readUntilDelimiter = R.readUntilDelimiter;
42 pub const readUntilDelimiterOrEof = R.readUntilDelimiterOrEof;
43 pub const readExpected = R.readExpected;
44 pub const readType = R.readType;
45 pub const skipBytes = R.skipBytes;
46 pub const skipUntilDelimiterOrEof = R.skipUntilDelimiterOrEof;
47 pub const pipeTo = R.pipeTo;
48
49 pub const ReadError = extras.Pointee(ReaderType).ReadError;
50
51 pub fn read(self: *Self, bytes: []u8) ReadError!usize {
52 const len = try self.backing_reader.read(bytes);
53 self.bytes_read += len;
54 return len;
55 }
56 // pub fn readv(self: *Self, iovec: []sys.struct_iovec) ReadError!usize {
57 // const len = try self.backing_reader.readv(iovec);
58 // self.bytes_read += len;
59 // return len;
60 // }
61
62 pub fn anyReadable(self: *Self) nio.AnyReadable {
63 const S = struct {
64 fn read(s: *allowzero anyopaque, buffer: []u8) anyerror!usize {
65 const fbs: *Self = @ptrCast(@alignCast(s));
66 return fbs.read(buffer);
67 }
68 };
69 return .{
70 .vtable = &.{ .read = S.read },
71 .state = @ptrCast(self),
72 };
73 }
74 };
75}