authorgravatar for samadi@vktec.org.ukSamadi van Koten <samadi@vktec.org.uk> 2021-06-07 22:09:53+01:00
committergravatar for git@vexu.euVeikka Tuominen <git@vexu.eu> 2021-08-20 12:20:42+03:00
loge94f3c4e25de123f5d19efdf2e068f7fd222f07e
tree1dfff7a7218026c01b8772f519c245bd479e57af
parent8c39ab2659a2bdc741c0ce51014977fb9bebe2ab

Add std.io.Reader.readUntilDelimiter()


1 files changed, 17 insertions(+), 0 deletions(-)

lib/std/io/reader.zig+17
...@@ -143,6 +143,23 @@ pub fn Reader(...@@ -143,6 +143,23 @@ pub fn Reader(
143 return array_list.toOwnedSlice();143 return array_list.toOwnedSlice();
144 }144 }
145145
146 /// Reads from the stream until specified byte is found. If the buffer is not
147 /// large enough to hold the entire contents, `error.StreamTooLong` is returned.
148 /// Returns a slice of the stream data, with ptr equal to `buf.ptr`. The
149 /// delimiter byte is not included in the returned slice.
150 pub fn readUntilDelimiter(self: Self, buf: []u8, delimiter: u8) ![]u8 {
151 var index: usize = 0;
152 while (true) {
153 const byte = try self.readByte();
154
155 if (byte == delimiter) return buf[0..index];
156 if (index >= buf.len) return error.StreamTooLong;
157
158 buf[index] = byte;
159 index += 1;
160 }
161 }
162
146 /// Allocates enough memory to read until `delimiter` or end-of-stream.163 /// Allocates enough memory to read until `delimiter` or end-of-stream.
147 /// If the allocated memory would be greater than `max_size`, returns164 /// If the allocated memory would be greater than `max_size`, returns
148 /// `error.StreamTooLong`. If end-of-stream is found, returns the rest165 /// `error.StreamTooLong`. If end-of-stream is found, returns the rest