| ... | @@ -323,13 +323,24 @@ pub fn Deque(comptime T: type) type { | ... | @@ -323,13 +323,24 @@ pub fn Deque(comptime T: type) type { |
| 323 | deque: *const Self, | 323 | deque: *const Self, |
| 324 | index: usize, | 324 | index: usize, |
| 325 | | 325 | |
| | 326 | pub fn peek(it: Iterator) ?T { |
| | 327 | if (it.index >= it.deque.len) return null; |
| | 328 | return it.deque.at(it.index); |
| | 329 | } |
| 326 | pub fn next(it: *Iterator) ?T { | 330 | pub fn next(it: *Iterator) ?T { |
| 327 | if (it.index < it.deque.len) { | 331 | const item = it.peek() orelse return null; |
| 328 | defer it.index += 1; | 332 | it.index += 1; |
| 329 | return it.deque.at(it.index); | 333 | return item; |
| 330 | } else { | 334 | } |
| 331 | return null; | 335 | |
| 332 | } | 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; |
| 333 | } | 344 | } |
| 334 | }; | 345 | }; |
| 335 | | 346 | |
| ... | @@ -469,6 +480,40 @@ test "slice" { | ... | @@ -469,6 +480,40 @@ test "slice" { |
| 469 | try testing.expectEqual(null, q.popBack()); | 480 | try testing.expectEqual(null, q.popBack()); |
| 470 | } | 481 | } |
| 471 | | 482 | |
| | 483 | test "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 | |
| 472 | test "fuzz against ArrayList oracle" { | 517 | test "fuzz against ArrayList oracle" { |
| 473 | try std.testing.fuzz({}, fuzzAgainstArrayList, .{}); | 518 | try std.testing.fuzz({}, fuzzAgainstArrayList, .{}); |
| 474 | } | 519 | } |