Skip to content

Commit cd0594e

Browse files
authored
std: add mem.SplitIterator.peek() (#15670)
1 parent cc56ab8 commit cd0594e

File tree

1 file changed

+16
-0
lines changed

1 file changed

+16
-0
lines changed

lib/std/mem.zig

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2241,15 +2241,18 @@ test "splitScalar" {
22412241
try testing.expectEqualSlices(u8, it.first(), "abc");
22422242

22432243
try testing.expectEqualSlices(u8, it.rest(), "def||ghi");
2244+
try testing.expectEqualSlices(u8, it.peek().?, "def");
22442245
try testing.expectEqualSlices(u8, it.next().?, "def");
22452246

22462247
try testing.expectEqualSlices(u8, it.rest(), "|ghi");
22472248
try testing.expectEqualSlices(u8, it.next().?, "");
22482249

22492250
try testing.expectEqualSlices(u8, it.rest(), "ghi");
2251+
try testing.expectEqualSlices(u8, it.peek().?, "ghi");
22502252
try testing.expectEqualSlices(u8, it.next().?, "ghi");
22512253

22522254
try testing.expectEqualSlices(u8, it.rest(), "");
2255+
try testing.expect(it.peek() == null);
22532256
try testing.expect(it.next() == null);
22542257

22552258
it = splitScalar(u8, "", '|');
@@ -2259,6 +2262,7 @@ test "splitScalar" {
22592262
it = splitScalar(u8, "|", '|');
22602263
try testing.expectEqualSlices(u8, it.first(), "");
22612264
try testing.expectEqualSlices(u8, it.next().?, "");
2265+
try testing.expect(it.peek() == null);
22622266
try testing.expect(it.next() == null);
22632267

22642268
it = splitScalar(u8, "hello", ' ');
@@ -2865,6 +2869,18 @@ pub fn SplitIterator(comptime T: type, comptime delimiter_type: DelimiterType) t
28652869
return self.buffer[start..end];
28662870
}
28672871

2872+
/// Returns a slice of the next field, or null if splitting is complete.
2873+
/// This method does not alter self.index.
2874+
pub fn peek(self: *Self) ?[]const T {
2875+
const start = self.index orelse return null;
2876+
const end = if (switch (delimiter_type) {
2877+
.sequence => indexOfPos(T, self.buffer, start, self.delimiter),
2878+
.any => indexOfAnyPos(T, self.buffer, start, self.delimiter),
2879+
.scalar => indexOfScalarPos(T, self.buffer, start, self.delimiter),
2880+
}) |delim_start| delim_start else self.buffer.len;
2881+
return self.buffer[start..end];
2882+
}
2883+
28682884
/// Returns a slice of the remaining bytes. Does not affect iterator state.
28692885
pub fn rest(self: Self) []const T {
28702886
const end = self.buffer.len;

0 commit comments

Comments
 (0)