aboutsummaryrefslogtreecommitdiff
path: root/src/zilch/Promise.zig
blob: 09654e31a1235d1f0a64ff9d5de4b8dc54bbc751 (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
const std = @import("std");

const mod = @import("root.zig");
const Env = mod.Env;
const Future = Env.Future;
const Function = Env.Function;
const Object = mod.Object;
const Value = mod.Value;

const Self = @This();

// NOTE: js runs only on one thread, so this is safe,
//       else an allocation would be necessary!
var promise_value: Value = undefined;

pub inline fn then(self: *Self, env: *Env, func: anytype, ud: *anyopaque) Future(void) {
    const wrapper = struct {
        fn wrapper(userdata: *anyopaque) callconv(.c) void {
            const args = @typeInfo(@TypeOf(func)).@"fn".params;

            const value = promise_value.unwrap(args[1].type orelse void);

            func(@alignCast(@ptrCast(userdata)), value) catch |err| {
                std.log.err("{}", .{err});
                @panic("error handling promise");
            };
        }
    }.wrapper;
    return .fromAny(env.call(bindings.then, .{
        self,
        @intFromPtr(&wrapper),
        @intFromPtr(&promise_value),
        @intFromPtr(ud),
    }));
}

pub fn as(self: *Self, T: type) *T {
    return @ptrCast(self);
}

pub const bindings = struct {
    pub const then: Function = .from(
        \\function(promise, func, ptr, ud) {
        \\  promise.then((value) => {
        \\      ObjectStore.writeValue(ptr, value);
        \\      wasm.exports.__indirect_function_table.get(func)(ud);
        \\  })
        \\}
    );
};

pub const functions = [_]Function{
    bindings.then,
};