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-07-20 10:38:38-07:00
logdab5dd286f289510985802d4cc5954227232ac44
tree9698d502ce5b727d0b75fdf9e0df4b11c9fbc86e
parent90cc7f4adf62e0c95af9b19cde880f05893fcc67

better API for Io.async


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

lib/std/Io.zig+9-14
...@@ -913,7 +913,6 @@ test {...@@ -913,7 +913,6 @@ test {
913}913}
914914
915const Io = @This();915const Io = @This();
916const fs = std.fs;
917916
918pub const EventLoop = @import("Io/EventLoop.zig");917pub const EventLoop = @import("Io/EventLoop.zig");
919918
...@@ -971,20 +970,16 @@ pub fn Future(Result: type) type {...@@ -971,20 +970,16 @@ pub fn Future(Result: type) type {
971 };970 };
972}971}
973972
974/// `s` is a struct instance that contains a function like this:973/// Calls `function` with `args`, such that the return value of the function is
975/// ```974/// not guaranteed to be available until `await` is called.
976/// struct {975pub fn async(io: Io, function: anytype, args: anytype) Future(@typeInfo(@TypeOf(function)).@"fn".return_type.?) {
977/// pub fn start(s: S) Result { ... }976 const Result = @typeInfo(@TypeOf(function)).@"fn".return_type.?;
978/// }977 const Args = @TypeOf(args);
979/// ```
980/// where `Result` is any type.
981pub fn async(io: Io, S: type, s: S) Future(@typeInfo(@TypeOf(S.start)).@"fn".return_type.?) {
982 const Result = @typeInfo(@TypeOf(S.start)).@"fn".return_type.?;
983 const TypeErased = struct {978 const TypeErased = struct {
984 fn start(context: *const anyopaque, result: *anyopaque) void {979 fn start(context: *const anyopaque, result: *anyopaque) void {
985 const context_casted: *const S = @alignCast(@ptrCast(context));980 const args_casted: *const Args = @alignCast(@ptrCast(context));
986 const result_casted: *Result = @ptrCast(@alignCast(result));981 const result_casted: *Result = @ptrCast(@alignCast(result));
987 result_casted.* = S.start(context_casted.*);982 result_casted.* = @call(.auto, function, args_casted.*);
988 }983 }
989 };984 };
990 var future: Future(Result) = undefined;985 var future: Future(Result) = undefined;
...@@ -992,8 +987,8 @@ pub fn async(io: Io, S: type, s: S) Future(@typeInfo(@TypeOf(S.start)).@"fn".ret...@@ -992,8 +987,8 @@ pub fn async(io: Io, S: type, s: S) Future(@typeInfo(@TypeOf(S.start)).@"fn".ret
992 io.userdata,987 io.userdata,
993 @ptrCast((&future.result)[0..1]),988 @ptrCast((&future.result)[0..1]),
994 .fromByteUnits(@alignOf(Result)),989 .fromByteUnits(@alignOf(Result)),
995 if (@sizeOf(S) == 0) &.{} else @ptrCast((&s)[0..1]), // work around compiler bug990 if (@sizeOf(Args) == 0) &.{} else @ptrCast((&args)[0..1]), // work around compiler bug
996 .fromByteUnits(@alignOf(S)),991 .fromByteUnits(@alignOf(Args)),
997 TypeErased.start,992 TypeErased.start,
998 );993 );
999 return future;994 return future;