From e94f3c4e25de123f5d19efdf2e068f7fd222f07e Mon Sep 17 00:00:00 2001 From: Samadi van Koten Date: Mon, 7 Jun 2021 22:09:53 +0100 Subject: [PATCH] Add std.io.Reader.readUntilDelimiter() --- lib/std/io/reader.zig | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/lib/std/io/reader.zig b/lib/std/io/reader.zig index 920b82e420..0846b14650 100644 --- a/lib/std/io/reader.zig +++ b/lib/std/io/reader.zig @@ -143,6 +143,23 @@ pub fn Reader( return array_list.toOwnedSlice(); } + /// Reads from the stream until specified byte is found. If the buffer is not + /// large enough to hold the entire contents, `error.StreamTooLong` is returned. + /// Returns a slice of the stream data, with ptr equal to `buf.ptr`. The + /// delimiter byte is not included in the returned slice. + pub fn readUntilDelimiter(self: Self, buf: []u8, delimiter: u8) ![]u8 { + var index: usize = 0; + while (true) { + const byte = try self.readByte(); + + if (byte == delimiter) return buf[0..index]; + if (index >= buf.len) return error.StreamTooLong; + + buf[index] = byte; + index += 1; + } + } + /// Allocates enough memory to read until `delimiter` or end-of-stream. /// If the allocated memory would be greater than `max_size`, returns /// `error.StreamTooLong`. If end-of-stream is found, returns the rest