aboutsummaryrefslogtreecommitdiff
path: root/lib/std/Io/counting_reader.zig
diff options
context:
space:
mode:
authorAndrew Kelley <andrew@ziglang.org>2025-07-10 10:28:32 -0700
committerAndrew Kelley <andrew@ziglang.org>2025-07-11 01:16:27 +0200
commit5360968e03525be4d312ca61a7ba2dcb7890ec42 (patch)
tree61a6e784902998cc3f59a05adb3251a78db5ee09 /lib/std/Io/counting_reader.zig
parent43fba5ea83849ec901bb2cd4f98bd0222f51f7f6 (diff)
downloadzig-5360968e03525be4d312ca61a7ba2dcb7890ec42.tar.gz
zig-5360968e03525be4d312ca61a7ba2dcb7890ec42.zip
std: rename `io` to `Io` in preparation
This commit is non-breaking. std.io is deprecated in favor of std.Io, in preparation for that namespace becoming an interface.
Diffstat (limited to 'lib/std/Io/counting_reader.zig')
-rw-r--r--lib/std/Io/counting_reader.zig43
1 files changed, 43 insertions, 0 deletions
diff --git a/lib/std/Io/counting_reader.zig b/lib/std/Io/counting_reader.zig
new file mode 100644
index 0000000000..bc1e1b6ec7
--- /dev/null
+++ b/lib/std/Io/counting_reader.zig
@@ -0,0 +1,43 @@
+const std = @import("../std.zig");
+const io = std.io;
+const testing = std.testing;
+
+/// A Reader that counts how many bytes has been read from it.
+pub fn CountingReader(comptime ReaderType: anytype) type {
+ return struct {
+ child_reader: ReaderType,
+ bytes_read: u64 = 0,
+
+ pub const Error = ReaderType.Error;
+ pub const Reader = io.GenericReader(*@This(), Error, read);
+
+ pub fn read(self: *@This(), buf: []u8) Error!usize {
+ const amt = try self.child_reader.read(buf);
+ self.bytes_read += amt;
+ return amt;
+ }
+
+ pub fn reader(self: *@This()) Reader {
+ return .{ .context = self };
+ }
+ };
+}
+
+pub fn countingReader(reader: anytype) CountingReader(@TypeOf(reader)) {
+ return .{ .child_reader = reader };
+}
+
+test CountingReader {
+ const bytes = "yay" ** 100;
+ var fbs = io.fixedBufferStream(bytes);
+
+ var counting_stream = countingReader(fbs.reader());
+ const stream = counting_stream.reader();
+
+ //read and discard all bytes
+ while (stream.readByte()) |_| {} else |err| {
+ try testing.expect(err == error.EndOfStream);
+ }
+
+ try testing.expect(counting_stream.bytes_read == bytes.len);
+}