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 {
913913}
914914
915915const Io = @This();
916const fs = std.fs;
917916
918917pub const EventLoop = @import("Io/EventLoop.zig");
919918
......@@ -971,20 +970,16 @@ pub fn Future(Result: type) type {
971970 };
972971}
973972
974/// `s` is a struct instance that contains a function like this:
975/// ```
976/// struct {
977/// pub fn start(s: S) Result { ... }
978/// }
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.?;
973/// Calls `function` with `args`, such that the return value of the function is
974/// not guaranteed to be available until `await` is called.
975pub fn async(io: Io, function: anytype, args: anytype) Future(@typeInfo(@TypeOf(function)).@"fn".return_type.?) {
976 const Result = @typeInfo(@TypeOf(function)).@"fn".return_type.?;
977 const Args = @TypeOf(args);
983978 const TypeErased = struct {
984979 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));
986981 const result_casted: *Result = @ptrCast(@alignCast(result));
987 result_casted.* = S.start(context_casted.*);
982 result_casted.* = @call(.auto, function, args_casted.*);
988983 }
989984 };
990985 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
992987 io.userdata,
993988 @ptrCast((&future.result)[0..1]),
994989 .fromByteUnits(@alignOf(Result)),
995 if (@sizeOf(S) == 0) &.{} else @ptrCast((&s)[0..1]), // work around compiler bug
996 .fromByteUnits(@alignOf(S)),
990 if (@sizeOf(Args) == 0) &.{} else @ptrCast((&args)[0..1]), // work around compiler bug
991 .fromByteUnits(@alignOf(Args)),
997992 TypeErased.start,
998993 );
999994 return future;