| ... | ... | @@ -323,13 +323,24 @@ pub fn Deque(comptime T: type) type { |
| 323 | 323 | deque: *const Self, |
| 324 | 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 | 330 | 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; |
| 333 | 344 | } |
| 334 | 345 | }; |
| 335 | 346 | |
| ... | ... | @@ -469,6 +480,40 @@ test "slice" { |
| 469 | 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 | 517 | test "fuzz against ArrayList oracle" { |
| 473 | 518 | try std.testing.fuzz({}, fuzzAgainstArrayList, .{}); |
| 474 | 519 | } |