diff options
author | Johannes Stoelp <johannes.stoelp@gmail.com> | 2024-12-18 23:13:12 +0100 |
---|---|---|
committer | Johannes Stoelp <johannes.stoelp@gmail.com> | 2024-12-18 23:13:12 +0100 |
commit | 42b6f9d23ab0f94744a90edb6fd74450f589ca14 (patch) | |
tree | e9a0b465eadc33570b412446475eb1a96d453f9d | |
parent | 3fbe24e6cde0e423f603c41ec06da736bf1a275b (diff) | |
download | zig-playground-main.tar.gz zig-playground-main.zip |
-rw-r--r-- | example-interface/Makefile | 2 | ||||
-rw-r--r-- | example-interface/main.zig | 45 |
2 files changed, 47 insertions, 0 deletions
diff --git a/example-interface/Makefile b/example-interface/Makefile new file mode 100644 index 0000000..6576ece --- /dev/null +++ b/example-interface/Makefile @@ -0,0 +1,2 @@ +run: + zig run main.zig diff --git a/example-interface/main.zig b/example-interface/main.zig new file mode 100644 index 0000000..085aa82 --- /dev/null +++ b/example-interface/main.zig @@ -0,0 +1,45 @@ +const std = @import("std"); + +/// Interface type, holding a pointer to the object and the interface function pointers. +const Iter = struct { + ptr: *anyopaque, + next_fn: *const fn (*anyopaque) ?i32, + + /// Convenience wrapper to call vtable function. + pub fn next(self: Iter) ?i32 { + return self.next_fn(self.ptr); + } +}; + +const UpIter = struct { + end: i32, + now: i32 = 0, + + /// Create an Inter interface object from UpIter. + pub fn iter(self: *UpIter) Iter { + return Iter{ .ptr = self, .next_fn = next }; + } + + pub fn next(ptr: *anyopaque) ?i32 { + const self: *UpIter = @alignCast(@ptrCast(ptr)); + if (self.now < self.end) { + self.now += 1; + return self.now; + } else { + return null; + } + } +}; + +/// Function example taking an Iter interface object. +fn run_iter(iter: Iter) void { + while (iter.next()) |v| { + std.debug.print("{},", .{v}); + } + std.debug.print("\n", .{}); +} + +pub fn main() void { + var uit = UpIter{ .end = 10 }; + run_iter(uit.iter()); +} |