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 {...@@ -555,7 +555,6 @@ test {
555}555}
556556
557const Io = @This();557const Io = @This();
558const fs = std.fs;
559558
560pub const EventLoop = @import("Io/EventLoop.zig");559pub const EventLoop = @import("Io/EventLoop.zig");
561560
...@@ -613,20 +612,16 @@ pub fn Future(Result: type) type {...@@ -613,20 +612,16 @@ pub fn Future(Result: type) type {
613 };612 };
614}613}
615614
616/// `s` is a struct instance that contains a function like this:615/// Calls `function` with `args`, such that the return value of the function is
617/// ```616/// not guaranteed to be available until `await` is called.
618/// struct {617pub fn async(io: Io, function: anytype, args: anytype) Future(@typeInfo(@TypeOf(function)).@"fn".return_type.?) {
619/// pub fn start(s: S) Result { ... }618 const Result = @typeInfo(@TypeOf(function)).@"fn".return_type.?;
620/// }619 const Args = @TypeOf(args);
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.?;
625 const TypeErased = struct {620 const TypeErased = struct {
626 fn start(context: *const anyopaque, result: *anyopaque) void {621 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));
628 const result_casted: *Result = @ptrCast(@alignCast(result));623 const result_casted: *Result = @ptrCast(@alignCast(result));
629 result_casted.* = S.start(context_casted.*);624 result_casted.* = @call(.auto, function, args_casted.*);
630 }625 }
631 };626 };
632 var future: Future(Result) = undefined;627 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...@@ -634,8 +629,8 @@ pub fn async(io: Io, S: type, s: S) Future(@typeInfo(@TypeOf(S.start)).@"fn".ret
634 io.userdata,629 io.userdata,
635 @ptrCast((&future.result)[0..1]),630 @ptrCast((&future.result)[0..1]),
636 .fromByteUnits(@alignOf(Result)),631 .fromByteUnits(@alignOf(Result)),
637 if (@sizeOf(S) == 0) &.{} else @ptrCast((&s)[0..1]), // work around compiler bug632 if (@sizeOf(Args) == 0) &.{} else @ptrCast((&args)[0..1]), // work around compiler bug
638 .fromByteUnits(@alignOf(S)),633 .fromByteUnits(@alignOf(Args)),
639 TypeErased.start,634 TypeErased.start,
640 );635 );
641 return future;636 return future;