authorgravatar for justus@klausecker.deJustus Klausecker <justus@klausecker.de> 2026-02-11 08:29:30+01:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2026-02-12 21:45:13-08:00
log623723507f7f307ac888ce483b422bde7da9984b
tree5a0bd0ebdbb0e2979884e3db1eb67afc319d9fd8
parent527e97b25201a1a252bcff6d79198513babda2db

std.Deque: add `peek` and `*Ptr` functions to `Iterator`

The iterator should be as powerful as manual access via `as` and `asPtr` to justify its existence.

1 files changed, 51 insertions(+), 6 deletions(-)

lib/std/deque.zig+51-6
......@@ -323,13 +323,24 @@ pub fn Deque(comptime T: type) type {
323323 deque: *const Self,
324324 index: usize,
325325
326 pub fn peek(it: Iterator) ?T {
327 if (it.index >= it.deque.len) return null;
328 return it.deque.at(it.index);
329 }
326330 pub fn next(it: *Iterator) ?T {
327 if (it.index < it.deque.len) {
328 defer it.index += 1;
329 return it.deque.at(it.index);
330 } else {
331 return null;
332 }
331 const item = it.peek() orelse return null;
332 it.index += 1;
333 return item;
334 }
335
336 pub fn peekPtr(it: Iterator) ?*T {
337 if (it.index >= it.deque.len) return null;
338 return it.deque.atPtr(it.index);
339 }
340 pub fn nextPtr(it: *Iterator) ?*T {
341 const item_ptr = it.peekPtr() orelse return null;
342 it.index += 1;
343 return item_ptr;
333344 }
334345 };
335346
......@@ -469,6 +480,40 @@ test "slice" {
469480 try testing.expectEqual(null, q.popBack());
470481}
471482
483test "iterator" {
484 const testing = std.testing;
485 const gpa = testing.allocator;
486
487 var q: Deque(i32) = .empty;
488 defer q.deinit(gpa);
489
490 const items: []const i32 = &.{ 0, 1, 2, 3, 4, 5 };
491 try q.pushFrontSlice(gpa, items);
492
493 {
494 var it = q.iterator();
495 for (items) |item| {
496 try testing.expectEqual(item, it.peek());
497 try testing.expectEqual(item, it.next());
498 }
499 try testing.expectEqual(null, it.peek());
500 try testing.expectEqual(null, it.next());
501 }
502 {
503 var it = q.iterator();
504 for (items) |item| {
505 if (it.peekPtr()) |ptr| {
506 try testing.expectEqual(item, ptr.*);
507 } else return error.TextExpectedNonNull;
508 if (it.nextPtr()) |ptr| {
509 try testing.expectEqual(item, ptr.*);
510 } else return error.TextExpectedNonNull;
511 }
512 try testing.expectEqual(null, it.peekPtr());
513 try testing.expectEqual(null, it.nextPtr());
514 }
515}
516
472517test "fuzz against ArrayList oracle" {
473518 try std.testing.fuzz({}, fuzzAgainstArrayList, .{});
474519}