| ... | ... | @@ -257,17 +257,23 @@ pub fn Reader( |
| 257 | 257 | return bytes; |
| 258 | 258 | } |
| 259 | 259 | |
| 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()` |
| 262 | 264 | pub fn readIntoBoundedBytes( |
| 263 | 265 | self: Self, |
| 264 | 266 | comptime num_bytes: usize, |
| 265 | 267 | bounded: *std.BoundedArray(u8, num_bytes), |
| 266 | 268 | ) Error!void { |
| 267 | 269 | while (bounded.len < num_bytes) { |
| 270 | // get at most the number of bytes free in the bounded array |
| 268 | 271 | const bytes_read = try self.read(bounded.unusedCapacitySlice()); |
| 269 | 272 | 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)); |
| 271 | 277 | } |
| 272 | 278 | } |
| 273 | 279 | |
| ... | ... | @@ -728,3 +734,24 @@ test "Reader.streamUntilDelimiter writes all bytes without delimiter to the outp |
| 728 | 734 | |
| 729 | 735 | try std.testing.expectError(error.StreamTooLong, reader.streamUntilDelimiter(writer, '!', 5)); |
| 730 | 736 | } |
| 737 | |
| 738 | test "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 | |
| 747 | test "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 | } |