Last active
June 7, 2023 14:56
-
-
Save maxsei/d66115136f75be937ac61191bec922f7 to your computer and use it in GitHub Desktop.
zig boolean iterator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const BoolIterator = struct { | |
| bools: []const bool, | |
| cursor: usize = 0, | |
| const Self = @This(); | |
| pub fn next(self: *Self) ?bool { | |
| if (self.cursor < self.bools.len) { | |
| const ret = self.bools[self.cursor]; | |
| self.cursor += 1; | |
| return ret; | |
| } | |
| return null; | |
| } | |
| pub fn reset(self: *Self) void { | |
| self.cursor = 0; | |
| } | |
| }; | |
| /// 1/1 test_0... | |
| /// while (it.next())... | |
| /// 0 true | |
| /// 1 true | |
| /// 2 false | |
| /// 3 true | |
| /// 4 true | |
| /// while (true)... it.next() orelse break | |
| /// 0 true | |
| /// 1 true | |
| /// 2 false | |
| /// 3 true | |
| /// 4 true | |
| /// while (true)... const maybe_val = it.next();... if (maybe_val == null) break; | |
| /// 0 true | |
| /// 1 true | |
| /// 2 false | |
| /// 3 true | |
| /// 4 true | |
| /// OK | |
| /// All 1 tests passed. | |
| test { | |
| var it = BoolIterator{ | |
| .bools = &[_]bool{ true, true, false, true, true }, | |
| }; | |
| std.debug.print("\n", .{}); | |
| std.debug.print("while (it.next())...\n", .{}); | |
| while (it.next()) |val| { | |
| std.debug.print("{} {}\n", .{ it.cursor - 1, val }); | |
| } | |
| it.reset(); | |
| std.debug.print("while (true)... it.next() orelse break\n", .{}); | |
| while (true) { | |
| const val = it.next() orelse break; | |
| std.debug.print("{} {}\n", .{ it.cursor - 1, val }); | |
| } | |
| it.reset(); | |
| std.debug.print("while (true)... const maybe_val = it.next();... if (maybe_val == null) break;\n", .{}); | |
| while (true) { | |
| const maybe_val = it.next(); | |
| if (maybe_val == null) break; | |
| const val = maybe_val.?; | |
| std.debug.print("{} {}\n", .{ it.cursor - 1, val }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment