aboutsummaryrefslogtreecommitdiff
path: root/src/frontend/io_interface.zig
blob: a2aa0ca9689a990f995c0ccfdb6c3d59a92ea87c (plain)
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
46
47
48
49
50
const std = @import("std");
const Action = @import("../actions.zig").Action;

pub const IOInterface = struct {
    ptr: *anyopaque,
    displayMessageFn: *const fn (ptr: *anyopaque, str: []const u8) anyerror!void,
    waitForTickFn: *const fn (ptr: *anyopaque) anyerror!Action,
    deinitFn: *const fn (ptr: *anyopaque) void,

    pub fn init(ptr: anytype) !IOInterface {
        const T = @TypeOf(ptr);
        const ptr_info = @typeInfo(T);

        const gen = struct {
            pub fn displayMessage(pointer: *anyopaque, str: []const u8) anyerror!void {
                const self: T = @ptrCast(@alignCast(pointer));
                return ptr_info.Pointer.child.displayMessage(self, str);
            }

            pub fn waitForTick(pointer: *anyopaque) anyerror!Action {
                const self: T = @ptrCast(@alignCast(pointer));
                return ptr_info.Pointer.child.waitForTick(self);
            }

            pub fn deinit(pointer: *anyopaque) void {
                const self: T = @ptrCast(@alignCast(pointer));
                return ptr_info.Pointer.child.deinit(self);
            }
        };

        return .{
            .ptr = ptr,
            .displayMessageFn = gen.displayMessage,
            .waitForTickFn = gen.waitForTick,
            .deinitFn = gen.deinit,
        };
    }

    pub fn displayMessage(self: IOInterface, str: []const u8) anyerror!void {
        return self.displayMessageFn(self.ptr, str);
    }

    pub fn waitForTick(self: IOInterface) anyerror!Action {
        return self.waitForTickFn(self.ptr);
    }

    pub fn deinit(self: IOInterface) void {
        return self.deinitFn(self.ptr);
    }
};