authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-03-29 15:22:00-07:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2025-10-02 16:30:59-07:00
log79e278f6a26467ea7788ae14267000517d91f1ac
tree0ad50cb6b50a3df544be110d86020ef141732d1a
parent708bac1a57e6cf8f9e3709ab25fac1ccbaa31520

better API for Io.async


1 files changed, 9 insertions(+), 14 deletions(-)

lib/std/Io.zig+9-14
......@@ -555,7 +555,6 @@ test {
555555}
556556
557557const Io = @This();
558const fs = std.fs;
559558
560559pub const EventLoop = @import("Io/EventLoop.zig");
561560
......@@ -613,20 +612,16 @@ pub fn Future(Result: type) type {
613612 };
614613}
615614
616/// `s` is a struct instance that contains a function like this:
617/// ```
618/// struct {
619/// pub fn start(s: S) Result { ... }
620/// }
621/// ```
622/// where `Result` is any type.
623pub fn async(io: Io, S: type, s: S) Future(@typeInfo(@TypeOf(S.start)).@"fn".return_type.?) {
624 const Result = @typeInfo(@TypeOf(S.start)).@"fn".return_type.?;
615/// Calls `function` with `args`, such that the return value of the function is
616/// not guaranteed to be available until `await` is called.
617pub fn async(io: Io, function: anytype, args: anytype) Future(@typeInfo(@TypeOf(function)).@"fn".return_type.?) {
618 const Result = @typeInfo(@TypeOf(function)).@"fn".return_type.?;
619 const Args = @TypeOf(args);
625620 const TypeErased = struct {
626621 fn start(context: *const anyopaque, result: *anyopaque) void {
627 const context_casted: *const S = @alignCast(@ptrCast(context));
622 const args_casted: *const Args = @alignCast(@ptrCast(context));
628623 const result_casted: *Result = @ptrCast(@alignCast(result));
629 result_casted.* = S.start(context_casted.*);
624 result_casted.* = @call(.auto, function, args_casted.*);
630625 }
631626 };
632627 var future: Future(Result) = undefined;
......@@ -634,8 +629,8 @@ pub fn async(io: Io, S: type, s: S) Future(@typeInfo(@TypeOf(S.start)).@"fn".ret
634629 io.userdata,
635630 @ptrCast((&future.result)[0..1]),
636631 .fromByteUnits(@alignOf(Result)),
637 if (@sizeOf(S) == 0) &.{} else @ptrCast((&s)[0..1]), // work around compiler bug
638 .fromByteUnits(@alignOf(S)),
632 if (@sizeOf(Args) == 0) &.{} else @ptrCast((&args)[0..1]), // work around compiler bug
633 .fromByteUnits(@alignOf(Args)),
639634 TypeErased.start,
640635 );
641636 return future;