aboutsummaryrefslogtreecommitdiff
path: root/src/zeroscript/Env/future.zig
blob: a0149900afe9dcb024f868deaebeb8a334601270 (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
const std = @import("std");
const Env = @import("root.zig");
const z = @import("../root.zig");


pub fn Future(comptime kind: Env.Value.Kind) type {
    return struct {
        const Self = @This();

        future: AnyFuture,

        pub fn fromAny(future: AnyFuture) Self {
            return .{ .future = future };
        }

        pub fn await(self: *const Self, env: *Env) !kind.asType() {
            return self.future.await(env, kind);
        }
    };
}

pub const AnyFuture = union(enum) {
    const Self = @This();

    result: *Env.Value,
    err: anyerror,

    pub fn await(self: *const Self, env: *Env, comptime kind: Env.Value.Kind) !kind.asType() {
        const result = try self.awaitAny(env);

        if (kind != result.kind) {
            std.log.err("unexpected {}, expected {}", .{ result.kind, kind });
            @panic("type error");
        }

        return switch (kind) {
            .uninit => @panic("uninitialized result"),
            .string => result.value.string.ptr[0..result.value.string.len],
            else => @field(result.value, @tagName(kind)),
        };
    }

    pub fn awaitAny(self: *const Self, env: *Env) !Env.Value {
        switch (self.*) {
            .err => |err| return err,
            .result => |result| {
                defer env.pool.destroy(result);

                if (result.kind != .uninit) {
                    return result.*;
                }

                env.flush();

                return result.*;
            }
        }
    }
};