summaryrefslogtreecommitdiff
path: root/example-interface/main.zig
blob: 085aa828ce0d125b4c436d7dff9d6a73a7237e96 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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());
}