-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPollable.zig
More file actions
47 lines (44 loc) · 1.54 KB
/
Copy pathPollable.zig
File metadata and controls
47 lines (44 loc) · 1.54 KB
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
const std = @import("std");
const Pollable = @This();
runFn: *const fn (*Pollable, Operation) ?Status,
pub const Operation = enum {
run,
query_status,
destroy,
};
pub const Status = enum {
ready,
done,
};
pub fn create(comptime func: anytype, args: std.meta.ArgsTuple(@TypeOf(func)), allocator: std.mem.Allocator) !Pollable {
std.debug.assert(@typeInfo(func).@"fn".return_type.? == Status);
const Closure = struct {
arguments: @TypeOf(args),
allocator: std.mem.Allocator,
status: Status = .ready,
runnable: Pollable = .{ .runFn = runFn },
fn runFn(runnable: *Pollable, operation: Operation) ?Status {
const closure: *@This() = @alignCast(@fieldParentPtr("runnable", runnable));
return switch (operation) {
.run => switch (closure.status) {
.ready => blk: {
closure.status = @call(.auto, func, closure.arguments);
break :blk closure.status;
},
.done => .done,
},
.query_status => closure.status,
.destroy => blk: {
closure.allocator.destroy(closure);
break :blk null;
},
};
}
};
const closure = try allocator.create(Closure);
closure.* = .{ .arguments = args, .allocator = allocator };
return &closure.runnable;
}
pub fn operate(self: *Pollable, operation: Operation) ?Status {
return self.runFn(self, operation);
}