|
| 1 | +/// References: |
| 2 | +/// https://github.com/thi-ng/umbrella/tree/develop/deprecated/packages/iterators |
| 3 | +/// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_generators |
| 4 | +/// https://github.com/ghostty-org/ghostty/blob/main/src/synthetic/Generator.zig |
| 5 | +const std = @import("std"); |
| 6 | +const assert = std.debug.assert; |
| 7 | + |
| 8 | +pub const GeneratorError = error{ |
| 9 | + NoSpaceLeft, |
| 10 | +}; |
| 11 | + |
| 12 | +fn Generator(comptime T: type, next_fn: fn () T) type { |
| 13 | + return struct { |
| 14 | + done: bool = false, |
| 15 | + |
| 16 | + pub fn next() T { |
| 17 | + return next_fn(); |
| 18 | + } |
| 19 | + }; |
| 20 | +} |
| 21 | + |
| 22 | +const UrlGenerator = struct { |
| 23 | + const list_of_urls = [_][]const u8{ |
| 24 | + "https://ziglang.org", |
| 25 | + "https://zig.news", |
| 26 | + "https://github.com", |
| 27 | + }; |
| 28 | + |
| 29 | + pub fn init() type { |
| 30 | + return Generator( |
| 31 | + @TypeOf(list_of_urls[0]), |
| 32 | + struct { |
| 33 | + var i: usize = 0; |
| 34 | + const rng_gen = std.Random.DefaultPrng; |
| 35 | + var rng: std.Random.Xoshiro256 = rng_gen.init(0); |
| 36 | + const random = rng.random(); |
| 37 | + |
| 38 | + pub fn next_fn() []const u8 { |
| 39 | + while (true) { |
| 40 | + // if (i >= list_of_urls.len - 1) { |
| 41 | + // i = @mod(i + 1, list_of_urls.len); |
| 42 | + // } else { |
| 43 | + // i += 1; |
| 44 | + // } |
| 45 | + i = random.intRangeAtMost(usize, 0, list_of_urls.len - 1); |
| 46 | + return list_of_urls[i]; |
| 47 | + } |
| 48 | + } |
| 49 | + }.next_fn, |
| 50 | + ); |
| 51 | + } |
| 52 | +}; |
| 53 | + |
| 54 | +const FibonacciGenerator = struct { |
| 55 | + pub fn init(start: usize) type { |
| 56 | + return Generator(usize, struct { |
| 57 | + var num_a: usize = start; |
| 58 | + var num_b: usize = start + 1; |
| 59 | + |
| 60 | + pub fn next_fn() usize { |
| 61 | + std.debug.assert(num_a + num_b < std.math.maxInt(usize)); |
| 62 | + const result = num_a + num_b; |
| 63 | + num_b = num_a; |
| 64 | + num_a = result; |
| 65 | + return result; |
| 66 | + } |
| 67 | + }.next_fn); |
| 68 | + } |
| 69 | +}; |
| 70 | + |
| 71 | +pub fn main() !void { |
| 72 | + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; |
| 73 | + const allocator = gpa.allocator(); |
| 74 | + |
| 75 | + const url_it = UrlGenerator.init(); |
| 76 | + const fib_it = FibonacciGenerator.init(0); |
| 77 | + while (true) { |
| 78 | + std.debug.print("Next URL:\n → {s}\n", .{url_it.next()}); |
| 79 | + std.debug.print("Fibonnacci:\n → {d}\n", .{fib_it.next()}); |
| 80 | + |
| 81 | + const in = std.io.getStdIn(); |
| 82 | + var buf = std.io.bufferedReader(in.reader()); |
| 83 | + |
| 84 | + var r = buf.reader(); |
| 85 | + const msg_buf: []u8 = try allocator.alloc(u8, 10); |
| 86 | + _ = try r.readUntilDelimiter(msg_buf, '\n'); |
| 87 | + } |
| 88 | +} |
0 commit comments