| ... | ... | @@ -0,0 +1,48 @@ |
| 1 | // SPDX-License-Identifier: MIT |
| 2 | // Copyright (c) 2015-2020 Zig Contributors |
| 3 | // This file is part of [zig](https://ziglang.org/), which is MIT licensed. |
| 4 | // The MIT license requires this copyright notice to be included in all copies |
| 5 | // and substantial portions of the software. |
| 6 | const std = @import("../std.zig"); |
| 7 | const io = std.io; |
| 8 | const testing = std.testing; |
| 9 | |
| 10 | /// A Reader that counts how many bytes has been read from it. |
| 11 | pub fn CountingReader(comptime ReaderType: anytype) type { |
| 12 | return struct { |
| 13 | child_reader: ReaderType, |
| 14 | bytes_read: u64 = 0, |
| 15 | |
| 16 | pub const Error = ReaderType.Error; |
| 17 | pub const Reader = io.Reader(*@This(), Error, read); |
| 18 | |
| 19 | pub fn read(self: *@This(), buf: []u8) Error!usize { |
| 20 | const amt = try self.child_reader.read(buf); |
| 21 | self.bytes_read += amt; |
| 22 | return amt; |
| 23 | } |
| 24 | |
| 25 | pub fn reader(self: *@This()) Reader { |
| 26 | return .{ .context = self }; |
| 27 | } |
| 28 | }; |
| 29 | } |
| 30 | |
| 31 | pub fn countingReader(reader: anytype) CountingReader(@TypeOf(reader)) { |
| 32 | return .{ .child_reader = reader, }; |
| 33 | } |
| 34 | |
| 35 | test "io.CountingReader" { |
| 36 | const bytes = "yay" ** 100; |
| 37 | var fbs = io.fixedBufferStream(bytes); |
| 38 | |
| 39 | var counting_stream = countingReader(fbs.reader()); |
| 40 | const stream = counting_stream.reader(); |
| 41 | |
| 42 | //read and discard all bytes |
| 43 | while(stream.readByte()) |_| {} else |err| { |
| 44 | testing.expect(err == error.EndOfStream); |
| 45 | } |
| 46 | |
| 47 | testing.expect(counting_stream.bytes_read == bytes.len); |
| 48 | } |
| | \ No newline at end of file |