authorgravatar for lockbox.06@protonmail.comlockbox <lockbox.06@protonmail.com> 2023-07-23 13:24:43-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-07-24 17:32:06-07:00
log9b56c7de79ee5aa4540f5427a37fd8883d1fb4e6
tree869224a9ebc0a82fbe5a0f18d09c9e4338dd76a6
parent8b1976cab55d04a138ccb102ca2008558e34bd7d

Fix type mismatch for Reader.readIntoBoundedBytes (#16416)

- add unit test to verify .readIntoBoundedBytes behavior - add unit test to verify .readBoundedBytes behavior

1 files changed, 30 insertions(+), 3 deletions(-)

lib/std/io/reader.zig+30-3
......@@ -257,17 +257,23 @@ pub fn Reader(
257257 return bytes;
258258 }
259259
260 /// Reads bytes into the bounded array, until
261 /// the bounded array is full, or the stream ends.
260 /// Reads bytes until `bounded.len` is equal to `num_bytes`,
261 /// or the stream ends.
262 ///
263 /// * it is assumed that `num_bytes` will not exceed `bounded.capacity()`
262264 pub fn readIntoBoundedBytes(
263265 self: Self,
264266 comptime num_bytes: usize,
265267 bounded: *std.BoundedArray(u8, num_bytes),
266268 ) Error!void {
267269 while (bounded.len < num_bytes) {
270 // get at most the number of bytes free in the bounded array
268271 const bytes_read = try self.read(bounded.unusedCapacitySlice());
269272 if (bytes_read == 0) return;
270 bounded.len += bytes_read;
273
274 // bytes_read will never be larger than @TypeOf(bounded.len)
275 // due to `self.read` being bounded by `bounded.unusedCapacitySlice()`
276 bounded.len += @as(@TypeOf(bounded.len), @intCast(bytes_read));
271277 }
272278 }
273279
......@@ -728,3 +734,24 @@ test "Reader.streamUntilDelimiter writes all bytes without delimiter to the outp
728734
729735 try std.testing.expectError(error.StreamTooLong, reader.streamUntilDelimiter(writer, '!', 5));
730736}
737
738test "Reader.readBoundedBytes correctly reads into a new bounded array" {
739 const test_string = "abcdefg";
740 var fis = std.io.fixedBufferStream(test_string);
741 const reader = fis.reader();
742
743 var array = try reader.readBoundedBytes(10000);
744 try testing.expectEqualStrings(array.slice(), test_string);
745}
746
747test "Reader.readIntoBoundedBytes correctly reads into a provided bounded array" {
748 const test_string = "abcdefg";
749 var fis = std.io.fixedBufferStream(test_string);
750 const reader = fis.reader();
751
752 var bounded_array = std.BoundedArray(u8, 10000){};
753
754 // compile time error if the size is not the same at the provided `bounded.capacity()`
755 try reader.readIntoBoundedBytes(10000, &bounded_array);
756 try testing.expectEqualStrings(bounded_array.slice(), test_string);
757}