|
| 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 assert = std.debug.assert; |
| 9 | +const testing = std.testing; |
| 10 | + |
| 11 | +pub fn EarlyEOFReader(comptime ReaderType: type) type { |
| 12 | + return struct { |
| 13 | + inner_reader: ReaderType, |
| 14 | + bytes_left: u64, |
| 15 | + |
| 16 | + pub const Error = ReaderType.Error; |
| 17 | + pub const Reader = io.Reader(*Self, Error, read); |
| 18 | + |
| 19 | + const Self = @This(); |
| 20 | + |
| 21 | + pub fn read(self: *Self, dest: []u8) Error!usize { |
| 22 | + const max_read = std.math.min(self.bytes_left, dest.len); |
| 23 | + const n = try self.inner_reader.read(dest[0..max_read]); |
| 24 | + self.bytes_left -= n; |
| 25 | + return n; |
| 26 | + } |
| 27 | + |
| 28 | + pub fn reader(self: *Self) Reader { |
| 29 | + return .{ .context = self }; |
| 30 | + } |
| 31 | + }; |
| 32 | +} |
| 33 | + |
| 34 | +/// Returns an initialised `EarlyEOFReader` |
| 35 | +/// `bytes_left` is a `u64` to be able to take 64 bit file offsets |
| 36 | +pub fn earlyEOFReader(inner_reader: anytype, bytes_left: u64) EarlyEOFReader(@TypeOf(inner_reader)) { |
| 37 | + return .{ .inner_reader = inner_reader, .bytes_left = bytes_left }; |
| 38 | +} |
| 39 | + |
| 40 | +test "io.EarlyEOFReader" { |
| 41 | + const data = "hello world"; |
| 42 | + var fbs = std.io.fixedBufferStream(data); |
| 43 | + var early_stream = earlyEOFReader(fbs.reader(), 3); |
| 44 | + |
| 45 | + var buf: [5]u8 = undefined; |
| 46 | + testing.expectEqual(@as(usize, 3), try early_stream.reader().read(&buf)); |
| 47 | + testing.expectEqualSlices(u8, data[0..3], buf[0..3]); |
| 48 | + testing.expectEqual(@as(usize, 0), try early_stream.reader().read(&buf)); |
| 49 | + testing.expectError(error.EndOfStream, early_stream.reader().skipBytes(10, .{})); |
| 50 | +} |
0 commit comments