Last active
April 10, 2025 08:29
-
-
Save helgeholm/64399117c68014b5d2fc96e4e8f30885 to your computer and use it in GitHub Desktop.
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 std = @import("std"); | |
const IteratorTypes = struct { | |
eyeThirtyTwos: ?type = null, | |
eweFifteens: ?type = null, | |
}; | |
fn Serializer(it: IteratorTypes) type { | |
const EyeThirtyTwosIterator = it.eyeThirtyTwos orelse DefaultIterator(i32); | |
const EweFifteensIterator = it.eweFifteens orelse DefaultIterator(u15); | |
return struct { | |
name: []const u8, | |
eyeThirtyTwos: EyeThirtyTwosIterator = .{}, | |
eweFifteens: EweFifteensIterator = .{}, | |
pub fn exist(self: *@This()) void { | |
std.debug.print("{s} existing\n", .{self.name}); | |
} | |
pub fn serialize(self: *@This()) void { | |
std.debug.print("= {s}\n", .{self.name}); | |
std.debug.print("== eyeThirtyTwos\n", .{}); | |
while (self.eyeThirtyTwos.next()) |n| | |
std.debug.print("- {d}\n", .{n}); | |
std.debug.print("== eweFifteens\n", .{}); | |
while (self.eweFifteens.next()) |n| | |
std.debug.print("- {d}\n", .{n}); | |
std.debug.print(":)\n", .{}); | |
} | |
}; | |
} | |
fn DefaultIterator(comptime T: type) type { | |
return struct { | |
pub fn next(_: *@This()) ?T { | |
@compileError("not defined"); | |
} | |
}; | |
} | |
test "simple" { | |
std.debug.print("\n\n DEFAULT INIT\n", .{}); | |
var s = Serializer(.{}){ | |
.name = "Default Bunny", | |
}; | |
s.exist(); | |
} | |
test "u15 iterator inject" { | |
std.debug.print("\n\n INIT WITH MY OWN ITERATOT TYPE\n", .{}); | |
var s = Serializer(.{ | |
.eweFifteens = MyU15Generator, | |
.eyeThirtyTwos = MyI32Generator, | |
}){ | |
.name = "Bunny with Some Numbers", | |
}; | |
s.serialize(); | |
std.debug.print("\n ...AND AGAIN WITH INJECTED ITERATOR\n", .{}); | |
s.eweFifteens = MyU15Generator{ .countdown = 3 }; | |
s.eyeThirtyTwos = MyI32Generator{ .countdown = 5 }; | |
s.serialize(); | |
} | |
const MyU15Generator = struct { | |
countdown: u15 = 0, | |
pub fn next(self: *@This()) ?u15 { | |
if (self.countdown == 0) return null; | |
defer self.countdown -= 1; | |
return self.countdown; | |
} | |
}; | |
const MyI32Generator = struct { | |
countdown: i32 = 0, | |
pub fn next(self: *@This()) ?i32 { | |
if (self.countdown < 0) return null; | |
defer self.countdown -= 2; | |
return self.countdown; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment