aboutsummaryrefslogtreecommitdiff
path: root/src/object.zig
blob: 5b7726e55cb7e0cf6c1e10074344f64314f199ff (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
const std = @import("std");
const wayland = @import("root.zig");

const Self = @This();

pub const Ref = struct {
    id: u32,

    pub const display: @This() = .{
        .id = 1,
    };

    pub const registry: @This() = .{
        .id = 2,
    };
};

const VTable = struct {
    on_event: *const fn (
        ptr: *anyopaque,
        ctx: *const wayland.Context,
        opcode: u16,
        args: []const u8,
    ) void,
};

ptr: ?*anyopaque,
vtable: VTable,
name: []const u8,

pub inline fn on_event(
    self: *Self,
    ctx: *const wayland.Context,
    opcode: u16,
    args: []const u8,
) !void {
    if (self.ptr) |ptr| {
        self.vtable.on_event(ptr, ctx, opcode, args);
    } else {
        return error.UseAfterRelease;
    }
}

pub inline fn from_self(ptr: anytype) Self {
    const T = @TypeOf(ptr.*);

    return .{
        .ptr = ptr,
        .vtable = VTable{
            .on_event = T.Events.on_event,
        },
        .name = @typeName(T),
    };
}

pub fn disable(self: *Self) void {
    self.ptr = null;
}

pub fn format(
    self: *const Self,
    comptime fmt: []const u8,
    options: std.fmt.FormatOptions,
    writer: anytype,
) !void {
    _ = fmt;
    _ = options;

    try writer.print("Object<{s}> {{ {?} }}", .{self.name, self.ptr});
}