跳转到内容
标准库Zig 0.17.0官方原文
源码std/Io/Kqueue.zig

第 1 行

字段

gpa: Allocator

必须使用线程安全的分配器。

mutex: Io.Mutex
main_fiber_buffer: [@sizeOf(Fiber) + Fiber.max_result_size]u8 align(@alignOf(Fiber))
threads: Thread.List

std.Io.Kqueue.Alignment

别名

第 11 行

别名目标 std.mem.Alignment

std.Io.Kqueue.Allocator

别名

第 10 行

别名目标 std.mem.Allocator

std.Io.Kqueue.assert

别名

第 9 行

别名目标 std.debug.assert

std.Io.Kqueue.async

函数

第 664 行

fn async( userdata: ?*anyopaque, result: []u8, result_alignment: std.mem.Alignment, context: []const u8, context_alignment: std.mem.Alignment, start: *const fn (context: *const anyopaque, result: *anyopaque) void, ) ?*Io.AnyFuture

参数

userdata: ?*anyopaque
result: []u8
result_alignment: std.mem.Alignment
context: []const u8
context_alignment: std.mem.Alignment
start: *const fn (context: *const anyopaque, result: *anyopaque) void

std.Io.Kqueue.AsyncClosure

容器

第 577 行

字段

kqueue: *Kqueue
fiber: *Fiber
start: *const fn (context: *const anyopaque, result: *anyopaque) void
result_align: Alignment
already_awaited: bool

std.Io.Kqueue.AsyncClosure.call

函数

第 588 行

fn call(closure: *AsyncClosure, message: *const SwitchMessage) callconv(.withStackAlign(.c, @alignOf(AsyncClosure))) noreturn

参数

closure: *AsyncClosure
message: *const SwitchMessage

std.Io.Kqueue.AsyncClosure.contextPointer

函数

第 584 行

fn contextPointer(closure: *AsyncClosure) [*]align(Fiber.max_context_align.toByteUnits()) u8

参数

closure: *AsyncClosure

std.Io.Kqueue.AsyncClosure.fromFiber

函数

第 603 行

fn fromFiber(fiber: *Fiber) *AsyncClosure

参数

fiber: *Fiber

std.Io.Kqueue.await

函数

第 729 行

fn await( userdata: ?*anyopaque, any_future: *Io.AnyFuture, result: []u8, result_alignment: std.mem.Alignment, ) void

参数

userdata: ?*anyopaque
any_future: *Io.AnyFuture
result: []u8
result_alignment: std.mem.Alignment

std.Io.Kqueue.builtin

常量

第 2 行

std.Io.Kqueue.cancel

函数

第 743 行

fn cancel( userdata: ?*anyopaque, any_future: *Io.AnyFuture, result: []u8, result_alignment: std.mem.Alignment, ) void

参数

userdata: ?*anyopaque
any_future: *Io.AnyFuture
result: []u8
result_alignment: std.mem.Alignment

std.Io.Kqueue.cancelRequested

函数

第 757 行

fn cancelRequested(userdata: ?*anyopaque) bool

参数

userdata: ?*anyopaque

std.Io.Kqueue.changes_buffer_len

常量

第 31 行

std.Io.Kqueue.checkCancel

函数

第 1456 行

fn checkCancel(k: *Kqueue) error{Canceled}!void

参数

k: *Kqueue

错误

Canceled

std.Io.Kqueue.closeFd

别名

第 14 行

别名目标 std.Io.Threaded.closeFd

std.Io.Kqueue.Completion

容器

第 412 行

字段

flags: u16

对应 Kevent 字段。

fflags: u32

对应 Kevent 字段。

data: isize

对应 Kevent 字段。

std.Io.Kqueue.Completion.UserData

容器

第 413 行

字段

unused
wakeup
cleanup
exit
_

*Fiber

std.Io.Kqueue.concurrent

函数

第 678 行

fn concurrent( userdata: ?*anyopaque, result_len: usize, result_alignment: Alignment, context: []const u8, context_alignment: Alignment, start: *const fn (context: *const anyopaque, result: *anyopaque) void, ) Io.ConcurrentError!*Io.AnyFuture

参数

userdata: ?*anyopaque
result_len: usize
result_alignment: Alignment
context: []const u8
context_alignment: Alignment
start: *const fn (context: *const anyopaque, result: *anyopaque) void

错误

ConcurrencyUnavailable

可能由资源耗尽等临时情况引起,也可能因为 Io 实现不支持并发。

std.Io.Kqueue.contextSwitch

函数

第 537 行

inline fn contextSwitch(message: *const SwitchMessage) *const SwitchMessage

参数

message: *const SwitchMessage

std.Io.Kqueue.createFileDescriptor

函数

第 246 行

pub fn createFileDescriptor() CreateFileDescriptorError!posix.fd_t

错误

ProcessFdQuotaExceeded

已达到每个进程可打开的文件描述符数量限制。

SystemFdQuotaExceeded

已达到系统范围内打开文件总数的上限。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.Io.Kqueue.CreateFileDescriptorError

错误集合

第 239 行

错误

ProcessFdQuotaExceeded

已达到每个进程可打开的文件描述符数量限制。

SystemFdQuotaExceeded

已达到系统范围内打开文件总数的上限。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.Io.Kqueue.deinit

函数

第 222 行

pub fn deinit(k: *Kqueue) void

参数

k: *Kqueue

std.Io.Kqueue.Dir

别名

第 6 行

别名目标 std.Io.Dir

std.Io.Kqueue.dirAccess

函数

第 870 行

fn dirAccess(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.AccessOptions) Dir.AccessError!void

参数

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
options: Dir.AccessOptions

错误

AccessDenied

文件不允许请求的 AccessOptions,或路径前缀中的 某个目录不允许搜索。

BadPathName PathNameError

文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。

Canceled Cancelable

调用方请求停止异步操作。

FileBusy
FileNotFound
InputOutput
NameTooLong PathNameError

提供的缓冲区过小, 无法容纳路径名时返回。

PermissionDenied

请求了写入权限,但文件不可变。

ReadOnlyFileSystem
SymLinkLoop
SystemResources
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.Io.Kqueue.dirClose

函数

第 902 行

fn dirClose(userdata: ?*anyopaque, dirs: []const Dir) void

参数

userdata: ?*anyopaque
dirs: []const Dir

std.Io.Kqueue.dirCreateDir

函数

第 811 行

fn dirCreateDir(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions) Dir.CreateDirError!void

参数

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
permissions: Dir.Permissions

错误

AccessDenied

在 WASI 中,当文件描述符不具备相对于自身 创建新目录所需的权限时,可能发生此错误。

BadPathName PathNameError

文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。

Canceled Cancelable

调用方请求停止异步操作。

DiskQuota
FileNotFound
LinkQuotaExceeded
NameTooLong PathNameError

提供的缓冲区过小, 无法容纳路径名时返回。

NetworkNotFound

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice
NoSpaceLeft
NotDir
PathAlreadyExists
PermissionDenied
ReadOnlyFileSystem
SymLinkLoop
SystemResources
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.Io.Kqueue.dirCreateDirPath

函数

第 820 行

fn dirCreateDirPath( userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions, ) Dir.CreateDirPathError!Dir.CreatePathStatus

参数

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
permissions: Dir.Permissions

错误

AccessDenied CreateDirError

在 WASI 中,当文件描述符不具备相对于自身 创建新目录所需的权限时,可能发生此错误。

AntivirusInterference OpenError

Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。

BadPathName PathNameError

文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。

Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy OpenError
DiskQuota CreateDirError
FileBusy OpenError

以下三种情况之一:

  • pathname 指向正在执行的可执行映像, 且请求写访问。
  • pathname 指向当前用作交换 文件的文件,且指定了 O_TRUNC 标志。
  • pathname 指向内核正在读取的文件, 例如用于加载模块或固件,且请求 写访问。
FileLocksUnsupported OpenError
FileNotFound OpenError

以下任一情况:

  • 某个路径分量不存在。
  • 使用了当前工作目录,但该目录已被删除。
  • 已打开目录句柄所关联的路径已被删除。
  • macOS 上,多个进程或线程将 O.EXCL 设为 false,并发争相创建同一文件。
FileTooBig OpenError

文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。

IsDir OpenError

以下任一情况:

  • 路径指向目录,但请求了写权限。
  • 路径指向目录,但 allow_directory 被设为 false。
LinkQuotaExceeded CreateDirError
NameTooLong PathNameError

提供的缓冲区过小, 无法容纳路径名时返回。

NetworkNotFound CreateDirError

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice CreateDirError
NoSpaceLeft OpenError

设备没有空间容纳新文件,无法创建新路径。 仅在提供 CREAT 标志时才可能出现此错误。

NotDir OpenError

路径中用作目录的某个部分实际上不是目录, 或者指定了 DIRECTORY,但路径不是目录。

PathAlreadyExists OpenError

路径已存在,且提供了 CREAT 和 EXCL 标志。

PermissionDenied CreateDirError
PipeBusy OpenError
ProcessFdQuotaExceeded OpenError
ReadOnlyFileSystem CreateDirError
Streaming StatError

尝试对非文件流调用 stat。

SymLinkLoop CreateDirError
SystemFdQuotaExceeded OpenError
SystemResources OpenError

路径超过 max_path_bytes 字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

WouldBlock OpenError

已请求非阻塞模式,但该操作无法立即返回。

std.Io.Kqueue.dirCreateDirPathOpen

函数

第 834 行

fn dirCreateDirPathOpen( userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions, options: Dir.OpenOptions, ) Dir.CreateDirPathOpenError!Dir

参数

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
permissions: Dir.Permissions
options: Dir.OpenOptions

错误

AccessDenied CreateDirError

在 WASI 中,当文件描述符不具备相对于自身 创建新目录所需的权限时,可能发生此错误。

AntivirusInterference OpenError

Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。

BadPathName PathNameError

文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。

Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy OpenError
DiskQuota CreateDirError
FileBusy OpenError

以下三种情况之一:

  • pathname 指向正在执行的可执行映像, 且请求写访问。
  • pathname 指向当前用作交换 文件的文件,且指定了 O_TRUNC 标志。
  • pathname 指向内核正在读取的文件, 例如用于加载模块或固件,且请求 写访问。
FileLocksUnsupported OpenError
FileNotFound OpenError

以下任一情况:

  • 某个路径分量不存在。
  • 使用了当前工作目录,但该目录已被删除。
  • 已打开目录句柄所关联的路径已被删除。
  • macOS 上,多个进程或线程将 O.EXCL 设为 false,并发争相创建同一文件。
FileTooBig OpenError

文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。

IsDir OpenError

以下任一情况:

  • 路径指向目录,但请求了写权限。
  • 路径指向目录,但 allow_directory 被设为 false。
LinkQuotaExceeded CreateDirError
NameTooLong PathNameError

提供的缓冲区过小, 无法容纳路径名时返回。

NetworkNotFound CreateDirError

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice CreateDirError
NoSpaceLeft OpenError

设备没有空间容纳新文件,无法创建新路径。 仅在提供 CREAT 标志时才可能出现此错误。

NotDir OpenError

路径中用作目录的某个部分实际上不是目录, 或者指定了 DIRECTORY,但路径不是目录。

PathAlreadyExists OpenError

路径已存在,且提供了 CREAT 和 EXCL 标志。

PermissionDenied CreateDirError
PipeBusy OpenError
ProcessFdQuotaExceeded OpenError
ReadOnlyFileSystem CreateDirError
Streaming StatError

尝试对非文件流调用 stat。

SymLinkLoop CreateDirError
SystemFdQuotaExceeded OpenError
SystemResources OpenError

路径超过 max_path_bytes 字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

WouldBlock OpenError

已请求非阻塞模式,但该操作无法立即返回。

std.Io.Kqueue.dirCreateFile

函数

第 878 行

fn dirCreateFile(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, flags: Dir.CreateFileOptions) File.OpenError!File

参数

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
flags: Dir.CreateFileOptions

错误

AccessDenied

在 WASI 中,若文件描述符不具有相对于它 打开新资源所需的权限,可能发生此错误。

AntivirusInterference

Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。

BadPathName PathNameError

文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。

Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy
FileBusy

以下三种情况之一:

  • pathname 指向正在执行的可执行映像, 且请求写访问。
  • pathname 指向当前用作交换 文件的文件,且指定了 O_TRUNC 标志。
  • pathname 指向内核正在读取的文件, 例如用于加载模块或固件,且请求 写访问。
FileLocksUnsupported
FileNotFound

以下任一情况:

  • 某个路径分量不存在。
  • 使用了当前工作目录,但该目录已被删除。
  • 已打开目录句柄所关联的路径已被删除。
  • macOS 上,多个进程或线程将 O.EXCL 设为 false,并发争相创建同一文件。
FileTooBig

文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。

IsDir

以下任一情况:

  • 路径指向目录,但请求了写权限。
  • 路径指向目录,但 allow_directory 被设为 false。
NameTooLong PathNameError

提供的缓冲区过小, 无法容纳路径名时返回。

NetworkNotFound

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice
NoSpaceLeft

设备没有空间容纳新文件,无法创建新路径。 仅在提供 CREAT 标志时才可能出现此错误。

NotDir

路径中用作目录的某个部分实际上不是目录, 或者指定了 DIRECTORY,但路径不是目录。

PathAlreadyExists

路径已存在,且提供了 CREAT 和 EXCL 标志。

PermissionDenied
PipeBusy
ProcessFdQuotaExceeded
ReadOnlyFileSystem
SymLinkLoop
SystemFdQuotaExceeded
SystemResources

路径超过 max_path_bytes 字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

WouldBlock

已请求非阻塞模式,但该操作无法立即返回。

std.Io.Kqueue.dirOpenDir

函数

第 894 行

fn dirOpenDir(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.OpenOptions) Dir.OpenError!Dir

参数

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
options: Dir.OpenOptions

错误

AccessDenied
BadPathName PathNameError

文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。

Canceled Cancelable

调用方请求停止异步操作。

FileNotFound
NameTooLong PathNameError

提供的缓冲区过小, 无法容纳路径名时返回。

NetworkNotFound

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice
NotDir
PermissionDenied
ProcessFdQuotaExceeded
SymLinkLoop
SystemFdQuotaExceeded
SystemResources
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.Io.Kqueue.dirOpenFile

函数

第 886 行

fn dirOpenFile(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, flags: Dir.OpenFileOptions) File.OpenError!File

参数

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
flags: Dir.OpenFileOptions

错误

AccessDenied

在 WASI 中,若文件描述符不具有相对于它 打开新资源所需的权限,可能发生此错误。

AntivirusInterference

Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。

BadPathName PathNameError

文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。

Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy
FileBusy

以下三种情况之一:

  • pathname 指向正在执行的可执行映像, 且请求写访问。
  • pathname 指向当前用作交换 文件的文件,且指定了 O_TRUNC 标志。
  • pathname 指向内核正在读取的文件, 例如用于加载模块或固件,且请求 写访问。
FileLocksUnsupported
FileNotFound

以下任一情况:

  • 某个路径分量不存在。
  • 使用了当前工作目录,但该目录已被删除。
  • 已打开目录句柄所关联的路径已被删除。
  • macOS 上,多个进程或线程将 O.EXCL 设为 false,并发争相创建同一文件。
FileTooBig

文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。

IsDir

以下任一情况:

  • 路径指向目录,但请求了写权限。
  • 路径指向目录,但 allow_directory 被设为 false。
NameTooLong PathNameError

提供的缓冲区过小, 无法容纳路径名时返回。

NetworkNotFound

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice
NoSpaceLeft

设备没有空间容纳新文件,无法创建新路径。 仅在提供 CREAT 标志时才可能出现此错误。

NotDir

路径中用作目录的某个部分实际上不是目录, 或者指定了 DIRECTORY,但路径不是目录。

PathAlreadyExists

路径已存在,且提供了 CREAT 和 EXCL 标志。

PermissionDenied
PipeBusy
ProcessFdQuotaExceeded
ReadOnlyFileSystem
SymLinkLoop
SystemFdQuotaExceeded
SystemResources

路径超过 max_path_bytes 字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

WouldBlock

已请求非阻塞模式,但该操作无法立即返回。

std.Io.Kqueue.dirStat

函数

第 850 行

fn dirStat(userdata: ?*anyopaque, dir: Dir) Dir.StatError!Dir.Stat

参数

userdata: ?*anyopaque
dir: Dir

错误

AccessDenied StatError

在 WASI 中,当文件描述符不具备获取自身 filestat 信息所需的权限时,可能发生此错误。

Canceled Cancelable

调用方请求停止异步操作。

PermissionDenied StatError
Streaming StatError

尝试对非文件流调用 stat。

SystemResources StatError
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.Io.Kqueue.dirStatFile

函数

第 857 行

fn dirStatFile( userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.StatFileOptions, ) Dir.StatFileError!File.Stat

参数

userdata: ?*anyopaque
dir: Dir
sub_path: []const u8
options: Dir.StatFileOptions

错误

AccessDenied OpenError

在 WASI 中,若文件描述符不具有相对于它 打开新资源所需的权限,可能发生此错误。

AntivirusInterference OpenError

Windows 默认启用杀毒软件。虽然可以禁用,但 Windows Update 有时会忽略用户偏好并重新启用。 启用时,Windows 上的杀毒软件会拦截文件系统操作,使其显著变慢,也可能导致操作因该错误码失败。

BadPathName PathNameError

文件系统无法编码请求的文件名字节。 原因可能是 Windows 上无效的 WTF-8、WASI 上无效的 UTF-8、 Windows 上的无效字符等,具体取决于文件系统与操作系统。

Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy OpenError
FileBusy OpenError

以下三种情况之一:

  • pathname 指向正在执行的可执行映像, 且请求写访问。
  • pathname 指向当前用作交换 文件的文件,且指定了 O_TRUNC 标志。
  • pathname 指向内核正在读取的文件, 例如用于加载模块或固件,且请求 写访问。
FileLocksUnsupported OpenError
FileNotFound OpenError

以下任一情况:

  • 某个路径分量不存在。
  • 使用了当前工作目录,但该目录已被删除。
  • 已打开目录句柄所关联的路径已被删除。
  • macOS 上,多个进程或线程将 O.EXCL 设为 false,并发争相创建同一文件。
FileTooBig OpenError

文件过大,无法打开。对于 64 位目标及打开目录的情况,此错误不可达。

IsDir OpenError

以下任一情况:

  • 路径指向目录,但请求了写权限。
  • 路径指向目录,但 allow_directory 被设为 false。
NameTooLong PathNameError

提供的缓冲区过小, 无法容纳路径名时返回。

NetworkNotFound OpenError

在 Windows 上,未找到 \\server 或 \\server\share。

NoDevice OpenError
NoSpaceLeft OpenError

设备没有空间容纳新文件,无法创建新路径。 仅在提供 CREAT 标志时才可能出现此错误。

NotDir OpenError

路径中用作目录的某个部分实际上不是目录, 或者指定了 DIRECTORY,但路径不是目录。

PathAlreadyExists OpenError

路径已存在,且提供了 CREAT 和 EXCL 标志。

PermissionDenied OpenError
PipeBusy OpenError
ProcessFdQuotaExceeded OpenError
ReadOnlyFileSystem OpenError
Streaming StatError

尝试对非文件流调用 stat。

SymLinkLoop OpenError
SystemFdQuotaExceeded OpenError
SystemResources OpenError

路径超过 max_path_bytes 字节。 可用内核内存不足;或者 指定文件为 FIFO,且达到每用户 管道内存分配的硬限制。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

WouldBlock OpenError

已请求非阻塞模式,但该操作无法立即返回。

std.Io.Kqueue.errnoBug

别名

第 13 行

别名目标 std.Io.Threaded.errnoBug

std.Io.Kqueue.Fiber

容器

第 76 行

字段

required_align: void align(4)
context: Io.fiber.Context
awaiter: ?*Fiber
queue_next: ?*Fiber
cancel_thread: ?*Thread
awaiting_completions: std.bit_set.Static(3)

std.Io.Kqueue.Fiber.allocate

函数

第 103 行

fn allocate(k: *Kqueue) error{OutOfMemory}!*Fiber

参数

k: *Kqueue

错误

OutOfMemory

std.Io.Kqueue.Fiber.allocatedEnd

函数

第 111 行

fn allocatedEnd(f: *Fiber) [*]u8

参数

f: *Fiber

std.Io.Kqueue.Fiber.allocatedSlice

函数

第 107 行

fn allocatedSlice(f: *Fiber) []align(@alignOf(Fiber)) u8

参数

f: *Fiber

std.Io.Kqueue.Fiber.allocation_size

常量

第 95 行

std.Io.Kqueue.Fiber.enterCancelRegion

函数

第 124 行

fn enterCancelRegion(fiber: *Fiber, thread: *Thread) error{Canceled}!void

参数

fiber: *Fiber
thread: *Thread

错误

Canceled

std.Io.Kqueue.Fiber.exitCancelRegion

函数

第 138 行

fn exitCancelRegion(fiber: *Fiber, thread: *Thread) void

参数

fiber: *Fiber
thread: *Thread

std.Io.Kqueue.Fiber.finished

常量

第 84 行

?*Fiber

std.Io.Kqueue.Fiber.max_closure_align

常量

第 94 行

Alignment

std.Io.Kqueue.Fiber.max_closure_size

常量

第 93 行

usize

std.Io.Kqueue.Fiber.max_context_align

常量

第 91 行

Alignment

std.Io.Kqueue.Fiber.max_context_size

常量

第 92 行

std.Io.Kqueue.Fiber.max_result_align

常量

第 86 行

Alignment

std.Io.Kqueue.Fiber.max_result_size

常量

第 87 行

std.Io.Kqueue.Fiber.min_stack_size

常量

第 90 行

包含所需的全部栈重新对齐,以及初始帧返回地址槽和参数帧,具体取决于目标。

std.Io.Kqueue.Fiber.Queue

容器

第 149 行

字段

head: *Fiber
tail: *Fiber

std.Io.Kqueue.Fiber.resultBytes

函数

第 120 行

fn resultBytes(f: *Fiber, alignment: Alignment) [*]u8

参数

f: *Fiber
alignment: Alignment

std.Io.Kqueue.Fiber.resultPointer

函数

第 116 行

fn resultPointer(f: *Fiber, comptime Result: type) *Result

参数

f: *Fiber
Result: type

std.Io.Kqueue.fiberEntry

函数

第 559 行

fn fiberEntry() callconv(.naked) void

std.Io.Kqueue.File

别名

第 7 行

别名目标 std.Io.File

std.Io.Kqueue.fileClose

函数

第 915 行

fn fileClose(userdata: ?*anyopaque, files: []const File) void

参数

userdata: ?*anyopaque
files: []const File

std.Io.Kqueue.fileReadPositional

函数

第 964 行

fn fileReadPositional(userdata: ?*anyopaque, file: File, data: []const []u8, offset: u64) File.ReadPositionalError!usize

参数

userdata: ?*anyopaque
file: File
data: []const []u8
offset: u64

错误

AccessDenied

在 WASI 中,当文件描述符不具有读取 所需的权限时发生此错误。

Canceled Cancelable

调用方请求停止异步操作。

InputOutput
IsDir

尝试将目录文件描述符当作普通文件读取。

LockViolation

由于锁定而无法读取文件。根据 Io 实现的不同,读取已锁定文件可能返回此错误,也可能忽略锁。

NotOpenForReading

打开文件时未授予读取能力。

SystemResources
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

Unseekable

此文件不支持按位置读取。

WouldBlock

已启用非阻塞模式,且从该文件描述符读取会阻塞。

std.Io.Kqueue.fileReadStreaming

函数

第 956 行

fn fileReadStreaming(userdata: ?*anyopaque, file: File, data: []const []u8) File.Reader.Error!usize

参数

userdata: ?*anyopaque
file: File
data: []const []u8

错误

AccessDenied UnendingError

在 WASI 中,当文件描述符不具有读取 所需的权限时发生此错误。

Canceled Cancelable

调用方请求停止异步操作。

ConnectionResetByPeer UnendingError
InputOutput UnendingError
IsDir UnendingError

尝试将目录文件描述符当作普通文件读取。

LockViolation UnendingError

由于锁定而无法读取文件。根据 Io 实现的不同,读取已锁定文件可能返回此错误,也可能忽略锁。

NotOpenForReading UnendingError

打开文件时未授予读取能力。

SocketUnconnected UnendingError
SystemResources UnendingError
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

WouldBlock UnendingError

已启用非阻塞模式,且从该文件描述符读取会阻塞。

std.Io.Kqueue.fileSeekBy

函数

第 972 行

fn fileSeekBy(userdata: ?*anyopaque, file: File, relative_offset: i64) File.SeekError!void

参数

userdata: ?*anyopaque
file: File
relative_offset: i64

错误

AccessDenied

文件描述符不具备执行定位所需的权限。

Canceled Cancelable

调用方请求停止异步操作。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

Unseekable

std.Io.Kqueue.fileSeekTo

函数

第 979 行

fn fileSeekTo(userdata: ?*anyopaque, file: File, absolute_offset: u64) File.SeekError!void

参数

userdata: ?*anyopaque
file: File
absolute_offset: u64

错误

AccessDenied

文件描述符不具备执行定位所需的权限。

Canceled Cancelable

调用方请求停止异步操作。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

Unseekable

std.Io.Kqueue.fileStat

函数

第 908 行

fn fileStat(userdata: ?*anyopaque, file: File) File.StatError!File.Stat

参数

userdata: ?*anyopaque
file: File

错误

AccessDenied

在 WASI 中,当文件描述符不具备获取自身 filestat 信息所需的权限时,可能发生此错误。

Canceled Cancelable

调用方请求停止异步操作。

PermissionDenied
Streaming

尝试对非文件流调用 stat。

SystemResources
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.Io.Kqueue.fileWritePositional

函数

第 938 行

fn fileWritePositional( userdata: ?*anyopaque, file: File, header: []const u8, data: []const []const u8, splat: usize, offset: u64, ) File.WritePositionalError!usize

参数

userdata: ?*anyopaque
file: File
header: []const u8
data: []const []const u8
splat: usize
offset: u64

错误

AccessDenied

文件描述符没有写入所需的权限。

BrokenPipe

文件为未连接的套接字,或其读取端已关闭。

Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy
DiskQuota
FileBusy
FileTooBig
InputOutput
LockViolation

进程无法访问文件,因为另一进程已锁定 文件的一部分。仅限 Windows。

NoDevice

写入设备期间,若设备在刷新之前或刷新途中断开,就会发生此错误:errno(6),没有此设备或地址。

NoSpaceLeft
NotOpenForWriting

文件打开时没有写入能力。

PermissionDenied
SystemResources

内核内存不足,无法从 in_fd 读取。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

Unseekable

无法对该文件按指定位置写入。

WouldBlock

已启用非阻塞模式,而此操作将阻塞。

std.Io.Kqueue.fileWriteStreaming

函数

第 922 行

fn fileWriteStreaming( userdata: ?*anyopaque, file: File, header: []const u8, data: []const []const u8, splat: usize, ) File.Writer.Error!usize

参数

userdata: ?*anyopaque
file: File
header: []const u8
data: []const []const u8
splat: usize

错误

AccessDenied Error

文件描述符没有写入所需的权限。

BrokenPipe Error

文件为未连接的套接字,或其读取端已关闭。

Canceled Cancelable

调用方请求停止异步操作。

DeviceBusy Error
DiskQuota Error
FileBusy Error
FileTooBig Error
InputOutput Error
LockViolation Error

进程无法访问文件,因为另一进程已锁定 文件的一部分。仅限 Windows。

NoDevice Error

写入设备期间,若设备在刷新之前或刷新途中断开,就会发生此错误:errno(6),没有此设备或地址。

NoSpaceLeft Error
NotOpenForWriting Error
PermissionDenied Error
SystemResources Error

内核内存不足,无法从 in_fd 读取。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

WouldBlock Error

已启用非阻塞模式,而此操作将阻塞。

std.Io.Kqueue.findReadyFiber

函数

第 256 行

fn findReadyFiber(k: *Kqueue, thread: *Thread) ?*Fiber

参数

k: *Kqueue
thread: *Thread

std.Io.Kqueue.groupAsync

函数

第 763 行

fn groupAsync( userdata: ?*anyopaque, type_erased: *Io.Group, context: []const u8, context_alignment: Alignment, start: *const fn (context: *const anyopaque) void, ) void

参数

userdata: ?*anyopaque
type_erased: *Io.Group
context: []const u8
context_alignment: Alignment
start: *const fn (context: *const anyopaque) void

std.Io.Kqueue.groupAwait

函数

第 795 行

fn groupAwait(userdata: ?*anyopaque, type_erased: *Io.Group, initial_token: *anyopaque) Io.Cancelable!void

参数

userdata: ?*anyopaque
type_erased: *Io.Group
initial_token: *anyopaque

错误

Canceled

调用方请求停止异步操作。

std.Io.Kqueue.groupCancel

函数

第 803 行

fn groupCancel(userdata: ?*anyopaque, group: *Io.Group, token: *anyopaque) void

参数

userdata: ?*anyopaque
group: *Io.Group
token: *anyopaque

std.Io.Kqueue.groupConcurrent

函数

第 779 行

fn groupConcurrent( userdata: ?*anyopaque, type_erased: *Io.Group, context: []const u8, context_alignment: Alignment, start: *const fn (context: *const anyopaque) void, ) Io.ConcurrentError!void

参数

userdata: ?*anyopaque
type_erased: *Io.Group
context: []const u8
context_alignment: Alignment
start: *const fn (context: *const anyopaque) void

错误

ConcurrencyUnavailable

可能由资源耗尽等临时情况引起,也可能因为 Io 实现不支持并发。

std.Io.Kqueue.idle

函数

第 429 行

fn idle(k: *Kqueue, thread: *Thread) void

参数

k: *Kqueue
thread: *Thread

std.Io.Kqueue.idle_stack_size

常量

第 25 行

经验上观察到,自托管后端在 panic 时使用超过 128KB。

std.Io.Kqueue.init

函数

第 164 行

pub fn init(k: *Kqueue, gpa: Allocator, options: InitOptions) !void

参数

k: *Kqueue
gpa: Allocator
options: InitOptions

std.Io.Kqueue.InitError

错误集合

第 162 行

错误

OutOfMemory Error
ProcessFdQuotaExceeded CreateFileDescriptorError

已达到每个进程可打开的文件描述符数量限制。

SystemFdQuotaExceeded CreateFileDescriptorError

已达到系统范围内打开文件总数的上限。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.Io.Kqueue.InitOptions

容器

第 158 行

字段

n_threads: ?usize = null

std.Io.Kqueue.io

函数

第 610 行

pub fn io(k: *Kqueue) Io

参数

k: *Kqueue

std.Io.Kqueue.Io

别名

第 5 行

别名目标 std.Io

std.Io.Kqueue.IpAddress

别名

第 12 行

别名目标 std.Io.net.IpAddress

std.Io.Kqueue.kevent

函数

第 1474 行

pub fn kevent( kq: i32, changelist: []const posix.Kevent, eventlist: []posix.Kevent, timeout: ?*const posix.timespec, ) KEventError!usize

参数

kq: i32
changelist: []const posix.Kevent
eventlist: []posix.Kevent
timeout: ?*const posix.timespec

错误

AccessDenied

进程无权注册过滤器。

EventNotFound

找不到要修改或删除的事件。

Overflow

changelist 或 eventlist 中的项目过多。 TODO 移除此可能性

ProcessNotFound

指定要附加的进程不存在。

SystemResources

没有可用于注册事件的内存。

std.Io.Kqueue.KEventError

错误集合

第 1460 行

错误

AccessDenied

进程无权注册过滤器。

EventNotFound

找不到要修改或删除的事件。

Overflow

changelist 或 eventlist 中的项目过多。 TODO 移除此可能性

ProcessNotFound

指定要附加的进程不存在。

SystemResources

没有可用于注册事件的内存。

std.Io.Kqueue.Kqueue

别名

第 1 行

别名目标 std.Io.Kqueue

std.Io.Kqueue.mainIdle

函数

第 397 行

fn mainIdle(k: *Kqueue, message: *const SwitchMessage) callconv(.withStackAlign(.c, @max(@alignOf(Thread), @alignOf(Io.fiber.Context)))) noreturn

参数

k: *Kqueue
message: *const SwitchMessage

std.Io.Kqueue.mainIdleEntry

函数

第 541 行

fn mainIdleEntry() callconv(.naked) void

std.Io.Kqueue.max_idle_search

常量

第 27 行

std.Io.Kqueue.max_iovecs_len

常量

第 29 行

std.Io.Kqueue.max_steal_ready_search

常量

第 28 行

std.Io.Kqueue.net

别名

第 8 行

别名目标 std.Io.net

std.Io.Kqueue.netAccept

函数

第 1011 行

fn netAccept(userdata: ?*anyopaque, server: net.Socket.Handle, options: net.Server.AcceptOptions) net.Server.AcceptError!net.Socket

参数

userdata: ?*anyopaque
server: net.Socket.Handle
options: net.Server.AcceptOptions

错误

BlockedByFirewall

防火墙规则禁止连接。

Canceled Cancelable

调用方请求停止异步操作。

ConnectionAborted

曾有传入连接,但在接受调用之前, 远端对等方已将其终止。

NetworkDown

网络子系统已失败。

ProcessFdQuotaExceeded

已达到每个进程可打开的文件描述符数量限制。

ProtocolFailure
SocketNotListening

从未调用 listen,或已调用 shutdown,后者可能发生于 本调用阻塞期间。因此,可将 shutdown 用作 并发取消机制。

SystemFdQuotaExceeded

已达到系统范围内打开文件总数的上限。

SystemResources

可用内存不足。这通常意味着内存分配受限于 套接字缓冲区上限,而非系统内存。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

WouldBlock

没有已排队且可立即接受的连接, 而套接字配置为非阻塞模式。

std.Io.Kqueue.netBindIp

函数

第 1018 行

fn netBindIp( userdata: ?*anyopaque, address: *const net.IpAddress, options: net.IpAddress.BindOptions, ) net.IpAddress.BindError!net.Socket

参数

userdata: ?*anyopaque
address: *const net.IpAddress
options: net.IpAddress.BindOptions

错误

AccessDenied

该地址受到保护,当前用户没有绑定它的权限。

AddressFamilyUnsupported

该地址对于套接字的地址族无效。

AddressInUse

地址已被占用。当绑定端口为 0, 但所有临时端口均已使用时,可能发生此情况。

AddressUnavailable

请求了不存在的接口,或请求的地址不是本地地址。

Canceled Cancelable

调用方请求停止异步操作。

NetworkDown

用于到达目标的本地网络接口已离线。

OptionUnsupported

Io 实现不支持某个 BindOptions。

ProcessFdQuotaExceeded

已达到每进程可打开文件描述符数量上限。

ProtocolUnsupportedByAddressFamily
ProtocolUnsupportedBySystem
SocketModeUnsupported
SystemFdQuotaExceeded

已达到系统范围内已打开文件的总数上限。

SystemResources

操作系统内部内存或其他资源不足。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.Io.Kqueue.netConnectIp

函数

第 1034 行

fn netConnectIp(userdata: ?*anyopaque, address: *const net.IpAddress, options: net.IpAddress.ConnectOptions) net.IpAddress.ConnectError!net.Socket

参数

userdata: ?*anyopaque
address: *const net.IpAddress
options: net.IpAddress.ConnectOptions

错误

AccessDenied

用户尝试连接广播地址,但未启用套接字广播标志;或 连接请求因本地防火墙规则而失败。

AddressFamilyUnsupported
AddressUnavailable
Canceled Cancelable

调用方请求停止异步操作。

ConnectionPending
ConnectionRefused
ConnectionResetByPeer
HostUnreachable
NetworkDown
NetworkUnreachable
OptionUnsupported

Io 实现不支持某个 ConnectOptions 选项。

ProcessFdQuotaExceeded

已达到每进程可打开文件描述符数量上限。

ProtocolUnsupportedByAddressFamily
ProtocolUnsupportedBySystem
SocketModeUnsupported
SystemFdQuotaExceeded

已达到系统范围内已打开文件的总数上限。

SystemResources

操作系统内部内存或其他资源不足。

Timeout
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

WouldBlock

已请求非阻塞模式,但该操作无法立即返回。

std.Io.Kqueue.netConnectUnix

函数

第 1094 行

fn netConnectUnix( userdata: ?*anyopaque, unix_address: *const net.UnixAddress, ) net.UnixAddress.ConnectError!net.Socket.Handle

参数

userdata: ?*anyopaque
unix_address: *const net.UnixAddress

错误

AccessDenied
AddressFamilyUnsupported
Canceled Cancelable

调用方请求停止异步操作。

ConnectionRefused
FileNotFound
NetworkDown
NotDir
PermissionDenied
ProcessFdQuotaExceeded
ProtocolUnsupportedBySystem
ReadOnlyFileSystem
SocketModeUnsupported
SymLinkLoop
SystemFdQuotaExceeded
SystemResources
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

WouldBlock

std.Io.Kqueue.netInterfaceName

函数

第 1289 行

fn netInterfaceName(userdata: ?*anyopaque, interface: net.Interface) net.Interface.NameError!net.Interface.Name

参数

userdata: ?*anyopaque
interface: net.Interface

错误

Canceled Cancelable

调用方请求停止异步操作。

InterfaceNotFound

index 超出范围。

NameTooLong

接口名称长于 Name.max_len。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.Io.Kqueue.netInterfaceNameResolve

函数

第 1279 行

fn netInterfaceNameResolve( userdata: ?*anyopaque, name: *const net.Interface.Name, ) net.Interface.Name.ResolveError!net.Interface

参数

userdata: ?*anyopaque
name: *const net.Interface.Name

错误

AccessDenied
Canceled Cancelable

调用方请求停止异步操作。

InterfaceNotFound
SystemResources
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.Io.Kqueue.netListenIp

函数

第 1000 行

fn netListenIp( userdata: ?*anyopaque, address: *const net.IpAddress, options: net.IpAddress.ListenOptions, ) net.IpAddress.ListenError!net.Socket

参数

userdata: ?*anyopaque
address: *const net.IpAddress
options: net.IpAddress.ListenOptions

错误

AccessDenied

该地址受到保护,当前用户没有绑定它的权限。

AddressFamilyUnsupported

操作系统不支持请求的地址族(IPv4 或 IPv6)。

AddressInUse

地址已被占用。当绑定端口为 0, 但所有临时端口均已使用时,可能发生此情况。

AddressUnavailable

请求了不存在的接口,或请求的地址不是本地地址。

Canceled Cancelable

调用方请求停止异步操作。

NetworkDown

用于到达目标的本地网络接口已离线。

OptionUnsupported

Io 实现不支持某个 ListenOptions。

ProcessFdQuotaExceeded

已达到每进程可打开文件描述符数量上限。

ProtocolUnsupportedByAddressFamily
ProtocolUnsupportedBySystem
SocketModeUnsupported
SystemFdQuotaExceeded

已达到系统范围内已打开文件的总数上限。

SystemResources

操作系统内部内存或其他资源不足。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.Io.Kqueue.netListenUnix

函数

第 1083 行

fn netListenUnix( userdata: ?*anyopaque, unix_address: *const net.UnixAddress, options: net.UnixAddress.ListenOptions, ) net.UnixAddress.ListenError!net.Socket.Handle

参数

userdata: ?*anyopaque
unix_address: *const net.UnixAddress
options: net.UnixAddress.ListenOptions

错误

AccessDenied
AddressFamilyUnsupported
AddressInUse
AddressUnavailable
Canceled Cancelable

调用方请求停止异步操作。

FileNotFound
NetworkDown
NotDir
PermissionDenied
ProcessFdQuotaExceeded
ReadOnlyFileSystem
SymLinkLoop
SystemFdQuotaExceeded
SystemResources
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.Io.Kqueue.netLookup

函数

第 1296 行

fn netLookup( userdata: ?*anyopaque, host_name: net.HostName, resolved: *Io.Queue(net.HostName.LookupResult), options: net.HostName.LookupOptions, ) net.HostName.LookupError!void

参数

userdata: ?*anyopaque
host_name: net.HostName
resolved: *Io.Queue(net.HostName.LookupResult)
options: net.HostName.LookupOptions

错误

AccessDenied BindError

该地址受到保护,当前用户没有绑定它的权限。

AddressFamilyUnsupported BindError

该地址对于套接字的地址族无效。

AddressInUse BindError

地址已被占用。当绑定端口为 0, 但所有临时端口均已使用时,可能发生此情况。

AddressUnavailable BindError

请求了不存在的接口,或请求的地址不是本地地址。

Canceled Cancelable

调用方请求停止异步操作。

DetectingNetworkConfigurationFailed

无法打开或读取 "/etc/hosts" 或 "/etc/resolv.conf"。

InvalidDnsAAAARecord
InvalidDnsARecord
InvalidDnsCnameRecord
NameServerFailure
NetworkDown BindError

用于到达目标的本地网络接口已离线。

NoAddressReturned
OptionUnsupported BindError

Io 实现不支持某个 BindOptions。

ProcessFdQuotaExceeded BindError

已达到每进程可打开文件描述符数量上限。

ProtocolUnsupportedByAddressFamily BindError
ProtocolUnsupportedBySystem BindError
ResolvConfParseFailed
SocketModeUnsupported BindError
SystemFdQuotaExceeded BindError

已达到系统范围内已打开文件的总数上限。

SystemResources BindError

操作系统内部内存或其他资源不足。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

UnknownHostName

std.Io.Kqueue.netRead

函数

第 1199 行

fn netRead(userdata: ?*anyopaque, fd: net.Socket.Handle, data: [][]u8) net.Stream.Reader.Error!usize

参数

userdata: ?*anyopaque
fd: net.Socket.Handle
data: [][]u8

错误

AccessDenied Error

文件描述符不具有读取所需权限。

Canceled Cancelable

调用方请求停止异步操作。

ConnectionResetByPeer Error
ConnectionTimedOut Error

远端对等方未响应正在进行的通信,导致 操作系统中止连接。

NetworkDown Error
SocketUnconnected Error
SystemResources Error
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.Io.Kqueue.netReceive

类型函数

第 1181 行

fn netReceive( userdata: ?*anyopaque, handle: net.Socket.Handle, message_buffer: []net.IncomingMessage, data_buffer: []u8, flags: net.ReceiveFlags, timeout: Io.Timeout, ) struct { ?net.Socket.ReceiveTimeoutError, usize }

参数

userdata: ?*anyopaque
handle: net.Socket.Handle
message_buffer: []net.IncomingMessage
data_buffer: []u8
flags: net.ReceiveFlags
timeout: Io.Timeout

std.Io.Kqueue.netSend

类型函数

第 1104 行

fn netSend( userdata: ?*anyopaque, handle: net.Socket.Handle, outgoing_messages: []net.OutgoingMessage, flags: net.SendFlags, ) struct { ?net.Socket.SendError, usize }

参数

userdata: ?*anyopaque
handle: net.Socket.Handle
outgoing_messages: []net.OutgoingMessage
flags: net.SendFlags

std.Io.Kqueue.netSendOne

函数

第 1127 行

fn netSendOne( k: *Kqueue, handle: net.Socket.Handle, message: *net.OutgoingMessage, flags: u32, ) net.Socket.SendError!void

参数

k: *Kqueue
handle: net.Socket.Handle
message: *net.OutgoingMessage
flags: u32

错误

AccessDenied Error

尝试向网络/广播地址发送数据, 却将其当作单播地址。

AddressFamilyUnsupported Error

操作系统或协议不支持该地址族。

Canceled Cancelable

调用方请求停止异步操作。

ConnectionRefused Error

目标地址未在侦听;对于无连接消息也可能发生此情况。

ConnectionResetByPeer Error

网络会话被接收方意外关闭。

ConnectionTimedOut Error

远端对等方未响应正在进行的通信,导致 操作系统中止连接。

FastOpenAlreadyInProgress Error

另一个 TCP 快速打开已在进行。

HostUnreachable Error

可到达网络,但没有到主机的路由。

MessageOversize Error

此套接字类型要求以原子方式发送消息,但待发送 消息的大小使其无法实现。消息未发送, 或仅发送了一部分。

NetworkDown Error

用于到达目标的本地网络接口已离线。

NetworkUnreachable Error

没有到网络的路由。

SocketUnconnected Error

面向连接的套接字的本地端已关闭,或 该套接字从未连接。

SystemResources Error

网络接口的输出队列已满。这通常表示 接口已停止发送,但也可能由短暂拥塞导致。通常, Linux 不会发生此错误;设备队列溢出时只会 静默丢弃分组。

可用内核内存不足时也会发生此错误。

Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.Io.Kqueue.netShutdown

函数

第 1271 行

fn netShutdown(userdata: ?*anyopaque, handle: net.Socket.Handle, how: net.ShutdownHow) net.ShutdownError!void

参数

userdata: ?*anyopaque
handle: net.Socket.Handle
how: net.ShutdownHow

错误

Canceled Cancelable

调用方请求停止异步操作。

ConnectionAborted
ConnectionResetByPeer
NetworkDown
SocketUnconnected
SystemResources
Unexpected UnexpectedError

操作系统返回了未记录在文档中的错误码。

理论上不可能出现此错误,但处理 此错误优于触发未定义行为。

观察到此错误码时,通常意味着 Zig 标准 库需要小幅修补,将该错误码加入 相应函数的错误集合。

std.Io.Kqueue.now

函数

第 987 行

fn now(userdata: ?*anyopaque, clock: Io.Clock) Io.Clock.Error!Io.Timestamp

参数

userdata: ?*anyopaque
clock: Io.Clock

std.Io.Kqueue.openSocketPosix

函数

第 1310 行

fn openSocketPosix( k: *Kqueue, family: posix.sa_family_t, options: IpAddress.BindOptions, ) error{ AddressFamilyUnsupported, ProtocolUnsupportedBySystem, ProcessFdQuotaExceeded, SystemFdQuotaExceeded, SystemResources, ProtocolUnsupportedByAddressFamily, SocketModeUnsupported, OptionUnsupported, Unexpected, Canceled, }!posix.socket_t

参数

错误

AddressFamilyUnsupported
Canceled
OptionUnsupported
ProcessFdQuotaExceeded
ProtocolUnsupportedByAddressFamily
ProtocolUnsupportedBySystem
SocketModeUnsupported
SystemFdQuotaExceeded
SystemResources
Unexpected

std.Io.Kqueue.posix

别名

第 15 行

别名目标 std.posix

std.Io.Kqueue.posixBind

函数

第 1393 行

fn posixBind( k: *Kqueue, socket_fd: posix.socket_t, addr: *const posix.sockaddr, addr_len: posix.socklen_t, ) !void

参数

k: *Kqueue
socket_fd: posix.socket_t
addr: *const posix.sockaddr
addr_len: posix.socklen_t

std.Io.Kqueue.posixConnect

函数

第 1050 行

fn posixConnect(k: *Kqueue, socket_fd: posix.socket_t, addr: *const posix.sockaddr, addr_len: posix.socklen_t) !void

参数

k: *Kqueue
socket_fd: posix.socket_t
addr: *const posix.sockaddr
addr_len: posix.socklen_t

std.Io.Kqueue.posixGetSockName

函数

第 1420 行

fn posixGetSockName(k: *Kqueue, socket_fd: posix.fd_t, addr: *posix.sockaddr, addr_len: *posix.socklen_t) !void

参数

k: *Kqueue
socket_fd: posix.fd_t
addr: *posix.sockaddr
addr_len: *posix.socklen_t

std.Io.Kqueue.posixSocketModeProtocol

别名

第 16 行

别名目标 std.Io.Threaded.posixSocketModeProtocol

std.Io.Kqueue.recycle

函数

第 152 行

fn recycle(k: *Kqueue, fiber: *Fiber) void

参数

k: *Kqueue
fiber: *Fiber

std.Io.Kqueue.schedule

函数

第 304 行

fn schedule(k: *Kqueue, thread: *Thread, ready_queue: Fiber.Queue) void

参数

k: *Kqueue
thread: *Thread
ready_queue: Fiber.Queue

std.Io.Kqueue.setSocketOption

函数

第 1438 行

fn setSocketOption(k: *Kqueue, fd: posix.fd_t, level: i32, opt_name: u32, option: u32) !void

参数

k: *Kqueue
fd: posix.fd_t
level: i32
opt_name: u32
option: u32

std.Io.Kqueue.sleep

函数

第 993 行

fn sleep(userdata: ?*anyopaque, timeout: Io.Timeout) Io.SleepError!void

参数

userdata: ?*anyopaque
timeout: Io.Timeout

std.Io.Kqueue.std

别名

第 4 行

别名目标 std

std.Io.Kqueue.SwitchMessage

容器

第 486 行

字段

contexts: Io.fiber.Switch
pending_task: PendingTask

std.Io.Kqueue.SwitchMessage.handle

函数

第 498 行

fn handle(message: *const SwitchMessage, k: *Kqueue) void

参数

message: *const SwitchMessage
k: *Kqueue

std.Io.Kqueue.SwitchMessage.PendingTask

容器

第 490 行

字段

nothing
reschedule
recycle: *Fiber
register_awaiter: *?*Fiber
exit

std.Io.Kqueue.Thread

容器

第 33 行

字段

thread: std.Thread
idle_context: Io.fiber.Context
current_context: *Io.fiber.Context
ready_queue: ?*Fiber
kq_fd: posix.fd_t
idle_search_index: u32
steal_ready_search_index: u32
wait_queues: std.array_hash_map.Auto(WaitQueueKey, *Fiber)

确保等待同一文件描述符及过滤器的多个纤程 使用同一个 kevent。

std.Io.Kqueue.Thread.canceling

常量

第 50 行

?*Thread

std.Io.Kqueue.Thread.current

函数

第 54 行

fn current() *Thread

std.Io.Kqueue.Thread.currentFiber

函数

第 58 行

fn currentFiber(thread: *Thread) *Fiber

参数

thread: *Thread

std.Io.Kqueue.Thread.deinit

函数

第 68 行

fn deinit(thread: *Thread, gpa: Allocator) void

参数

thread: *Thread
gpa: Allocator

std.Io.Kqueue.Thread.List

容器

第 62 行

字段

allocated: []Thread
reserved: u32
active: u32

std.Io.Kqueue.Thread.self

变量

第 52 行

*Thread

std.Io.Kqueue.Thread.WaitQueueKey

容器

第 45 行

字段

ident: usize
filter: i32

std.Io.Kqueue.threadEntry

函数

第 404 行

fn threadEntry(k: *Kqueue, index: u32) void

参数

k: *Kqueue
index: u32

std.Io.Kqueue.yield

函数

第 287 行

fn yield(k: *Kqueue, maybe_ready_fiber: ?*Fiber, pending_task: SwitchMessage.PendingTask) void

参数

k: *Kqueue
maybe_ready_fiber: ?*Fiber
pending_task: SwitchMessage.PendingTask
源码

std/Io/Kqueue.zig

const Kqueue = @This();
const builtin = @import("builtin");

const std = @import("../std.zig");
const Io = std.Io;
const Dir = std.Io.Dir;
const File = std.Io.File;
const net = std.Io.net;
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const Alignment = std.mem.Alignment;
const IpAddress = std.Io.net.IpAddress;
const errnoBug = std.Io.Threaded.errnoBug;
const closeFd = std.Io.Threaded.closeFd;
const posix = std.posix;
const posixSocketModeProtocol = Io.Threaded.posixSocketModeProtocol;

/// 必须使用线程安全的分配器。
gpa: Allocator,
mutex: Io.Mutex,
main_fiber_buffer: [@sizeOf(Fiber) + Fiber.max_result_size]u8 align(@alignOf(Fiber)),
threads: Thread.List,

/// 经验上观察到,自托管后端在 panic 时使用超过 128KB。
const idle_stack_size = 256 * 1024;

const max_idle_search = 4;
const max_steal_ready_search = 4;
const max_iovecs_len = 8;

const changes_buffer_len = 64;

const Thread = struct {
    thread: std.Thread,
    idle_context: Io.fiber.Context,
    current_context: *Io.fiber.Context,
    ready_queue: ?*Fiber,
    kq_fd: posix.fd_t,
    idle_search_index: u32,
    steal_ready_search_index: u32,
    /// 确保等待同一文件描述符及过滤器的多个纤程
    /// 使用同一个 kevent。
    wait_queues: std.array_hash_map.Auto(WaitQueueKey, *Fiber),

    const WaitQueueKey = struct {
        ident: usize,
        filter: i32,
    };

    const canceling: ?*Thread = @ptrFromInt(@alignOf(Thread));

    threadlocal var self: *Thread = undefined;

    fn current() *Thread {
        return self;
    }

    fn currentFiber(thread: *Thread) *Fiber {
        return @fieldParentPtr("context", thread.current_context);
    }

    const List = struct {
        allocated: []Thread,
        reserved: u32,
        active: u32,
    };

    fn deinit(thread: *Thread, gpa: Allocator) void {
        closeFd(thread.kq_fd);
        assert(thread.wait_queues.count() == 0);
        thread.wait_queues.deinit(gpa);
        thread.* = undefined;
    }
};

const Fiber = struct {
    required_align: void align(4),
    context: Io.fiber.Context,
    awaiter: ?*Fiber,
    queue_next: ?*Fiber,
    cancel_thread: ?*Thread,
    awaiting_completions: std.bit_set.Static(3),

    const finished: ?*Fiber = @ptrFromInt(@alignOf(Thread));

    const max_result_align: Alignment = .@"16";
    const max_result_size = max_result_align.forward(64);
    /// 包含所需的全部栈重新对齐,以及初始帧返回地址槽和参数帧,具体取决于目标。
    ///
    const min_stack_size = 4 * 1024 * 1024;
    const max_context_align: Alignment = .@"16";
    const max_context_size = max_context_align.forward(1024);
    const max_closure_size: usize = @sizeOf(AsyncClosure);
    const max_closure_align: Alignment = .of(AsyncClosure);
    const allocation_size = std.mem.alignForward(
        usize,
        max_closure_align.max(max_context_align).forward(
            max_result_align.forward(@sizeOf(Fiber)) + max_result_size + min_stack_size,
        ) + max_closure_size + max_context_size,
        std.heap.page_size_max,
    );

    fn allocate(k: *Kqueue) error{OutOfMemory}!*Fiber {
        return @ptrCast(try k.gpa.alignedAlloc(u8, .of(Fiber), allocation_size));
    }

    fn allocatedSlice(f: *Fiber) []align(@alignOf(Fiber)) u8 {
        return @as([*]align(@alignOf(Fiber)) u8, @ptrCast(f))[0..allocation_size];
    }

    fn allocatedEnd(f: *Fiber) [*]u8 {
        const allocated_slice = f.allocatedSlice();
        return allocated_slice[allocated_slice.len..].ptr;
    }

    fn resultPointer(f: *Fiber, comptime Result: type) *Result {
        return @ptrCast(@alignCast(f.resultBytes(.of(Result))));
    }

    fn resultBytes(f: *Fiber, alignment: Alignment) [*]u8 {
        return @ptrFromInt(alignment.forward(@intFromPtr(f) + @sizeOf(Fiber)));
    }

    fn enterCancelRegion(fiber: *Fiber, thread: *Thread) error{Canceled}!void {
        if (@cmpxchgStrong(
            ?*Thread,
            &fiber.cancel_thread,
            null,
            thread,
            .acq_rel,
            .acquire,
        )) |cancel_thread| {
            assert(cancel_thread == Thread.canceling);
            return error.Canceled;
        }
    }

    fn exitCancelRegion(fiber: *Fiber, thread: *Thread) void {
        if (@cmpxchgStrong(
            ?*Thread,
            &fiber.cancel_thread,
            thread,
            null,
            .acq_rel,
            .acquire,
        )) |cancel_thread| assert(cancel_thread == Thread.canceling);
    }

    const Queue = struct { head: *Fiber, tail: *Fiber };
};

fn recycle(k: *Kqueue, fiber: *Fiber) void {
    std.log.debug("recyling {*}", .{fiber});
    assert(fiber.queue_next == null);
    k.gpa.free(fiber.allocatedSlice());
}

pub const InitOptions = struct {
    n_threads: ?usize = null,
};

pub const InitError = Allocator.Error || CreateFileDescriptorError;

pub fn init(k: *Kqueue, gpa: Allocator, options: InitOptions) !void {
    assert(options.n_threads != 0);

    const n_threads = @max(1, options.n_threads orelse std.Thread.getCpuCount() catch 1);
    const threads_size = n_threads * @sizeOf(Thread);
    const idle_stack_end_offset = std.mem.alignForward(usize, threads_size + idle_stack_size, std.heap.page_size_max);
    const allocated_slice = try gpa.alignedAlloc(u8, .of(Thread), idle_stack_end_offset);
    errdefer gpa.free(allocated_slice);
    k.* = .{
        .gpa = gpa,
        .mutex = .init,
        .main_fiber_buffer = undefined,
        .threads = .{
            .allocated = @ptrCast(allocated_slice[0..threads_size]),
            .reserved = 1,
            .active = 1,
        },
    };
    const main_fiber: *Fiber = @ptrCast(&k.main_fiber_buffer);
    main_fiber.* = .{
        .required_align = {},
        .context = undefined,
        .awaiter = null,
        .queue_next = null,
        .cancel_thread = null,
        .awaiting_completions = .empty,
    };
    const main_thread = &k.threads.allocated[0];
    Thread.self = main_thread;
    const idle_stack_end: [*]align(16) usize = @ptrCast(@alignCast(allocated_slice[idle_stack_end_offset..].ptr));
    (idle_stack_end - 1)[0..1].* = .{@intFromPtr(k)};
    main_thread.* = .{
        .thread = undefined,
        .idle_context = switch (builtin.cpu.arch) {
            .aarch64 => .{
                .sp = @intFromPtr(idle_stack_end),
                .fp = 0,
                .pc = @intFromPtr(&mainIdleEntry),
            },
            .x86_64 => .{
                .rsp = @intFromPtr(idle_stack_end - 1),
                .rbp = 0,
                .rip = @intFromPtr(&mainIdleEntry),
            },
            else => @compileError("unimplemented architecture"),
        },
        .current_context = &main_fiber.context,
        .ready_queue = null,
        .kq_fd = try createFileDescriptor(),
        .idle_search_index = 1,
        .steal_ready_search_index = 1,
        .wait_queues = .empty,
    };
    errdefer closeFd(main_thread.kq_fd);
    std.log.debug("created main idle {*}", .{&main_thread.idle_context});
    std.log.debug("created main {*}", .{main_fiber});
}

pub fn deinit(k: *Kqueue) void {
    const active_threads = @atomicLoad(u32, &k.threads.active, .acquire);
    for (k.threads.allocated[0..active_threads]) |*thread| {
        const ready_fiber = @atomicLoad(?*Fiber, &thread.ready_queue, .monotonic);
        assert(ready_fiber == null or ready_fiber == Fiber.finished); // 待处理的异步操作
    }
    k.yield(null, .exit);
    const main_thread = &k.threads.allocated[0];
    const gpa = k.gpa;
    main_thread.deinit(gpa);
    const allocated_ptr: [*]align(@alignOf(Thread)) u8 = @ptrCast(@alignCast(k.threads.allocated.ptr));
    const idle_stack_end_offset = std.mem.alignForward(usize, k.threads.allocated.len * @sizeOf(Thread) + idle_stack_size, std.heap.page_size_max);
    for (k.threads.allocated[1..active_threads]) |*thread| thread.thread.join();
    gpa.free(allocated_ptr[0..idle_stack_end_offset]);
    k.* = undefined;
}

pub const CreateFileDescriptorError = error{
    /// 已达到每个进程可打开的文件描述符数量限制。
    ProcessFdQuotaExceeded,
    /// 已达到系统范围内打开文件总数的上限。
    SystemFdQuotaExceeded,
} || Io.UnexpectedError;

pub fn createFileDescriptor() CreateFileDescriptorError!posix.fd_t {
    const rc = posix.system.kqueue();
    switch (posix.errno(rc)) {
        .SUCCESS => return @intCast(rc),
        .MFILE => return error.ProcessFdQuotaExceeded,
        .NFILE => return error.SystemFdQuotaExceeded,
        else => |err| return posix.unexpectedErrno(err),
    }
}

fn findReadyFiber(k: *Kqueue, thread: *Thread) ?*Fiber {
    if (@atomicRmw(?*Fiber, &thread.ready_queue, .Xchg, Fiber.finished, .acquire)) |ready_fiber| {
        @atomicStore(?*Fiber, &thread.ready_queue, ready_fiber.queue_next, .release);
        ready_fiber.queue_next = null;
        return ready_fiber;
    }
    const active_threads = @atomicLoad(u32, &k.threads.active, .acquire);
    for (0..@min(max_steal_ready_search, active_threads)) |_| {
        defer thread.steal_ready_search_index += 1;
        if (thread.steal_ready_search_index == active_threads) thread.steal_ready_search_index = 0;
        const steal_ready_search_thread = &k.threads.allocated[0..active_threads][thread.steal_ready_search_index];
        if (steal_ready_search_thread == thread) continue;
        const ready_fiber = @atomicLoad(?*Fiber, &steal_ready_search_thread.ready_queue, .acquire) orelse continue;
        if (ready_fiber == Fiber.finished) continue;
        if (@cmpxchgWeak(
            ?*Fiber,
            &steal_ready_search_thread.ready_queue,
            ready_fiber,
            null,
            .acquire,
            .monotonic,
        )) |_| continue;
        @atomicStore(?*Fiber, &thread.ready_queue, ready_fiber.queue_next, .release);
        ready_fiber.queue_next = null;
        return ready_fiber;
    }
    // 未找到要做的工作,因此现在可以正常处理请求
    @atomicStore(?*Fiber, &thread.ready_queue, null, .monotonic);
    return null;
}

fn yield(k: *Kqueue, maybe_ready_fiber: ?*Fiber, pending_task: SwitchMessage.PendingTask) void {
    const thread: *Thread = .current();
    const ready_context = if (maybe_ready_fiber orelse k.findReadyFiber(thread)) |ready_fiber|
        &ready_fiber.context
    else
        &thread.idle_context;
    const message: SwitchMessage = .{
        .contexts = .{
            .old = thread.current_context,
            .new = ready_context,
        },
        .pending_task = pending_task,
    };
    std.log.debug("switching from {*} to {*}", .{ message.contexts.old, message.contexts.new });
    contextSwitch(&message).handle(k);
}

fn schedule(k: *Kqueue, thread: *Thread, ready_queue: Fiber.Queue) void {
    {
        var fiber = ready_queue.head;
        while (true) {
            std.log.debug("scheduling {*}", .{fiber});
            fiber = fiber.queue_next orelse break;
        }
        assert(fiber == ready_queue.tail);
    }
    // 必须先初始化前一个 `Thread` 的共享字段,再将后续线程标记为活动。
    const new_thread_index = @atomicLoad(u32, &k.threads.active, .acquire);
    for (0..@min(max_idle_search, new_thread_index)) |_| {
        defer thread.idle_search_index += 1;
        if (thread.idle_search_index == new_thread_index) thread.idle_search_index = 0;
        const idle_search_thread = &k.threads.allocated[0..new_thread_index][thread.idle_search_index];
        if (idle_search_thread == thread) continue;
        if (@cmpxchgWeak(
            ?*Fiber,
            &idle_search_thread.ready_queue,
            null,
            ready_queue.head,
            .release,
            .monotonic,
        )) |_| continue;
        const changes = [_]posix.Kevent{
            .{
                .ident = 0,
                .filter = std.c.EVFILT.USER,
                .flags = std.c.EV.ADD | std.c.EV.ONESHOT,
                .fflags = std.c.NOTE.TRIGGER,
                .data = 0,
                .udata = @backingInt(Completion.UserData.wakeup),
            },
        };
        // 若发生错误,只会使调度效果变差。
        _ = kevent(idle_search_thread.kq_fd, &changes, &.{}, null) catch |err| {
            // TODO 为取消操作处理 EINTR
            @panic(@errorName(err)); // TODO
        };
        return;
    }
    spawn_thread: {
        // 重试之前,先前失败的预留必须已经完成
        if (new_thread_index == k.threads.allocated.len or @cmpxchgWeak(
            u32,
            &k.threads.reserved,
            new_thread_index,
            new_thread_index + 1,
            .acquire,
            .monotonic,
        ) != null) break :spawn_thread;
        const new_thread = &k.threads.allocated[new_thread_index];
        const next_thread_index = new_thread_index + 1;
        new_thread.* = .{
            .thread = undefined,
            .idle_context = undefined,
            .current_context = &new_thread.idle_context,
            .ready_queue = ready_queue.head,
            .kq_fd = createFileDescriptor() catch |err| {
                @atomicStore(u32, &k.threads.reserved, new_thread_index, .release);
                // 放弃保留资格后,不得再访问 `thread`
                std.log.warn("unable to create worker thread due to kqueue init failure: {t}", .{err});
                break :spawn_thread;
            },
            .idle_search_index = 0,
            .steal_ready_search_index = 0,
            .wait_queues = .empty,
        };
        new_thread.thread = std.Thread.spawn(.{
            .stack_size = idle_stack_size,
            .allocator = k.gpa,
        }, threadEntry, .{ k, new_thread_index }) catch |err| {
            closeFd(new_thread.kq_fd);
            @atomicStore(u32, &k.threads.reserved, new_thread_index, .release);
            // 放弃保留资格后,不得再访问 `thread`
            std.log.warn("unable to create worker thread due spawn failure: {s}", .{@errorName(err)});
            break :spawn_thread;
        };
        // 必须在标记为活动前初始化 `Thread` 的共享字段
        @atomicStore(u32, &k.threads.active, next_thread_index, .release);
        return;
    }
    // 无人需要它,因此直接加入自身队列
    while (@cmpxchgWeak(
        ?*Fiber,
        &thread.ready_queue,
        ready_queue.tail.queue_next,
        ready_queue.head,
        .acq_rel,
        .acquire,
    )) |old_head| ready_queue.tail.queue_next = old_head;
}

fn mainIdle(k: *Kqueue, message: *const SwitchMessage) callconv(.withStackAlign(.c, @max(@alignOf(Thread), @alignOf(Io.fiber.Context)))) noreturn {
    message.handle(k);
    k.idle(&k.threads.allocated[0]);
    k.yield(@ptrCast(&k.main_fiber_buffer), .nothing);
    unreachable; // 切换至已终止的纤程
}

fn threadEntry(k: *Kqueue, index: u32) void {
    const thread: *Thread = &k.threads.allocated[index];
    Thread.self = thread;
    std.log.debug("created thread idle {*}", .{&thread.idle_context});
    k.idle(thread);
    thread.deinit(k.gpa);
}

const Completion = struct {
    const UserData = enum(usize) {
        unused,
        wakeup,
        cleanup,
        exit,
        /// *Fiber
        _,
    };
    /// 对应 Kevent 字段。
    flags: u16,
    /// 对应 Kevent 字段。
    fflags: u32,
    /// 对应 Kevent 字段。
    data: isize,
};

fn idle(k: *Kqueue, thread: *Thread) void {
    var events_buffer: [changes_buffer_len]posix.Kevent = undefined;
    var maybe_ready_fiber: ?*Fiber = null;
    while (true) {
        while (maybe_ready_fiber orelse k.findReadyFiber(thread)) |ready_fiber| {
            k.yield(ready_fiber, .nothing);
            maybe_ready_fiber = null;
        }
        const n = kevent(thread.kq_fd, &.{}, &events_buffer, null) catch |err| {
            // TODO 为取消操作处理 EINTR
            @panic(@errorName(err)); // TODO
        };
        var maybe_ready_queue: ?Fiber.Queue = null;
        for (events_buffer[0..n]) |event| switch (@as(Completion.UserData, @fromBackingInt(@intCast(event.udata)))) {
            .unused => unreachable, // 是否有无效提交进入队列?
            .wakeup => {},
            .cleanup => @panic("failed to notify other threads that we are exiting"),
            .exit => {
                assert(maybe_ready_fiber == null and maybe_ready_queue == null); // 待处理的异步操作
                return;
            },
            _ => {
                const event_head_fiber: *Fiber = @ptrFromInt(event.udata);
                const event_tail_fiber = thread.wait_queues.fetchSwapRemove(.{
                    .ident = event.ident,
                    .filter = event.filter,
                }).?.value;
                assert(event_tail_fiber.queue_next == null);

                // TODO 重新评估此逻辑
                event_head_fiber.resultPointer(Completion).* = .{
                    .flags = event.flags,
                    .fflags = event.fflags,
                    .data = event.data,
                };

                queue_ready: {
                    const head: *Fiber = if (maybe_ready_fiber == null) f: {
                        maybe_ready_fiber = event_head_fiber;
                        const next = event_head_fiber.queue_next orelse break :queue_ready;
                        event_head_fiber.queue_next = null;
                        break :f next;
                    } else event_head_fiber;

                    if (maybe_ready_queue) |*ready_queue| {
                        ready_queue.tail.queue_next = head;
                        ready_queue.tail = event_tail_fiber;
                    } else {
                        maybe_ready_queue = .{ .head = head, .tail = event_tail_fiber };
                    }
                }
            },
        };
        if (maybe_ready_queue) |ready_queue| k.schedule(thread, ready_queue);
    }
}

const SwitchMessage = struct {
    contexts: Io.fiber.Switch,
    pending_task: PendingTask,

    const PendingTask = union(enum) {
        nothing,
        reschedule,
        recycle: *Fiber,
        register_awaiter: *?*Fiber,
        exit,
    };

    fn handle(message: *const SwitchMessage, k: *Kqueue) void {
        const thread: *Thread = .current();
        thread.current_context = message.contexts.new;
        switch (message.pending_task) {
            .nothing => {},
            .reschedule => if (message.contexts.old != &thread.idle_context) {
                const prev_fiber: *Fiber = @alignCast(@fieldParentPtr("context", message.contexts.old));
                assert(prev_fiber.queue_next == null);
                k.schedule(thread, .{ .head = prev_fiber, .tail = prev_fiber });
            },
            .recycle => |fiber| {
                k.recycle(fiber);
            },
            .register_awaiter => |awaiter| {
                const prev_fiber: *Fiber = @alignCast(@fieldParentPtr("context", message.contexts.old));
                assert(prev_fiber.queue_next == null);
                if (@atomicRmw(?*Fiber, awaiter, .Xchg, prev_fiber, .acq_rel) == Fiber.finished)
                    k.schedule(thread, .{ .head = prev_fiber, .tail = prev_fiber });
            },
            .exit => for (k.threads.allocated[0..@atomicLoad(u32, &k.threads.active, .acquire)]) |*each_thread| {
                const changes = [_]posix.Kevent{
                    .{
                        .ident = 0,
                        .filter = std.c.EVFILT.USER,
                        .flags = std.c.EV.ADD | std.c.EV.ONESHOT,
                        .fflags = std.c.NOTE.TRIGGER,
                        .data = 0,
                        .udata = @backingInt(Completion.UserData.exit),
                    },
                };
                _ = kevent(each_thread.kq_fd, &changes, &.{}, null) catch |err| {
                    // TODO 为取消操作处理 EINTR
                    @panic(@errorName(err)); // TODO
                };
            },
        }
    }
};

inline fn contextSwitch(message: *const SwitchMessage) *const SwitchMessage {
    return @fieldParentPtr("contexts", Io.fiber.contextSwitch(&message.contexts));
}

fn mainIdleEntry() callconv(.naked) void {
    switch (builtin.cpu.arch) {
        .x86_64 => asm volatile (
            \\ movq (%%rsp), %%rdi
            \\ jmp %[mainIdle:P]
            :
            : [mainIdle] "X" (&mainIdle),
        ),
        .aarch64 => asm volatile (
            \\ ldr x0, [sp, #-8]
            \\ b %[mainIdle]
            :
            : [mainIdle] "X" (&mainIdle),
        ),
        else => |arch| @compileError("unimplemented architecture: " ++ @tagName(arch)),
    }
}

fn fiberEntry() callconv(.naked) void {
    switch (builtin.cpu.arch) {
        .x86_64 => asm volatile (
            \\ leaq 8(%%rsp), %%rdi
            \\ jmp %[AsyncClosure_call:P]
            :
            : [AsyncClosure_call] "X" (&AsyncClosure.call),
        ),
        .aarch64 => asm volatile (
            \\ mov x0, sp
            \\ b %[AsyncClosure_call]
            :
            : [AsyncClosure_call] "X" (&AsyncClosure.call),
        ),
        else => |arch| @compileError("unimplemented architecture: " ++ @tagName(arch)),
    }
}

const AsyncClosure = struct {
    kqueue: *Kqueue,
    fiber: *Fiber,
    start: *const fn (context: *const anyopaque, result: *anyopaque) void,
    result_align: Alignment,
    already_awaited: bool,

    fn contextPointer(closure: *AsyncClosure) [*]align(Fiber.max_context_align.toByteUnits()) u8 {
        return @alignCast(@as([*]u8, @ptrCast(closure)) + @sizeOf(AsyncClosure));
    }

    fn call(closure: *AsyncClosure, message: *const SwitchMessage) callconv(.withStackAlign(.c, @alignOf(AsyncClosure))) noreturn {
        message.handle(closure.kqueue);
        const fiber = closure.fiber;
        std.log.debug("{*} performing async", .{fiber});
        closure.start(closure.contextPointer(), fiber.resultBytes(closure.result_align));
        const awaiter = @atomicRmw(?*Fiber, &fiber.awaiter, .Xchg, Fiber.finished, .acq_rel);
        const ready_awaiter = r: {
            const a = awaiter orelse break :r null;
            if (@atomicRmw(bool, &closure.already_awaited, .Xchg, true, .acq_rel)) break :r null;
            break :r a;
        };
        closure.kqueue.yield(ready_awaiter, .nothing);
        unreachable; // 切换至已终止的纤程
    }

    fn fromFiber(fiber: *Fiber) *AsyncClosure {
        return @ptrFromInt(Fiber.max_context_align.max(.of(AsyncClosure)).backward(
            @intFromPtr(fiber.allocatedEnd()) - Fiber.max_context_size,
        ) - @sizeOf(AsyncClosure));
    }
};

pub fn io(k: *Kqueue) Io {
    return .{
        .userdata = k,
        .vtable = &.{
            .async = async,
            .concurrent = concurrent,
            .await = await,
            .cancel = cancel,

            .groupAsync = groupAsync,
            .groupConcurrent = groupConcurrent,
            .groupAwait = groupAwait,
            .groupCancel = groupCancel,

            .dirCreateDir = dirCreateDir,
            .dirCreateDirPath = dirCreateDirPath,
            .dirCreateDirPathOpen = dirCreateDirPathOpen,
            .dirStat = dirStat,
            .dirStatFile = dirStatFile,

            .fileStat = fileStat,
            .dirAccess = dirAccess,
            .dirCreateFile = dirCreateFile,
            .dirOpenFile = dirOpenFile,
            .dirOpenDir = dirOpenDir,
            .dirClose = dirClose,
            .fileClose = fileClose,
            .fileWriteStreaming = fileWriteStreaming,
            .fileWritePositional = fileWritePositional,
            .fileReadStreaming = fileReadStreaming,
            .fileReadPositional = fileReadPositional,
            .fileSeekBy = fileSeekBy,
            .fileSeekTo = fileSeekTo,

            .now = now,
            .sleep = sleep,

            .netListenIp = netListenIp,
            .netListenUnix = netListenUnix,
            .netAccept = netAccept,
            .netBindIp = netBindIp,
            .netConnectIp = netConnectIp,
            .netConnectUnix = netConnectUnix,
            .netShutdown = netShutdown,
            .netRead = netRead,
            .netSend = netSend,
            .netReceive = netReceive,
            .netInterfaceNameResolve = netInterfaceNameResolve,
            .netInterfaceName = netInterfaceName,
            .netLookup = netLookup,
        },
    };
}

fn async(
    userdata: ?*anyopaque,
    result: []u8,
    result_alignment: std.mem.Alignment,
    context: []const u8,
    context_alignment: std.mem.Alignment,
    start: *const fn (context: *const anyopaque, result: *anyopaque) void,
) ?*Io.AnyFuture {
    return concurrent(userdata, result.len, result_alignment, context, context_alignment, start) catch {
        start(context.ptr, result.ptr);
        return null;
    };
}

fn concurrent(
    userdata: ?*anyopaque,
    result_len: usize,
    result_alignment: Alignment,
    context: []const u8,
    context_alignment: Alignment,
    start: *const fn (context: *const anyopaque, result: *anyopaque) void,
) Io.ConcurrentError!*Io.AnyFuture {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    assert(result_alignment.compare(.lte, Fiber.max_result_align)); // TODO
    assert(context_alignment.compare(.lte, Fiber.max_context_align)); // TODO
    assert(result_len <= Fiber.max_result_size); // TODO
    assert(context.len <= Fiber.max_context_size); // TODO

    const fiber = Fiber.allocate(k) catch return error.ConcurrencyUnavailable;
    std.log.debug("allocated {*}", .{fiber});

    const closure: *AsyncClosure = .fromFiber(fiber);
    fiber.* = .{
        .required_align = {},
        .context = switch (builtin.cpu.arch) {
            .x86_64 => .{
                .rsp = @intFromPtr(closure) - @sizeOf(usize),
                .rbp = 0,
                .rip = @intFromPtr(&fiberEntry),
            },
            .aarch64 => .{
                .sp = @intFromPtr(closure),
                .fp = 0,
                .pc = @intFromPtr(&fiberEntry),
            },
            else => |arch| @compileError("unimplemented architecture: " ++ @tagName(arch)),
        },
        .awaiter = null,
        .queue_next = null,
        .cancel_thread = null,
        .awaiting_completions = .empty,
    };
    closure.* = .{
        .kqueue = k,
        .fiber = fiber,
        .start = start,
        .result_align = result_alignment,
        .already_awaited = false,
    };
    @memcpy(closure.contextPointer(), context);

    k.schedule(.current(), .{ .head = fiber, .tail = fiber });
    return @ptrCast(fiber);
}

fn await(
    userdata: ?*anyopaque,
    any_future: *Io.AnyFuture,
    result: []u8,
    result_alignment: std.mem.Alignment,
) void {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    const future_fiber: *Fiber = @ptrCast(@alignCast(any_future));
    if (@atomicLoad(?*Fiber, &future_fiber.awaiter, .acquire) != Fiber.finished)
        k.yield(null, .{ .register_awaiter = &future_fiber.awaiter });
    @memcpy(result, future_fiber.resultBytes(result_alignment));
    k.recycle(future_fiber);
}

fn cancel(
    userdata: ?*anyopaque,
    any_future: *Io.AnyFuture,
    result: []u8,
    result_alignment: std.mem.Alignment,
) void {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = any_future;
    _ = result;
    _ = result_alignment;
    @panic("TODO");
}

fn cancelRequested(userdata: ?*anyopaque) bool {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    return false; // TODO
}

fn groupAsync(
    userdata: ?*anyopaque,
    type_erased: *Io.Group,
    context: []const u8,
    context_alignment: Alignment,
    start: *const fn (context: *const anyopaque) void,
) void {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = type_erased;
    _ = context;
    _ = context_alignment;
    _ = start;
    @panic("TODO");
}

fn groupConcurrent(
    userdata: ?*anyopaque,
    type_erased: *Io.Group,
    context: []const u8,
    context_alignment: Alignment,
    start: *const fn (context: *const anyopaque) void,
) Io.ConcurrentError!void {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = type_erased;
    _ = context;
    _ = context_alignment;
    _ = start;
    @panic("TODO");
}

fn groupAwait(userdata: ?*anyopaque, type_erased: *Io.Group, initial_token: *anyopaque) Io.Cancelable!void {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = type_erased;
    _ = initial_token;
    @panic("TODO");
}

fn groupCancel(userdata: ?*anyopaque, group: *Io.Group, token: *anyopaque) void {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = group;
    _ = token;
    @panic("TODO");
}

fn dirCreateDir(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, permissions: Dir.Permissions) Dir.CreateDirError!void {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = dir;
    _ = sub_path;
    _ = permissions;
    @panic("TODO");
}

fn dirCreateDirPath(
    userdata: ?*anyopaque,
    dir: Dir,
    sub_path: []const u8,
    permissions: Dir.Permissions,
) Dir.CreateDirPathError!Dir.CreatePathStatus {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = dir;
    _ = sub_path;
    _ = permissions;
    @panic("TODO");
}

fn dirCreateDirPathOpen(
    userdata: ?*anyopaque,
    dir: Dir,
    sub_path: []const u8,
    permissions: Dir.Permissions,
    options: Dir.OpenOptions,
) Dir.CreateDirPathOpenError!Dir {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = dir;
    _ = sub_path;
    _ = permissions;
    _ = options;
    @panic("TODO");
}

fn dirStat(userdata: ?*anyopaque, dir: Dir) Dir.StatError!Dir.Stat {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = dir;
    @panic("TODO");
}

fn dirStatFile(
    userdata: ?*anyopaque,
    dir: Dir,
    sub_path: []const u8,
    options: Dir.StatFileOptions,
) Dir.StatFileError!File.Stat {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = dir;
    _ = sub_path;
    _ = options;
    @panic("TODO");
}
fn dirAccess(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.AccessOptions) Dir.AccessError!void {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = dir;
    _ = sub_path;
    _ = options;
    @panic("TODO");
}
fn dirCreateFile(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, flags: Dir.CreateFileOptions) File.OpenError!File {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = dir;
    _ = sub_path;
    _ = flags;
    @panic("TODO");
}
fn dirOpenFile(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, flags: Dir.OpenFileOptions) File.OpenError!File {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = dir;
    _ = sub_path;
    _ = flags;
    @panic("TODO");
}
fn dirOpenDir(userdata: ?*anyopaque, dir: Dir, sub_path: []const u8, options: Dir.OpenOptions) Dir.OpenError!Dir {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = dir;
    _ = sub_path;
    _ = options;
    @panic("TODO");
}
fn dirClose(userdata: ?*anyopaque, dirs: []const Dir) void {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = dirs;
    @panic("TODO");
}
fn fileStat(userdata: ?*anyopaque, file: File) File.StatError!File.Stat {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = file;
    @panic("TODO");
}

fn fileClose(userdata: ?*anyopaque, files: []const File) void {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = files;
    @panic("TODO");
}

fn fileWriteStreaming(
    userdata: ?*anyopaque,
    file: File,
    header: []const u8,
    data: []const []const u8,
    splat: usize,
) File.Writer.Error!usize {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = file;
    _ = header;
    _ = data;
    _ = splat;
    @panic("TODO");
}

fn fileWritePositional(
    userdata: ?*anyopaque,
    file: File,
    header: []const u8,
    data: []const []const u8,
    splat: usize,
    offset: u64,
) File.WritePositionalError!usize {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = file;
    _ = header;
    _ = data;
    _ = splat;
    _ = offset;
    @panic("TODO");
}

fn fileReadStreaming(userdata: ?*anyopaque, file: File, data: []const []u8) File.Reader.Error!usize {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = file;
    _ = data;
    @panic("TODO");
}

fn fileReadPositional(userdata: ?*anyopaque, file: File, data: []const []u8, offset: u64) File.ReadPositionalError!usize {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = file;
    _ = data;
    _ = offset;
    @panic("TODO");
}
fn fileSeekBy(userdata: ?*anyopaque, file: File, relative_offset: i64) File.SeekError!void {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = file;
    _ = relative_offset;
    @panic("TODO");
}
fn fileSeekTo(userdata: ?*anyopaque, file: File, absolute_offset: u64) File.SeekError!void {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = file;
    _ = absolute_offset;
    @panic("TODO");
}

fn now(userdata: ?*anyopaque, clock: Io.Clock) Io.Clock.Error!Io.Timestamp {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = clock;
    @panic("TODO");
}
fn sleep(userdata: ?*anyopaque, timeout: Io.Timeout) Io.SleepError!void {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = timeout;
    @panic("TODO");
}

fn netListenIp(
    userdata: ?*anyopaque,
    address: *const net.IpAddress,
    options: net.IpAddress.ListenOptions,
) net.IpAddress.ListenError!net.Socket {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = address;
    _ = options;
    @panic("TODO");
}
fn netAccept(userdata: ?*anyopaque, server: net.Socket.Handle, options: net.Server.AcceptOptions) net.Server.AcceptError!net.Socket {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = server;
    _ = options;
    @panic("TODO");
}
fn netBindIp(
    userdata: ?*anyopaque,
    address: *const net.IpAddress,
    options: net.IpAddress.BindOptions,
) net.IpAddress.BindError!net.Socket {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    const family = Io.Threaded.posixAddressFamily(address);
    const socket_fd = try openSocketPosix(k, family, options);
    errdefer closeFd(socket_fd);
    var storage: Io.Threaded.PosixAddress = undefined;
    var addr_len = Io.Threaded.addressToPosix(address, &storage);
    try posixBind(k, socket_fd, &storage.any, addr_len);
    if (options.allow_broadcast) try setSocketOption(k, socket_fd, posix.SOL.SOCKET, posix.SO.BROADCAST, 1);
    try posixGetSockName(k, socket_fd, &storage.any, &addr_len);
    return .{ .handle = socket_fd, .address = Io.Threaded.addressFromPosix(&storage) };
}
fn netConnectIp(userdata: ?*anyopaque, address: *const net.IpAddress, options: net.IpAddress.ConnectOptions) net.IpAddress.ConnectError!net.Socket {
    if (options.timeout != .none) @panic("TODO");
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    const family = Io.Threaded.posixAddressFamily(address);
    const socket_fd = try openSocketPosix(k, family, .{
        .mode = options.mode,
        .protocol = options.protocol,
    });
    errdefer closeFd(socket_fd);
    var storage: Io.Threaded.PosixAddress = undefined;
    var addr_len = Io.Threaded.addressToPosix(address, &storage);
    try posixConnect(k, socket_fd, &storage.any, addr_len);
    try posixGetSockName(k, socket_fd, &storage.any, &addr_len);
    return .{ .handle = socket_fd, .address = Io.Threaded.addressFromPosix(&storage) };
}

fn posixConnect(k: *Kqueue, socket_fd: posix.socket_t, addr: *const posix.sockaddr, addr_len: posix.socklen_t) !void {
    while (true) {
        try k.checkCancel();
        switch (posix.errno(posix.system.connect(socket_fd, addr, addr_len))) {
            .SUCCESS => return,
            .INTR => continue,
            .CANCELED => return error.Canceled,
            .AGAIN => @panic("TODO"),
            .INPROGRESS => return, // 由于 TCP 快速打开,稍后才会发现可能的错误。

            .ADDRNOTAVAIL => return error.AddressUnavailable,
            .AFNOSUPPORT => return error.AddressFamilyUnsupported,
            .ALREADY => return error.ConnectionPending,
            .BADF => |err| return errnoBug(err), // 文件描述符在关闭后被使用。
            .CONNREFUSED => return error.ConnectionRefused,
            .CONNRESET => return error.ConnectionResetByPeer,
            .FAULT => |err| return errnoBug(err),
            .ISCONN => |err| return errnoBug(err),
            .HOSTUNREACH => return error.HostUnreachable,
            .NETUNREACH => return error.NetworkUnreachable,
            .NOTSOCK => |err| return errnoBug(err),
            .PROTOTYPE => |err| return errnoBug(err),
            .TIMEDOUT => return error.Timeout,
            .CONNABORTED => |err| return errnoBug(err),
            .ACCES => return error.AccessDenied,
            .PERM => |err| return errnoBug(err),
            .NOENT => |err| return errnoBug(err),
            .NETDOWN => return error.NetworkDown,
            else => |err| return posix.unexpectedErrno(err),
        }
    }
}

fn netListenUnix(
    userdata: ?*anyopaque,
    unix_address: *const net.UnixAddress,
    options: net.UnixAddress.ListenOptions,
) net.UnixAddress.ListenError!net.Socket.Handle {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = unix_address;
    _ = options;
    @panic("TODO");
}
fn netConnectUnix(
    userdata: ?*anyopaque,
    unix_address: *const net.UnixAddress,
) net.UnixAddress.ConnectError!net.Socket.Handle {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = unix_address;
    @panic("TODO");
}

fn netSend(
    userdata: ?*anyopaque,
    handle: net.Socket.Handle,
    outgoing_messages: []net.OutgoingMessage,
    flags: net.SendFlags,
) struct { ?net.Socket.SendError, usize } {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));

    const posix_flags: u32 =
        @as(u32, if (@hasDecl(posix.MSG, "CONFIRM") and flags.confirm) posix.MSG.CONFIRM else 0) |
        @as(u32, if (@hasDecl(posix.MSG, "DONTROUTE") and flags.dont_route) posix.MSG.DONTROUTE else 0) |
        @as(u32, if (@hasDecl(posix.MSG, "EOR") and flags.eor) posix.MSG.EOR else 0) |
        @as(u32, if (@hasDecl(posix.MSG, "OOB") and flags.oob) posix.MSG.OOB else 0) |
        @as(u32, if (@hasDecl(posix.MSG, "FASTOPEN") and flags.fastopen) posix.MSG.FASTOPEN else 0) |
        posix.MSG.NOSIGNAL;

    for (outgoing_messages, 0..) |*msg, i| {
        netSendOne(k, handle, msg, posix_flags) catch |err| return .{ err, i };
    }

    return .{ null, outgoing_messages.len };
}

fn netSendOne(
    k: *Kqueue,
    handle: net.Socket.Handle,
    message: *net.OutgoingMessage,
    flags: u32,
) net.Socket.SendError!void {
    var addr: Io.Threaded.PosixAddress = undefined;
    var iovec: posix.iovec_const = .{ .base = @constCast(message.data_ptr), .len = message.data_len };
    const msg: posix.msghdr_const = .{
        .name = &addr.any,
        .namelen = Io.Threaded.addressToPosix(message.address, &addr),
        .iov = (&iovec)[0..1],
        .iovlen = 1,
        // 如果该指针无效,即使 controllen 为零,操作系统也返回 EINVAL。
        .control = if (message.control.len == 0) null else @constCast(message.control.ptr),
        .controllen = @intCast(message.control.len),
        .flags = 0,
    };
    while (true) {
        try k.checkCancel();
        const rc = posix.system.sendmsg(handle, &msg, flags);
        switch (posix.errno(rc)) {
            .SUCCESS => {
                message.data_len = @intCast(rc);
                return;
            },
            .INTR => continue,
            .CANCELED => return error.Canceled,
            .AGAIN => @panic("TODO register kevent"),

            .ACCES => return error.AccessDenied,
            .ALREADY => return error.FastOpenAlreadyInProgress,
            .BADF => |err| return errnoBug(err), // 文件描述符在关闭后被使用。
            .CONNRESET => return error.ConnectionResetByPeer,
            .DESTADDRREQ => |err| return errnoBug(err),
            .FAULT => |err| return errnoBug(err),
            .INVAL => |err| return errnoBug(err),
            .ISCONN => |err| return errnoBug(err),
            .MSGSIZE => return error.MessageOversize,
            .NOBUFS => return error.SystemResources,
            .NOMEM => return error.SystemResources,
            .NOTSOCK => |err| return errnoBug(err),
            .OPNOTSUPP => |err| return errnoBug(err),
            .PIPE => return error.SocketUnconnected,
            .AFNOSUPPORT => return error.AddressFamilyUnsupported,
            .HOSTUNREACH => return error.HostUnreachable,
            .NETUNREACH => return error.NetworkUnreachable,
            .NOTCONN => return error.SocketUnconnected,
            .NETDOWN => return error.NetworkDown,
            else => |err| return posix.unexpectedErrno(err),
        }
    }
}

fn netReceive(
    userdata: ?*anyopaque,
    handle: net.Socket.Handle,
    message_buffer: []net.IncomingMessage,
    data_buffer: []u8,
    flags: net.ReceiveFlags,
    timeout: Io.Timeout,
) struct { ?net.Socket.ReceiveTimeoutError, usize } {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = handle;
    _ = message_buffer;
    _ = data_buffer;
    _ = flags;
    _ = timeout;
    @panic("TODO");
}

fn netRead(userdata: ?*anyopaque, fd: net.Socket.Handle, data: [][]u8) net.Stream.Reader.Error!usize {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));

    var iovecs_buffer: [max_iovecs_len]posix.iovec = undefined;
    var i: usize = 0;
    for (data) |buf| {
        if (iovecs_buffer.len - i == 0) break;
        if (buf.len != 0) {
            iovecs_buffer[i] = .{ .base = buf.ptr, .len = buf.len };
            i += 1;
        }
    }
    const dest = iovecs_buffer[0..i];
    assert(dest[0].len > 0);

    while (true) {
        try k.checkCancel();
        const rc = posix.system.readv(fd, dest.ptr, @intCast(dest.len));
        switch (posix.errno(rc)) {
            .SUCCESS => return @intCast(rc),
            .INTR => continue,
            .CANCELED => return error.Canceled,
            .AGAIN => {
                const thread: *Thread = .current();
                const fiber = thread.currentFiber();
                const ident: u32 = @bitCast(fd);
                const filter = std.c.EVFILT.READ;
                const gop = thread.wait_queues.getOrPut(k.gpa, .{
                    .ident = ident,
                    .filter = filter,
                }) catch return error.SystemResources;
                if (gop.found_existing) {
                    const tail_fiber = gop.value_ptr.*;
                    assert(tail_fiber.queue_next == null);
                    tail_fiber.queue_next = fiber;
                    gop.value_ptr.* = fiber;
                } else {
                    gop.value_ptr.* = fiber;
                    const changes = [_]posix.Kevent{
                        .{
                            .ident = ident,
                            .filter = filter,
                            .flags = std.c.EV.ADD | std.c.EV.ONESHOT,
                            .fflags = 0,
                            .data = 0,
                            .udata = @intFromPtr(fiber),
                        },
                    };
                    assert(0 == (kevent(thread.kq_fd, &changes, &.{}, null) catch |err| {
                        // TODO 为取消操作处理 EINTR
                        @panic(@errorName(err)); // TODO
                    }));
                }
                yield(k, null, .nothing);
                continue;
            },

            .INVAL => |err| return errnoBug(err),
            .FAULT => |err| return errnoBug(err),
            .BADF => |err| return errnoBug(err), // 文件描述符在关闭后被使用。
            .NOBUFS => return error.SystemResources,
            .NOMEM => return error.SystemResources,
            .NOTCONN => return error.SocketUnconnected,
            .CONNRESET => return error.ConnectionResetByPeer,
            .TIMEDOUT => return error.Timeout,
            .PIPE => return error.SocketUnconnected,
            .NETDOWN => return error.NetworkDown,
            else => |err| return posix.unexpectedErrno(err),
        }
    }
}

fn netShutdown(userdata: ?*anyopaque, handle: net.Socket.Handle, how: net.ShutdownHow) net.ShutdownError!void {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = handle;
    _ = how;
    @panic("TODO");
}

fn netInterfaceNameResolve(
    userdata: ?*anyopaque,
    name: *const net.Interface.Name,
) net.Interface.Name.ResolveError!net.Interface {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = name;
    @panic("TODO");
}

fn netInterfaceName(userdata: ?*anyopaque, interface: net.Interface) net.Interface.NameError!net.Interface.Name {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = interface;
    @panic("TODO");
}

fn netLookup(
    userdata: ?*anyopaque,
    host_name: net.HostName,
    resolved: *Io.Queue(net.HostName.LookupResult),
    options: net.HostName.LookupOptions,
) net.HostName.LookupError!void {
    const k: *Kqueue = @ptrCast(@alignCast(userdata));
    _ = k;
    _ = host_name;
    _ = resolved;
    _ = options;
    @panic("TODO");
}

fn openSocketPosix(
    k: *Kqueue,
    family: posix.sa_family_t,
    options: IpAddress.BindOptions,
) error{
    AddressFamilyUnsupported,
    ProtocolUnsupportedBySystem,
    ProcessFdQuotaExceeded,
    SystemFdQuotaExceeded,
    SystemResources,
    ProtocolUnsupportedByAddressFamily,
    SocketModeUnsupported,
    OptionUnsupported,
    Unexpected,
    Canceled,
}!posix.socket_t {
    const mode, const protocol = try posixSocketModeProtocol(family, options.mode, options.protocol);
    const socket_fd = while (true) {
        try k.checkCancel();
        const flags: u32 = mode | if (Io.Threaded.socket_flags_unsupported) 0 else posix.SOCK.CLOEXEC;
        const socket_rc = posix.system.socket(family, flags, protocol);
        switch (posix.errno(socket_rc)) {
            .SUCCESS => {
                const fd: posix.fd_t = @intCast(socket_rc);
                errdefer closeFd(fd);
                if (Io.Threaded.socket_flags_unsupported) {
                    while (true) {
                        try k.checkCancel();
                        switch (posix.errno(posix.system.fcntl(fd, posix.F.SETFD, @as(usize, posix.FD_CLOEXEC)))) {
                            .SUCCESS => break,
                            .INTR => continue,
                            .CANCELED => return error.Canceled,
                            else => |err| return posix.unexpectedErrno(err),
                        }
                    }

                    var fl_flags: usize = while (true) {
                        try k.checkCancel();
                        const rc = posix.system.fcntl(fd, posix.F.GETFL, @as(usize, 0));
                        switch (posix.errno(rc)) {
                            .SUCCESS => break @intCast(rc),
                            .INTR => continue,
                            .CANCELED => return error.Canceled,
                            else => |err| return posix.unexpectedErrno(err),
                        }
                    };
                    fl_flags |= @as(usize, 1 << @bitOffsetOf(posix.O, "NONBLOCK"));
                    while (true) {
                        try k.checkCancel();
                        switch (posix.errno(posix.system.fcntl(fd, posix.F.SETFL, fl_flags))) {
                            .SUCCESS => break,
                            .INTR => continue,
                            .CANCELED => return error.Canceled,
                            else => |err| return posix.unexpectedErrno(err),
                        }
                    }
                }
                break fd;
            },
            .INTR => continue,
            .CANCELED => return error.Canceled,

            .AFNOSUPPORT => return error.AddressFamilyUnsupported,
            .INVAL => return error.ProtocolUnsupportedBySystem,
            .MFILE => return error.ProcessFdQuotaExceeded,
            .NFILE => return error.SystemFdQuotaExceeded,
            .NOBUFS => return error.SystemResources,
            .NOMEM => return error.SystemResources,
            .PROTONOSUPPORT => return error.ProtocolUnsupportedByAddressFamily,
            .PROTOTYPE => return error.SocketModeUnsupported,
            else => |err| return posix.unexpectedErrno(err),
        }
    };
    errdefer closeFd(socket_fd);

    if (options.ip6_only) |ip6_only| {
        if (posix.IPV6 == void) return error.OptionUnsupported;
        try setSocketOption(k, socket_fd, posix.IPPROTO.IPV6, posix.IPV6.V6ONLY, @intFromBool(ip6_only));
    }

    return socket_fd;
}

fn posixBind(
    k: *Kqueue,
    socket_fd: posix.socket_t,
    addr: *const posix.sockaddr,
    addr_len: posix.socklen_t,
) !void {
    while (true) {
        try k.checkCancel();
        switch (posix.errno(posix.system.bind(socket_fd, addr, addr_len))) {
            .SUCCESS => break,
            .INTR => continue,
            .CANCELED => return error.Canceled,

            .ACCES => return error.AccessDenied,
            .ADDRINUSE => return error.AddressInUse,
            .BADF => |err| return errnoBug(err), // 文件描述符在关闭后被使用。
            .INVAL => |err| return errnoBug(err), // 无效参数
            .NOTSOCK => |err| return errnoBug(err), // 无效的 `sockfd`
            .AFNOSUPPORT => return error.AddressFamilyUnsupported,
            .ADDRNOTAVAIL => return error.AddressUnavailable,
            .FAULT => |err| return errnoBug(err), // 无效的 `addr` 指针
            .NOMEM => return error.SystemResources,
            else => |err| return posix.unexpectedErrno(err),
        }
    }
}

fn posixGetSockName(k: *Kqueue, socket_fd: posix.fd_t, addr: *posix.sockaddr, addr_len: *posix.socklen_t) !void {
    while (true) {
        try k.checkCancel();
        switch (posix.errno(posix.system.getsockname(socket_fd, addr, addr_len))) {
            .SUCCESS => break,
            .INTR => continue,
            .CANCELED => return error.Canceled,

            .BADF => |err| return errnoBug(err), // 文件描述符在关闭后被使用。
            .FAULT => |err| return errnoBug(err),
            .INVAL => |err| return errnoBug(err), // 无效参数
            .NOTSOCK => |err| return errnoBug(err), // 始终存在竞态条件
            .NOBUFS => return error.SystemResources,
            else => |err| return posix.unexpectedErrno(err),
        }
    }
}

fn setSocketOption(k: *Kqueue, fd: posix.fd_t, level: i32, opt_name: u32, option: u32) !void {
    const o: []const u8 = @ptrCast(&option);
    while (true) {
        try k.checkCancel();
        switch (posix.errno(posix.system.setsockopt(fd, level, opt_name, o.ptr, @intCast(o.len)))) {
            .SUCCESS => return,
            .INTR => continue,
            .CANCELED => return error.Canceled,

            .BADF => |err| return errnoBug(err), // 文件描述符在关闭后被使用。
            .NOTSOCK => |err| return errnoBug(err),
            .INVAL => |err| return errnoBug(err),
            .FAULT => |err| return errnoBug(err),
            else => |err| return posix.unexpectedErrno(err),
        }
    }
}

fn checkCancel(k: *Kqueue) error{Canceled}!void {
    if (cancelRequested(k)) return error.Canceled;
}

pub const KEventError = error{
    /// 进程无权注册过滤器。
    AccessDenied,
    /// 找不到要修改或删除的事件。
    EventNotFound,
    /// 没有可用于注册事件的内存。
    SystemResources,
    /// 指定要附加的进程不存在。
    ProcessNotFound,
    /// changelist 或 eventlist 中的项目过多。
    /// TODO 移除此可能性
    Overflow,
};

pub fn kevent(
    kq: i32,
    changelist: []const posix.Kevent,
    eventlist: []posix.Kevent,
    timeout: ?*const posix.timespec,
) KEventError!usize {
    while (true) {
        const rc = posix.system.kevent(
            kq,
            changelist.ptr,
            std.math.cast(c_int, changelist.len) orelse return error.Overflow,
            eventlist.ptr,
            std.math.cast(c_int, eventlist.len) orelse return error.Overflow,
            timeout,
        );
        switch (posix.errno(rc)) {
            .SUCCESS => return @intCast(rc),
            .ACCES => return error.AccessDenied,
            .FAULT => unreachable, // TODO 对这些情况使用 error.Unexpected
            .BADF => unreachable, // 始终存在竞态条件。
            .INTR => continue, // TODO 处理取消
            .INVAL => unreachable,
            .NOENT => return error.EventNotFound,
            .NOMEM => return error.SystemResources,
            .SRCH => return error.ProcessNotFound,
            else => unreachable,
        }
    }
}