跳转到内容
标准库Zig 0.17.1官方原文
源码std/Progress.zig

第 1 行

此 API 不分配内存、不会失败、线程安全且无锁。

字段

terminal: Io.File

目前此 API 仅支持将此值设为 stderr, 这在 start 内自动完成。

io: Io
terminal_mode: TerminalMode
update_worker: ?Io.Future(WorkerError!void)
redraw_event: Io.Event

由 SIGWINCH 和根 done() 函数以原子方式设置。

need_clear: bool
status: Status
refresh_rate_ns: u64
initial_delay_ns: u64
rows: u16
cols: u16
draw_buffer: []u8

仅由更新线程访问。

node_parents: [node_storage_buffer_len]Node.Parent

此项与 node_storage 分别存放在不同数组中,但长度相同, 以便高效遍历, 避免过多扰乱 CPU 缓存。

node_storage: [node_storage_buffer_len]Node.Storage
node_freelist_next: [node_storage_buffer_len]Node.OptionalIndex
node_freelist: Freelist
node_end_index: u32

节点数组中截至目前已使用过的元素数量。 此索引之前的节点要么处于活动状态,要么位于空闲链表上;剩余节点隐式为空闲。 此值有时可能暂时超过节点总数。

ipc_next: Ipc.SlotAtomic
ipc: [ipc_storage_buffer_len]Ipc
ipc_files: [ipc_storage_buffer_len]Io.File
start_failure: StartFailure

std.Progress.@"progress_error {d}"

常量

第 829 行

std.Progress.@"progress_normal {d}"

常量

第 828 行

std.Progress.appendTreeSymbol

函数

第 890 行

fn appendTreeSymbol(symbol: TreeSymbol, buf: []u8, start_i: usize) usize

参数

symbol: TreeSymbol
buf: []u8
start_i: usize

std.Progress.assert

别名

第 12 行

别名目标 std.debug.assert

std.Progress.builtin

常量

第 4 行

std.Progress.Children

容器

第 1001 行

字段

std.Progress.clear

常量

第 822 行

std.Progress.clearWrittenWindowsApi

函数

第 922 行

fn clearWrittenWindowsApi(io: Io) WindowsApiError!void

参数

io: Io

错误

Canceled Cancelable

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

Unexpected UnexpectedError

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

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

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

std.Progress.clearWrittenWithEscapeCodes

函数

第 913 行

pub fn clearWrittenWithEscapeCodes(file_writer: *Io.File.Writer) Io.Writer.Error!void

参数

file_writer: *Io.File.Writer

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.Progress.computeNode

类型函数

第 1441 行

fn computeNode( buf: []u8, start_i: usize, start_nl_n: usize, serialized: Serialized, children: []const Children, node_index: Node.Index, ) struct { usize, usize }

参数

buf: []u8
start_i: usize
start_nl_n: usize
serialized: Serialized
children: []const Children
node_index: Node.Index

std.Progress.computePrefix

函数

第 1401 行

fn computePrefix( buf: []u8, start_i: usize, nl_n: usize, serialized: Serialized, children: []const Children, node_index: Node.Index, ) usize

参数

buf: []u8
start_i: usize
nl_n: usize
serialized: Serialized
children: []const Children
node_index: Node.Index

std.Progress.computeRedraw

类型函数

第 1290 行

fn computeRedraw(io: Io, serialized_buffer: *Serialized.Buffer) !struct { []u8, usize }

参数

io: Io
serialized_buffer: *Serialized.Buffer

std.Progress.copyAtomicLoad

函数

第 1629 行

fn copyAtomicLoad( dest: *align(@alignOf(usize)) [Node.max_name_len]u8, src: *align(@alignOf(usize)) const [Node.max_name_len]u8, ) void

参数

dest: *align(@alignOf(usize)) [Node.max_name_len]u8
src: *align(@alignOf(usize)) const [Node.max_name_len]u8

std.Progress.copyAtomicStore

函数

第 1615 行

fn copyAtomicStore(dest: []align(@alignOf(usize)) u8, src: []const u8) void

参数

dest: []align(@alignOf(usize)) u8
src: []const u8

std.Progress.debug_start_trace

变量

第 554 行

std.Progress.default_draw_buffer

变量

第 552 行

[4096]u8

std.Progress.finish_sync

常量

第 825 行

std.Progress.Freelist

容器

第 74 行

字段

head: Node.OptionalIndex
generation: u24

每当向 node_freelist 添加节点时,递增此代数, 避免获取节点时发生 ABA 问题。使用回绕算术。

std.Progress.global_progress

变量

第 507 行

Progress

std.Progress.handleSigWinch

函数

第 1586 行

fn handleSigWinch(sig: posix.SIG, info: *const posix.siginfo_t, ctx_ptr: ?*anyopaque) callconv(.c) void

参数

sig: posix.SIG
info: *const posix.siginfo_t
ctx_ptr: ?*anyopaque

std.Progress.have_ipc

常量

第 556 行

std.Progress.have_sigwinch

常量

第 1593 行

std.Progress.Io

别名

第 9 行

别名目标 std.Io

std.Progress.Ipc

容器

第 81 行

字段

locked: bool

保护 file 使用的互斥锁,仅由 serializeIpc 锁定

valid: bool

未锁定时:表示 file 是否已定义。 锁定时:表示 file 是否无需关闭。

unused: @Int(.unsigned, 32 - 2 - @bitSizeOf(Generation)) = 0
generation: Generation

std.Progress.ipc_storage_buffer_len

常量

第 545 行

取二的幂,以避免浪费 ipc_next 的递增。

std.Progress.Ipc.Data

容器

第 100 行

字段

state: State
bytes_read: u16
main_index: u8
start_index: u8
nodes_len: u8

std.Progress.Ipc.Data.findLastPacket

类型函数

第 118 行

fn findLastPacket(data: *const Data, buffer: *const [max_packet_len]u8) struct { u16, u16 }

参数

data: *const Data
buffer: *const [max_packet_len]u8

std.Progress.Ipc.Data.rebase

函数

第 133 行

fn rebase( data: *Data, buffer: *[max_packet_len]u8, vec: *[1][]u8, batch: *std.Io.Batch, slot: Slot, packet_end: u16, ) void

参数

data: *Data
buffer: *[max_packet_len]u8
vec: *[1][]u8
batch: *std.Io.Batch
slot: Slot
packet_end: u16

std.Progress.Ipc.Data.State

容器

第 107 行

字段

unused
pending
ready

std.Progress.Ipc.Data.unused

常量

第 110 行

尚未对此文件启动任何操作。

Data

std.Progress.Ipc.Generation

常量

第 91 行

std.Progress.Ipc.Index

容器

第 95 行

字段

slot: Slot
generation: Generation

std.Progress.Ipc.Slot

类型

第 90 行

std.Progress.Ipc.SlotAtomic

常量

第 93 行

std.Progress.ipcThreadRun

函数

第 802 行

fn ipcThreadRun(io: Io, file: Io.File) WorkerError!void

参数

io: Io
file: Io.File

错误

AccessDenied Error

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

BrokenPipe Error

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

Canceled Cancelable

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

ConcurrencyUnavailable ConcurrentError

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

ConnectionResetByPeer UnendingError
DeviceBusy Error
DiskQuota Error
EndOfStream Error
FileBusy Error
FileTooBig Error
InputOutput Error
IsDir UnendingError

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

LockViolation Error

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

NoDevice Error

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

NoSpaceLeft Error
NotOpenForReading UnendingError

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

NotOpenForWriting Error
PermissionDenied Error
SocketUnconnected UnendingError
SystemResources Error

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

Unexpected UnexpectedError

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

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

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

WindowTooSmall
WouldBlock Error

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

std.Progress.is_big_endian

常量

第 5 行

std.Progress.is_windows

常量

第 6 行

std.Progress.lineUpperBoundLen

函数

第 1432 行

fn lineUpperBoundLen(nl_n: usize) usize

参数

nl_n: usize

std.Progress.max_packet_len

常量

第 547 行

std.Progress.maybeUpdateSize

函数

第 1543 行

fn maybeUpdateSize(io: Io, resize_flag: bool) !void

参数

io: Io
resize_flag: bool

std.Progress.Node

容器

第 170 行

表示一个进度单位。每个节点可以拥有子节点, 也可以通过 update 使用整数表示进度。

字段

index: OptionalIndex

std.Progress.node_storage_buffer_len

常量

第 542 行

取比二的幂小一的值,确保 max_packet_len 已是二的幂。

std.Progress.Node.completeOne

函数

第 316 行

等价于调用 start,再对返回的 Node 调用 end。线程安全。

pub fn completeOne(n: Node) void

参数

n: Node

std.Progress.Node.end

函数

第 370 行

结束已启动的 Node。线程安全。

pub fn end(n: Node) void

参数

n: Node

std.Progress.Node.freelistNextByIndex

函数

第 480 行

fn freelistNextByIndex(index: Node.Index) *Node.OptionalIndex

参数

index: Node.Index

std.Progress.Node.getName

函数

第 336 行

获取此 Node 的名称。 之后可以将指向此数组的指针传给 setName,以恢复名称。

pub fn getName(n: Node) [max_name_len]u8

参数

n: Node

std.Progress.Node.increaseEstimatedTotalItems

函数

第 361 行

线程安全。

pub fn increaseEstimatedTotalItems(n: Node, count: usize) void

参数

n: Node
count: usize

std.Progress.Node.Index

容器

第 251 行

node_storage 的索引。

字段

_

std.Progress.Node.Index.toOptional

函数

第 260 行

pub fn toOptional(i: @This()) OptionalIndex

参数

i: @This()

std.Progress.Node.Index.toParent

函数

第 254 行

fn toParent(i: @This()) Parent

参数

i: @This()

std.Progress.Node.init

函数

第 484 行

fn init(free_index: Index, parent: Parent, name: []const u8, estimated_total_items: usize) Node

参数

free_index: Index
parent: Parent
name: []const u8
estimated_total_items: usize

std.Progress.Node.max_name_len

常量

第 175 行

std.Progress.Node.none

常量

第 173 行

Node

std.Progress.Node.OptionalIndex

容器

第 234 行

字段

none = std.math.maxInt(u8)
_

node_storage 的索引。

std.Progress.Node.OptionalIndex.toParent

函数

第 244 行

fn toParent(i: @This()) Parent

参数

i: @This()

std.Progress.Node.OptionalIndex.unwrap

函数

第 239 行

pub fn unwrap(i: @This()) ?Index

参数

i: @This()

std.Progress.Node.Parent

容器

第 218 行

字段

unused = std.math.maxInt(u8) - 1

未分配的存储空间。

none = std.math.maxInt(u8)

表示根节点。

_

node_storage 的索引。

std.Progress.Node.Parent.unwrap

函数

第 226 行

fn unwrap(i: @This()) ?Index

参数

i: @This()

std.Progress.Node.parentByIndex

函数

第 476 行

fn parentByIndex(index: Node.Index) *Node.Parent

参数

index: Node.Index

std.Progress.Node.setCompletedItems

函数

第 345 行

线程安全。

pub fn setCompletedItems(n: Node, completed_items: usize) void

参数

n: Node
completed_items: usize

std.Progress.Node.setEstimatedTotalItems

函数

第 352 行

线程安全。0 表示未知。

pub fn setEstimatedTotalItems(n: Node, count: usize) void

参数

n: Node
count: usize

std.Progress.Node.setIpcFile

函数

第 421 行

由 std.process.Child 使用。线程安全。

pub fn setIpcFile(node: Node, expected_io_userdata: ?*anyopaque, file: Io.File) void

参数

node: Node
expected_io_userdata: ?*anyopaque
file: Io.File

std.Progress.Node.setIpcIndex

函数

第 456 行

pub fn setIpcIndex(node: Node, ipc_index: Ipc.Index) void

参数

node: Node
ipc_index: Ipc.Index

std.Progress.Node.setName

函数

第 323 行

线程安全。忽略 new_name 中 '0' 之后的字节。

pub fn setName(n: Node, new_name: []const u8) void

参数

n: Node
new_name: []const u8

std.Progress.Node.start

函数

第 268 行

创建新的子进度节点。线程安全。

estimated_total_items 传入 0 表示未知。

pub fn start(node: Node, name: []const u8, estimated_total_items: usize) Node

参数

node: Node
name: []const u8
estimated_total_items: usize

std.Progress.Node.startFmt

函数

第 309 行

pub fn startFmt(node: Node, estimated_total_items: usize, comptime format: []const u8, args: anytype) Node

参数

node: Node
estimated_total_items: usize
format: []const u8

std.Progress.Node.Storage

容器

第 177 行

字段

completed_count: u32

小端序。

estimated_total_count: u32

0 表示未知。 小端序。

name: [max_name_len]u8 align(@alignOf(usize))

std.Progress.Node.Storage.byteSwap

函数

第 200 行

非线程安全。

fn byteSwap(s: *Storage) void

参数

s: *Storage

std.Progress.Node.Storage.copyRoot

函数

第 205 行

fn copyRoot(dest: *Node.Storage, src: *align(1) const Node.Storage) void

参数

dest: *Node.Storage
src: *align(1) const Node.Storage

std.Progress.Node.Storage.getIpcIndex

函数

第 186 行

非线程安全。

fn getIpcIndex(s: Storage) ?Ipc.Index

参数

s: Storage

std.Progress.Node.Storage.setIpcIndex

函数

第 191 行

线程安全。

fn setIpcIndex(s: *Storage, ipc_index: Ipc.Index) void

参数

s: *Storage
ipc_index: Ipc.Index

std.Progress.Node.storageByIndex

函数

第 472 行

fn storageByIndex(index: Node.Index) *Node.Storage

参数

index: Node.Index

std.Progress.Node.takeIpcIndex

函数

第 461 行

非线程安全。

pub fn takeIpcIndex(node: Node) ?Ipc.Index

参数

node: Node

std.Progress.noop_impl

常量

第 561 行

std.Progress.Options

容器

第 574 行

字段

draw_buffer: []u8 = &default_draw_buffer

用户提供的具有静态生存期的缓冲区。

用于存储发送到终端的整个写入缓冲区。若进度输出无法放入此缓冲区, 则会截断输出;这会影响显示,但不会导致功能故障。

必须至少为 200 字节。

refresh_rate_ns: Io.Duration = .fromMilliseconds(80)

向终端写入更新之间间隔的纳秒数。

initial_delay_ns: Io.Duration = .fromMilliseconds(200)

保持输出隐藏的纳秒数。

estimated_total_items: usize = 0

若提供,则进度项包含分母。 0 表示未知。

root_name: []const u8 = ""
disable_printing: bool = false

std.Progress.ParentFileError

错误集合

第 568 行

错误

EnvironmentVariableMissing
UnrecognizedFormat
UnsupportedOperation

std.Progress.posix

别名

第 13 行

别名目标 std.posix

std.Progress.Progress

别名

第 2 行

别名目标 std.Progress

std.Progress.progress_error_100

常量

第 833 行

std.Progress.progress_normal_100

常量

第 832 行

std.Progress.progress_pulsing

常量

第 830 行

std.Progress.progress_pulsing_error

常量

第 831 行

std.Progress.progress_remove

常量

第 827 行

std.Progress.restore

常量

第 824 行

std.Progress.save

常量

第 823 行

std.Progress.serialize

函数

第 1031 行

fn serialize(io: Io, serialized_buffer: *Serialized.Buffer) !Serialized

参数

io: Io
serialized_buffer: *Serialized.Buffer

std.Progress.Serialized

容器

第 1006 行

字段

parents: []Node.Parent
storage: []Node.Storage

std.Progress.Serialized.Buffer

容器

第 1010 行

字段

parents: [node_storage_buffer_len]Node.Parent
storage: [node_storage_buffer_len]Node.Storage
ipc_start: u8
ipc_end: u8
ipc_data: [ipc_storage_buffer_len]Ipc.Data
ipc_buffers: [ipc_storage_buffer_len][max_packet_len]u8
ipc_vecs: [ipc_storage_buffer_len][1][]u8
batch_storage: [ipc_storage_buffer_len]Io.Operation.Storage
batch: Io.Batch

std.Progress.Serialized.Buffer.init

函数

第 1022 行

fn init(buffer: *Buffer) void

参数

buffer: *Buffer

std.Progress.setStatus

函数

第 684 行

pub fn setStatus(new_status: Status) void

参数

new_status: Status

std.Progress.start

函数

第 600 行

初始化全局 Progress 实例。

断言仅存在一个全局 Progress 实例。

完成后调用 Node.end。

若发生错误,则填充 start_failure。

pub fn start(io: Io, options: Options) Node

参数

io: Io
options: Options

std.Progress.start_sync

常量

第 820 行

std.Progress.StartFailure

容器

第 534 行

字段

unstarted
spawn_ipc_worker: error{ConcurrencyUnavailable}
spawn_update_worker: error{ConcurrencyUnavailable}
parent_ipc: error{ UnsupportedOperation, UnrecognizedFormat }

std.Progress.Status

容器

第 58 行

字段

working

表示应用程序正在推进任务直至完成。 除非应用程序具有交互性,否则程序 始终只有这一种状态!

success

应用程序已完成操作,现在正在等待用户 输入,而不是调用 exit(0)。

failure

应用程序遇到错误,目前正在等待用户输入, 而不是调用 exit(1)。

failure_working

应用程序遇到至少一个错误,但仍在处理 更多任务。

std.Progress.std

别名

第 8 行

别名目标 std

std.Progress.TerminalMode

容器

第 155 行

字段

off
ansi_escape_codes
windows_api: if (is_windows) WindowsApi else noreturn

这与运行在 Windows 上并不相同, 因为还存在 MSYS/git-bash 等其他终端。

std.Progress.TerminalMode.WindowsApi

容器

第 162 行

字段

code_page: windows.UINT

控制台的输出代码页。

std.Progress.testing

别名

第 11 行

别名目标 std.testing

std.Progress.TreeSymbol

容器

第 835 行

字段

tee

├─

line

│

langle

└─

std.Progress.TreeSymbol.bytes

函数

第 859 行

fn bytes(symbol: TreeSymbol, encoding: Encoding) []const u8

参数

symbol: TreeSymbol
encoding: Encoding

std.Progress.TreeSymbol.Encoding

容器

第 843 行

字段

ansi_escapes
code_page_437
utf8
ascii

std.Progress.TreeSymbol.escapeSeq

函数

第 851 行

转义序列的字符串字面量表示

fn escapeSeq(symbol: TreeSymbol) *const [9:0]u8

参数

symbol: TreeSymbol

std.Progress.TreeSymbol.maxByteLen

函数

第 880 行

fn maxByteLen(symbol: TreeSymbol) usize

参数

symbol: TreeSymbol

std.Progress.up_one_line

常量

第 821 行

std.Progress.updateTask

函数

第 706 行

fn updateTask(io: Io) WorkerError!void

参数

io: Io

错误

AccessDenied Error

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

BrokenPipe Error

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

Canceled Cancelable

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

ConcurrencyUnavailable ConcurrentError

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

ConnectionResetByPeer UnendingError
DeviceBusy Error
DiskQuota Error
EndOfStream Error
FileBusy Error
FileTooBig Error
InputOutput Error
IsDir UnendingError

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

LockViolation Error

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

NoDevice Error

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

NoSpaceLeft Error
NotOpenForReading UnendingError

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

NotOpenForWriting Error
PermissionDenied Error
SocketUnconnected UnendingError
SystemResources Error

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

Unexpected UnexpectedError

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

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

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

WindowTooSmall
WouldBlock Error

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

std.Progress.wait

函数

第 690 行

返回是否需要调整大小以获知终端尺寸。

fn wait(io: Io, timeout_ns: u64) Io.Cancelable!bool

参数

io: Io
timeout_ns: u64

错误

Canceled

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

std.Progress.windows

别名

第 10 行

别名目标 std.os.windows

std.Progress.windows_api_start_marker

常量

第 920 行

U+25BA 或 ►

std.Progress.WindowsApiError

错误集合

第 742 行

错误

Canceled Cancelable

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

Unexpected UnexpectedError

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

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

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

std.Progress.windowsApiMoveToMarker

函数

第 962 行

fn windowsApiMoveToMarker(io: Io, nl_n: usize) WindowsApiError!void

参数

io: Io
nl_n: usize

错误

Canceled Cancelable

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

Unexpected UnexpectedError

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

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

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

std.Progress.windowsApiUpdateTask

函数

第 763 行

fn windowsApiUpdateTask(io: Io) WorkerError!void

参数

io: Io

错误

AccessDenied Error

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

BrokenPipe Error

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

Canceled Cancelable

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

ConcurrencyUnavailable ConcurrentError

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

ConnectionResetByPeer UnendingError
DeviceBusy Error
DiskQuota Error
EndOfStream Error
FileBusy Error
FileTooBig Error
InputOutput Error
IsDir UnendingError

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

LockViolation Error

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

NoDevice Error

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

NoSpaceLeft Error
NotOpenForReading UnendingError

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

NotOpenForWriting Error
PermissionDenied Error
SocketUnconnected UnendingError
SystemResources Error

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

Unexpected UnexpectedError

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

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

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

WindowTooSmall
WouldBlock Error

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

std.Progress.windowsApiWriteMarker

函数

第 744 行

fn windowsApiWriteMarker(io: Io) WindowsApiError!void

参数

io: Io

错误

Canceled Cancelable

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

Unexpected UnexpectedError

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

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

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

std.Progress.withinRowLimit

函数

第 1521 行

fn withinRowLimit(p: *Progress, nl_n: usize) bool

参数

p: *Progress
nl_n: usize

std.Progress.WorkerError

错误集合

第 703 行

错误

AccessDenied Error

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

BrokenPipe Error

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

Canceled Cancelable

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

ConcurrencyUnavailable ConcurrentError

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

ConnectionResetByPeer UnendingError
DeviceBusy Error
DiskQuota Error
EndOfStream Error
FileBusy Error
FileTooBig Error
InputOutput Error
IsDir UnendingError

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

LockViolation Error

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

NoDevice Error

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

NoSpaceLeft Error
NotOpenForReading UnendingError

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

NotOpenForWriting Error
PermissionDenied Error
SocketUnconnected UnendingError
SystemResources Error

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

Unexpected UnexpectedError

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

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

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

WindowTooSmall
WouldBlock Error

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

std.Progress.writeIpc

函数

第 1528 行

fn writeIpc(writer: *Io.Writer, serialized: Serialized) Io.Writer.Error!void

参数

writer: *Io.Writer
serialized: Serialized

错误

WriteFailed

详细诊断信息见 Writer 实现。

std.Progress.Writer

别名

第 14 行

别名目标 std.Io.Writer

源码

std/Progress.zig

//! 此 API 不分配内存、不会失败、线程安全且无锁。
const Progress = @This();

const builtin = @import("builtin");
const is_big_endian = builtin.cpu.arch.endian() == .big;
const is_windows = builtin.os.tag == .windows;

const std = @import("std");
const Io = std.Io;
const windows = std.os.windows;
const testing = std.testing;
const assert = std.debug.assert;
const posix = std.posix;
const Writer = Io.Writer;

/// 目前此 API 仅支持将此值设为 stderr,
/// 这在 `start` 内自动完成。
terminal: Io.File,

io: Io,

terminal_mode: TerminalMode,

update_worker: ?Io.Future(WorkerError!void),

/// 由 SIGWINCH 和根 done() 函数以原子方式设置。
redraw_event: Io.Event,
need_clear: bool,
status: Status,

refresh_rate_ns: u64,
initial_delay_ns: u64,

rows: u16,
cols: u16,

/// 仅由更新线程访问。
draw_buffer: []u8,

/// 此项与 `node_storage` 分别存放在不同数组中,但长度相同,
/// 以便高效遍历,
/// 避免过多扰乱 CPU 缓存。
node_parents: [node_storage_buffer_len]Node.Parent,
node_storage: [node_storage_buffer_len]Node.Storage,
node_freelist_next: [node_storage_buffer_len]Node.OptionalIndex,
node_freelist: Freelist,
/// 节点数组中截至目前已使用过的元素数量。
/// 此索引之前的节点要么处于活动状态,要么位于空闲链表上;剩余节点隐式为空闲。
/// 此值有时可能暂时超过节点总数。
node_end_index: u32,

ipc_next: Ipc.SlotAtomic,
ipc: [ipc_storage_buffer_len]Ipc,
ipc_files: [ipc_storage_buffer_len]Io.File,

start_failure: StartFailure,

pub const Status = enum {
    /// 表示应用程序正在推进任务直至完成。
    /// 除非应用程序具有交互性,否则程序
    /// 始终只有这一种状态!
    working,
    /// 应用程序已完成操作,现在正在等待用户
    /// 输入,而不是调用 exit(0)。
    success,
    /// 应用程序遇到错误,目前正在等待用户输入,
    /// 而不是调用 exit(1)。
    failure,
    /// 应用程序遇到至少一个错误,但仍在处理
    /// 更多任务。
    failure_working,
};

const Freelist = packed struct(u32) {
    head: Node.OptionalIndex,
    /// 每当向 `node_freelist` 添加节点时,递增此代数,
    /// 避免获取节点时发生 ABA 问题。使用回绕算术。
    generation: u24,
};

pub const Ipc = packed struct(u32) {
    /// 保护 `file` 使用的互斥锁,仅由 `serializeIpc` 锁定
    locked: bool,
    /// 未锁定时:表示 `file` 是否已定义。
    /// 锁定时:表示 `file` 是否无需关闭。
    valid: bool,
    unused: @Int(.unsigned, 32 - 2 - @bitSizeOf(Generation)) = 0,
    generation: Generation,

    pub const Slot = std.math.IntFittingRange(0, ipc_storage_buffer_len - 1);
    pub const Generation = @Int(.unsigned, 32 - @bitSizeOf(Slot));

    const SlotAtomic = @Int(.unsigned, std.math.ceilPowerOfTwoAssert(usize, @min(@bitSizeOf(Slot), 8)));

    pub const Index = packed struct(u32) {
        slot: Slot,
        generation: Generation,
    };

    const Data = struct {
        state: State,
        bytes_read: u16,
        main_index: u8,
        start_index: u8,
        nodes_len: u8,

        const State = enum { unused, pending, ready };

        /// 尚未对此文件启动任何操作。
        const unused: Data = .{
            .state = .unused,
            .bytes_read = 0,
            .main_index = 0,
            .start_index = 0,
            .nodes_len = 0,
        };

        fn findLastPacket(data: *const Data, buffer: *const [max_packet_len]u8) struct { u16, u16 } {
            assert(data.state == .ready);
            var packet_start: u16 = 0;
            var packet_end: u16 = 0;
            const bytes_read = data.bytes_read;
            while (bytes_read - packet_end >= 1) {
                const nodes_len: u16 = buffer[packet_end];
                const packet_len = 1 + nodes_len * (@sizeOf(Node.Storage) + @sizeOf(Node.Parent));
                if (packet_end + packet_len > bytes_read) break;
                packet_start = packet_end;
                packet_end += packet_len;
            }
            return .{ packet_start, packet_end };
        }

        fn rebase(
            data: *Data,
            buffer: *[max_packet_len]u8,
            vec: *[1][]u8,
            batch: *std.Io.Batch,
            slot: Slot,
            packet_end: u16,
        ) void {
            assert(data.state == .ready);
            const remaining = buffer[packet_end..data.bytes_read];
            @memmove(buffer[0..remaining.len], remaining);
            vec.* = .{buffer[remaining.len..]};
            batch.addAt(slot, .{ .file_read_streaming = .{
                .file = global_progress.ipc_files[slot],
                .data = vec,
            } });
            data.state = .pending;
            data.bytes_read = @intCast(remaining.len);
        }
    };
};

pub const TerminalMode = union(enum) {
    off,
    ansi_escape_codes,
    /// 这与运行在 Windows 上并不相同,
    /// 因为还存在 MSYS/git-bash 等其他终端。
    windows_api: if (is_windows) WindowsApi else noreturn,

    pub const WindowsApi = struct {
        /// 控制台的输出代码页。
        code_page: windows.UINT,
    };
};

/// 表示一个进度单位。每个节点可以拥有子节点,
/// 也可以通过 `update` 使用整数表示进度。
pub const Node = struct {
    index: OptionalIndex,

    pub const none: Node = .{ .index = .none };

    pub const max_name_len = 120;

    const Storage = extern struct {
        /// 小端序。
        completed_count: u32,
        /// 0 表示未知。
        /// 小端序。
        estimated_total_count: u32,
        name: [max_name_len]u8 align(@alignOf(usize)),

        /// 非线程安全。
        fn getIpcIndex(s: Storage) ?Ipc.Index {
            return if (s.estimated_total_count == std.math.maxInt(u32)) @bitCast(s.completed_count) else null;
        }

        /// 线程安全。
        fn setIpcIndex(s: *Storage, ipc_index: Ipc.Index) void {
            // `estimated_total_count` 的最大整数值表示特殊状态,使 `completed_count` 被视为文件描述符,因此这里的顺序很重要。
            //
            //
            @atomicStore(u32, &s.completed_count, @bitCast(ipc_index), .monotonic);
            @atomicStore(u32, &s.estimated_total_count, std.math.maxInt(u32), .release); // 与 `serialize` 中的获取操作同步
        }

        /// 非线程安全。
        fn byteSwap(s: *Storage) void {
            s.completed_count = @byteSwap(s.completed_count);
            s.estimated_total_count = @byteSwap(s.estimated_total_count);
        }

        fn copyRoot(dest: *Node.Storage, src: *align(1) const Node.Storage) void {
            dest.* = .{
                .completed_count = src.completed_count,
                .estimated_total_count = src.estimated_total_count,
                .name = if (src.name[0] == 0) dest.name else src.name,
            };
        }

        comptime {
            assert((@sizeOf(Storage) % 4) == 0);
        }
    };

    const Parent = enum(u8) {
        /// 未分配的存储空间。
        unused = std.math.maxInt(u8) - 1,
        /// 表示根节点。
        none = std.math.maxInt(u8),
        /// `node_storage` 的索引。
        _,

        fn unwrap(i: @This()) ?Index {
            return switch (i) {
                .unused, .none => return null,
                else => @fromBackingInt(@intCast(@backingInt(i))),
            };
        }
    };

    pub const OptionalIndex = enum(u8) {
        none = std.math.maxInt(u8),
        /// `node_storage` 的索引。
        _,

        pub fn unwrap(i: @This()) ?Index {
            if (i == .none) return null;
            return @fromBackingInt(@intCast(@backingInt(i)));
        }

        fn toParent(i: @This()) Parent {
            assert(@backingInt(i) != @backingInt(Parent.unused));
            return @fromBackingInt(@intCast(@backingInt(i)));
        }
    };

    /// `node_storage` 的索引。
    pub const Index = enum(u8) {
        _,

        fn toParent(i: @This()) Parent {
            assert(@backingInt(i) != @backingInt(Parent.unused));
            assert(@backingInt(i) != @backingInt(Parent.none));
            return @fromBackingInt(@intCast(@backingInt(i)));
        }

        pub fn toOptional(i: @This()) OptionalIndex {
            return @fromBackingInt(@intCast(@backingInt(i)));
        }
    };

    /// 创建新的子进度节点。线程安全。
    ///
    /// `estimated_total_items` 传入 0 表示未知。
    pub fn start(node: Node, name: []const u8, estimated_total_items: usize) Node {
        if (noop_impl) {
            assert(node.index == .none);
            return Node.none;
        }
        const node_index = node.index.unwrap() orelse return Node.none;
        const parent = node_index.toParent();

        const freelist = &global_progress.node_freelist;
        var old_freelist = @atomicLoad(Freelist, freelist, .acquire); // 使用 acquire,以确保获得正确的 "next" 条目
        while (old_freelist.head.unwrap()) |free_index| {
            const next_ptr = freelistNextByIndex(free_index);
            const new_freelist: Freelist = .{
                .head = @atomicLoad(Node.OptionalIndex, next_ptr, .monotonic),
                // 从空闲链表移除节点时无需增加代数,仅在添加节点时增加。
                // (此选择是任意的;反过来也可以。)
                .generation = old_freelist.generation,
            };
            old_freelist = @cmpxchgWeak(
                Freelist,
                freelist,
                old_freelist,
                new_freelist,
                .acquire, // 理论上并无必要,但不能弱于失败内存序
                .acquire, // 确保下一次迭代具有正确的 `node_freelist_next` 条目
            ) orelse {
                // 在分配竞态中获胜。
                return init(free_index, parent, name, estimated_total_items);
            };
        }

        const free_index = @atomicRmw(u32, &global_progress.node_end_index, .Add, 1, .monotonic);
        if (free_index >= node_storage_buffer_len) {
            // 节点存储内存已耗尽。不会跟踪此节点的进度。
            _ = @atomicRmw(u32, &global_progress.node_end_index, .Sub, 1, .monotonic);
            return Node.none;
        }

        return init(@fromBackingInt(@intCast(free_index)), parent, name, estimated_total_items);
    }

    pub fn startFmt(node: Node, estimated_total_items: usize, comptime format: []const u8, args: anytype) Node {
        var buffer: [max_name_len]u8 = undefined;
        const name = std.mem.print(&buffer, format, args) catch &buffer;
        return Node.start(node, name, estimated_total_items);
    }

    /// 等价于调用 `start`,再对返回的 `Node` 调用 `end`。线程安全。
    pub fn completeOne(n: Node) void {
        const index = n.index.unwrap() orelse return;
        const storage = storageByIndex(index);
        _ = @atomicRmw(u32, &storage.completed_count, .Add, 1, .monotonic);
    }

    /// 线程安全。忽略 `new_name` 中 '0' 之后的字节。
    pub fn setName(n: Node, new_name: []const u8) void {
        const index = n.index.unwrap() orelse return;
        const storage = storageByIndex(index);

        const name_len = @min(max_name_len, std.mem.findScalar(u8, new_name, 0) orelse new_name.len);

        copyAtomicStore(storage.name[0..name_len], new_name[0..name_len]);
        if (name_len < storage.name.len)
            @atomicStore(u8, &storage.name[name_len], 0, .monotonic);
    }

    /// 获取此 `Node` 的名称。
    /// 之后可以将指向此数组的指针传给 `setName`,以恢复名称。
    pub fn getName(n: Node) [max_name_len]u8 {
        var dest: [max_name_len]u8 align(@alignOf(usize)) = undefined;
        if (n.index.unwrap()) |index| {
            copyAtomicLoad(&dest, &storageByIndex(index).name);
        }
        return dest;
    }

    /// 线程安全。
    pub fn setCompletedItems(n: Node, completed_items: usize) void {
        const index = n.index.unwrap() orelse return;
        const storage = storageByIndex(index);
        @atomicStore(u32, &storage.completed_count, std.math.lossyCast(u32, completed_items), .monotonic);
    }

    /// 线程安全。0 表示未知。
    pub fn setEstimatedTotalItems(n: Node, count: usize) void {
        const index = n.index.unwrap() orelse return;
        const storage = storageByIndex(index);
        // 避开 u32 最大整数值,因为它用于表示特殊状态。
        const saturated_total_count = @min(std.math.maxInt(u32) - 1, count);
        @atomicStore(u32, &storage.estimated_total_count, saturated_total_count, .monotonic);
    }

    /// 线程安全。
    pub fn increaseEstimatedTotalItems(n: Node, count: usize) void {
        const index = n.index.unwrap() orelse return;
        const storage = storageByIndex(index);
        // 避开 u32 最大整数值,因为它用于表示特殊状态。
        const saturated_total_count = @min(std.math.maxInt(u32) - 1, count);
        _ = @atomicRmw(u32, &storage.estimated_total_count, .Add, saturated_total_count, .monotonic);
    }

    /// 结束已启动的 `Node`。线程安全。
    pub fn end(n: Node) void {
        if (noop_impl) {
            assert(n.index == .none);
            return;
        }
        const index = n.index.unwrap() orelse return;
        const io = global_progress.io;
        const parent_ptr = parentByIndex(index);
        if (@atomicLoad(Node.Parent, parent_ptr, .monotonic).unwrap()) |parent_index| {
            _ = @atomicRmw(u32, &storageByIndex(parent_index).completed_count, .Add, 1, .monotonic);
            @atomicStore(Node.Parent, parent_ptr, .unused, .monotonic);

            if (storageByIndex(index).getIpcIndex()) |ipc_index| {
                const file = global_progress.ipc_files[ipc_index.slot];
                const ipc = @atomicRmw(
                    Ipc,
                    &global_progress.ipc[ipc_index.slot],
                    .And,
                    .{ .locked = true, .valid = false, .generation = std.math.maxInt(Ipc.Generation) },
                    .release,
                );
                assert(ipc.valid and ipc.generation == ipc_index.generation);
                if (!ipc.locked) file.close(io);
            }

            const freelist = &global_progress.node_freelist;
            var old_freelist = @atomicLoad(Freelist, freelist, .monotonic);
            while (true) {
                @atomicStore(Node.OptionalIndex, freelistNextByIndex(index), old_freelist.head, .monotonic);
                old_freelist = @cmpxchgWeak(
                    Freelist,
                    freelist,
                    old_freelist,
                    .{ .head = index.toOptional(), .generation = old_freelist.generation +% 1 },
                    .release, // 确保匹配的 `start` 能看到上面写入的空闲链表链接
                    .monotonic, // 若需重试,上方的写入操作无关紧要
                ) orelse {
                    // 本方赢得竞态。
                    return;
                };
            }
        } else {
            if (global_progress.update_worker) |*worker| worker.cancel(io) catch {};
            for (&global_progress.ipc, &global_progress.ipc_files) |ipc, ipc_file| {
                assert(!ipc.locked or !ipc.valid); // 缺少 end() 调用
                if (ipc.locked or ipc.valid) ipc_file.close(io);
            }
        }
    }

    /// 由 `std.process.Child` 使用。线程安全。
    pub fn setIpcFile(node: Node, expected_io_userdata: ?*anyopaque, file: Io.File) void {
        const index = node.index.unwrap() orelse return;
        const io = global_progress.io;
        assert(io.userdata == expected_io_userdata);
        for (0..ipc_storage_buffer_len) |_| {
            const slot: Ipc.Slot = @truncate(
                @atomicRmw(Ipc.SlotAtomic, &global_progress.ipc_next, .Add, 1, .monotonic),
            );
            if (slot >= ipc_storage_buffer_len) continue;
            const ipc_ptr = &global_progress.ipc[slot];
            const ipc = @atomicLoad(Ipc, ipc_ptr, .monotonic);
            if (ipc.locked or ipc.valid) continue;
            const generation = ipc.generation +% 1;
            if (@cmpxchgWeak(
                Ipc,
                ipc_ptr,
                ipc,
                .{ .locked = false, .valid = true, .generation = generation },
                .acquire,
                .monotonic,
            )) |_| continue;
            global_progress.ipc_files[slot] = file;
            storageByIndex(index).setIpcIndex(.{ .slot = slot, .generation = generation });
            break;
        } else {
            // 没有可用的 IPC 槽位,因此丢弃此节点的 IPC 信息,仅关闭
            // 文件描述符。为避免仍为此节点渲染旧的 `estimated_total_items` 或 `completed_count`
            // 值,会将对应字段清零;由于用户认为我们正在使用 IPC,
            // 不允许用户更改此字段。
            file.close(io);
            @atomicStore(u32, &storageByIndex(index).completed_count, 0, .monotonic);
            @atomicStore(u32, &storageByIndex(index).estimated_total_count, 0, .monotonic);
        }
    }

    pub fn setIpcIndex(node: Node, ipc_index: Ipc.Index) void {
        storageByIndex(node.index.unwrap() orelse return).setIpcIndex(ipc_index);
    }

    /// 非线程安全。
    pub fn takeIpcIndex(node: Node) ?Ipc.Index {
        const storage = storageByIndex(node.index.unwrap() orelse return null);
        switch (storage.estimated_total_count) {
            std.math.maxInt(u32) => {}, // 表示 `completed_count` 中存在 IPC 索引
            0 => return null, // `setIpcFile` 失败,因此此节点没有 IPC 索引
            else => unreachable, // 不是 IPC 节点
        }
        @atomicStore(u32, &storage.estimated_total_count, 0, .monotonic);
        return @bitCast(storage.completed_count);
    }

    fn storageByIndex(index: Node.Index) *Node.Storage {
        return &global_progress.node_storage[@backingInt(index)];
    }

    fn parentByIndex(index: Node.Index) *Node.Parent {
        return &global_progress.node_parents[@backingInt(index)];
    }

    fn freelistNextByIndex(index: Node.Index) *Node.OptionalIndex {
        return &global_progress.node_freelist_next[@backingInt(index)];
    }

    fn init(free_index: Index, parent: Parent, name: []const u8, estimated_total_items: usize) Node {
        assert(parent == .none or @backingInt(parent) < node_storage_buffer_len);

        const storage = storageByIndex(free_index);
        @atomicStore(u32, &storage.completed_count, 0, .monotonic);
        // 避开 u32 最大整数值,因为它用于表示特殊状态。
        const saturated_total_count = @min(std.math.maxInt(u32) - 1, estimated_total_items);
        @atomicStore(u32, &storage.estimated_total_count, saturated_total_count, .monotonic);
        const name_len = @min(max_name_len, name.len);
        copyAtomicStore(storage.name[0..name_len], name[0..name_len]);
        if (name_len < storage.name.len)
            @atomicStore(u8, &storage.name[name_len], 0, .monotonic);

        const parent_ptr = parentByIndex(free_index);
        if (std.debug.runtime_safety) {
            assert(@atomicLoad(Node.Parent, parent_ptr, .monotonic) == .unused);
        }
        @atomicStore(Node.Parent, parent_ptr, parent, .monotonic);

        return .{ .index = free_index.toOptional() };
    }
};

var global_progress: Progress = .{
    .io = undefined,
    .terminal = undefined,
    .terminal_mode = .off,
    .update_worker = null,
    .redraw_event = .unset,
    .refresh_rate_ns = undefined,
    .initial_delay_ns = undefined,
    .rows = 0,
    .cols = 0,
    .draw_buffer = undefined,
    .need_clear = false,
    .status = .working,

    .node_parents = undefined,
    .node_storage = undefined,
    .node_freelist_next = undefined,
    .node_freelist = .{ .head = .none, .generation = 0 },
    .node_end_index = 0,

    .ipc_next = 0,
    .ipc = undefined,
    .ipc_files = undefined,

    .start_failure = .unstarted,
};

pub const StartFailure = union(enum) {
    unstarted,
    spawn_ipc_worker: error{ConcurrencyUnavailable},
    spawn_update_worker: error{ConcurrencyUnavailable},
    parent_ipc: error{ UnsupportedOperation, UnrecognizedFormat },
};

/// 取比二的幂小一的值,确保 `max_packet_len` 已是二的幂。
const node_storage_buffer_len = ipc_storage_buffer_len - 1;

/// 取二的幂,以避免浪费 `ipc_next` 的递增。
const ipc_storage_buffer_len = 128;

pub const max_packet_len = std.math.ceilPowerOfTwoAssert(
    usize,
    1 + node_storage_buffer_len * (@sizeOf(Node.Storage) + @sizeOf(Node.OptionalIndex)),
);

var default_draw_buffer: [4096]u8 = undefined;

var debug_start_trace = std.debug.Trace.init;

pub const have_ipc = switch (builtin.os.tag) {
    .wasi, .freestanding => false,
    else => true,
};

const noop_impl = builtin.single_threaded or switch (builtin.os.tag) {
    .wasi, .freestanding => true,
    else => false,
} or switch (builtin.zig_backend) {
    else => false,
};

pub const ParentFileError = error{
    UnsupportedOperation,
    EnvironmentVariableMissing,
    UnrecognizedFormat,
};

pub const Options = struct {
    /// 用户提供的具有静态生存期的缓冲区。
    ///
    /// 用于存储发送到终端的整个写入缓冲区。若进度输出无法放入此缓冲区,
    /// 则会截断输出;这会影响显示,但不会导致功能故障。
    ///
    /// 必须至少为 200 字节。
    draw_buffer: []u8 = &default_draw_buffer,
    /// 向终端写入更新之间间隔的纳秒数。
    refresh_rate_ns: Io.Duration = .fromMilliseconds(80),
    /// 保持输出隐藏的纳秒数。
    initial_delay_ns: Io.Duration = .fromMilliseconds(200),
    /// 若提供,则进度项包含分母。
    /// 0 表示未知。
    estimated_total_items: usize = 0,
    root_name: []const u8 = "",
    disable_printing: bool = false,
};

/// 初始化全局 Progress 实例。
///
/// 断言仅存在一个全局 Progress 实例。
///
/// 完成后调用 `Node.end`。
///
/// 若发生错误,则填充 `start_failure`。
pub fn start(io: Io, options: Options) Node {
    // 确保仅有 1 个全局 Progress 对象。
    if (global_progress.node_end_index != 0) {
        debug_start_trace.dump();
        unreachable;
    }
    debug_start_trace.add("first initialized here");

    @memset(&global_progress.node_parents, .unused);
    @memset(&global_progress.ipc, .{ .locked = false, .valid = false, .generation = 0 });
    const root_node = Node.init(@fromBackingInt(@intCast(0)), .none, options.root_name, options.estimated_total_items);
    global_progress.node_end_index = 1;

    assert(options.draw_buffer.len >= 200);
    global_progress.draw_buffer = options.draw_buffer;
    global_progress.refresh_rate_ns = @intCast(options.refresh_rate_ns.toNanoseconds());
    global_progress.initial_delay_ns = @intCast(options.initial_delay_ns.toNanoseconds());

    if (noop_impl) return .none;

    global_progress.io = io;

    if (io.vtable.progressParentFile(io.userdata)) |ipc_file| {
        global_progress.update_worker = io.concurrent(ipcThreadRun, .{ io, ipc_file }) catch |err| {
            global_progress.start_failure = .{ .spawn_ipc_worker = err };
            return .none;
        };
    } else |env_err| switch (env_err) {
        error.EnvironmentVariableMissing => {
            if (options.disable_printing) return .none;
            const stderr: Io.File = .stderr();
            global_progress.terminal = stderr;
            if (stderr.enableAnsiEscapeCodes(io)) |_| {
                global_progress.terminal_mode = .ansi_escape_codes;
            } else |_| if (is_windows) {
                var get_console_cp = windows.CONSOLE.USER_IO.GET_CP(.Output);
                // 通常此处应传入 `null`,目标为 `operate`,因为 kernel32 函数不接受句柄。
                // 但若仍传入句柄,当它未关联到当前进程的控制台时就会得到错误,从而在同一次系统调用中有效整合 `isTty` 检查。
                //
                //
                //
                switch (get_console_cp.operate(io, stderr) catch |err| switch (err) {
                    error.Canceled => {
                        io.recancel();
                        return .none;
                    },
                }) {
                    .SUCCESS => global_progress.terminal_mode = .{ .windows_api = .{
                        .code_page = get_console_cp.Data.CodePage,
                    } },
                    .INVALID_HANDLE => {},
                    else => {},
                }
            }
            if (future: switch (global_progress.terminal_mode) {
                .off => return .none,
                .ansi_escape_codes => {
                    if (have_sigwinch) {
                        const act: posix.Sigaction = .{
                            .handler = .{ .sigaction = handleSigWinch },
                            .mask = posix.sigemptyset(),
                            .flags = (posix.SA.SIGINFO | posix.SA.RESTART),
                        };
                        posix.sigaction(.WINCH, &act, null);
                    }
                    break :future io.concurrent(updateTask, .{io});
                },
                .windows_api => io.concurrent(windowsApiUpdateTask, .{io}),
            }) |future| {
                global_progress.update_worker = future;
            } else |err| {
                global_progress.start_failure = .{ .spawn_update_worker = err };
                return .none;
            }
        },
        else => |e| {
            global_progress.start_failure = .{ .parent_ipc = e };
            return .none;
        },
    }

    return root_node;
}

pub fn setStatus(new_status: Status) void {
    if (noop_impl) return;
    @atomicStore(Status, &global_progress.status, new_status, .monotonic);
}

/// 返回是否需要调整大小以获知终端尺寸。
fn wait(io: Io, timeout_ns: u64) Io.Cancelable!bool {
    const timeout: Io.Timeout = .{ .duration = .{
        .clock = .awake,
        .raw = .fromNanoseconds(timeout_ns),
    } };
    const resize_flag = if (global_progress.redraw_event.waitTimeout(io, timeout)) |_| true else |err| switch (err) {
        error.Timeout => false,
        error.Canceled => |e| return e,
    };
    global_progress.redraw_event.reset();
    return resize_flag or (global_progress.cols == 0);
}

const WorkerError = error{WindowTooSmall} || Io.ConcurrentError || Io.Cancelable ||
    Io.File.Writer.Error || Io.Operation.FileReadStreaming.Error;

fn updateTask(io: Io) WorkerError!void {
    // 将此数据存储在线程中,使其无需成为
    // 主可执行文件链接器数据的一部分。
    var serialized_buffer: Serialized.Buffer = undefined;
    serialized_buffer.init();
    defer serialized_buffer.batch.cancel(io);

    // 此函数绕过 `Io.lockStderr`/`Io.tryLockStderr`
    // 内部的包装代码,避免清空终端两次。
    // 不过仍需经过 `Io` 实例,以兼容其可能使用的
    // 任务切换互斥锁。

    try maybeUpdateSize(io, try wait(io, global_progress.initial_delay_ns));
    errdefer {
        const cancel_protection = io.swapCancelProtection(.blocked);
        defer _ = io.swapCancelProtection(cancel_protection);
        const stderr = io.vtable.lockStderr(io.userdata, null) catch |err| switch (err) {
            error.Canceled => unreachable, // 已阻塞
        };
        defer io.unlockStderr();
        clearWrittenWithEscapeCodes(stderr.file_writer) catch {};
    }
    while (true) {
        const buffer, _ = try computeRedraw(io, &serialized_buffer);
        if (try io.vtable.tryLockStderr(io.userdata, null)) |locked_stderr| {
            defer io.unlockStderr();
            global_progress.need_clear = true;
            locked_stderr.file_writer.interface.writeAll(buffer) catch |err| switch (err) {
                error.WriteFailed => return locked_stderr.file_writer.err.?,
            };
        }

        try maybeUpdateSize(io, try wait(io, global_progress.refresh_rate_ns));
    }
}

const WindowsApiError = Io.Cancelable || Io.UnexpectedError;

fn windowsApiWriteMarker(io: Io) WindowsApiError!void {
    // 写入标记,以便清除时找到进度显示的起始位置。
    // 注意:不必使用 WriteConsoleW,但使用它可避免处理代码页。
    const terminal = global_progress.terminal;
    var write_console = windows.CONSOLE.USER_IO.WRITE(.WideCharacter);
    const buffer = [1]windows.WCHAR{windows_api_start_marker};
    switch ((try io.operate(.{ .device_io_control = .{
        .file = terminal,
        .code = windows.IOCTL.CONDRV.ISSUE_USER_IO,
        .in = @ptrCast(&write_console.request(null, 1, .{
            .{ .Size = @sizeOf(@TypeOf(buffer)), .Pointer = &buffer },
        }, 0, .{})),
    } })).device_io_control.u.Status) {
        .SUCCESS => {},
        .CANCELLED => unreachable,
        else => |status| return windows.unexpectedStatus(status),
    }
}

fn windowsApiUpdateTask(io: Io) WorkerError!void {
    // 将此数据存储在线程中,使其无需成为
    // 主可执行文件链接器数据的一部分。
    var serialized_buffer: Serialized.Buffer = undefined;
    serialized_buffer.init();
    defer serialized_buffer.batch.cancel(io);

    // 此函数绕过 `Io.lockStderr`/`Io.tryLockStderr`
    // 内部的包装代码,避免清空终端两次。
    // 不过仍需经过 `Io` 实例,以兼容其可能使用的
    // 任务切换互斥锁。

    try maybeUpdateSize(io, try wait(io, global_progress.initial_delay_ns));
    errdefer {
        const cancel_protection = io.swapCancelProtection(.blocked);
        defer _ = io.swapCancelProtection(cancel_protection);
        _ = io.vtable.lockStderr(io.userdata, null) catch |err| switch (err) {
            error.Canceled => unreachable, // 已阻塞
        };
        defer io.unlockStderr();
        clearWrittenWindowsApi(io) catch {};
    }
    while (true) {
        const buffer, const nl_n = try computeRedraw(io, &serialized_buffer);
        if (io.vtable.tryLockStderr(io.userdata, null) catch return) |locked_stderr| {
            defer io.unlockStderr();
            try clearWrittenWindowsApi(io);
            try windowsApiWriteMarker(io);
            global_progress.need_clear = true;
            locked_stderr.file_writer.interface.writeAll(buffer) catch |err| switch (err) {
                error.WriteFailed => return locked_stderr.file_writer.err.?,
            };
            windowsApiMoveToMarker(io, nl_n) catch return;
        }

        try maybeUpdateSize(io, try wait(io, global_progress.refresh_rate_ns));
    }
}

fn ipcThreadRun(io: Io, file: Io.File) WorkerError!void {
    // 将此数据存储在线程中,使其无需成为
    // 主可执行文件链接器数据的一部分。
    var serialized_buffer: Serialized.Buffer = undefined;
    serialized_buffer.init();
    defer serialized_buffer.batch.cancel(io);
    var fw = file.writerStreaming(io, &.{});

    _ = try io.sleep(.fromNanoseconds(global_progress.initial_delay_ns), .awake);
    while (true) {
        writeIpc(&fw.interface, try serialize(io, &serialized_buffer)) catch |err| switch (err) {
            error.WriteFailed => return fw.err.?,
        };

        _ = try io.sleep(.fromNanoseconds(global_progress.refresh_rate_ns), .awake);
    }
}

const start_sync = "\x1b[?2026h";
const up_one_line = "\x1bM";
const clear = "\x1b[J";
const save = "\x1b7";
const restore = "\x1b8";
const finish_sync = "\x1b[?2026l";

const progress_remove = "\x1b]9;4;0\x1b\\";
const @"progress_normal {d}" = "\x1b]9;4;1;{d}\x1b\\";
const @"progress_error {d}" = "\x1b]9;4;2;{d}\x1b\\";
const progress_pulsing = "\x1b]9;4;3\x1b\\";
const progress_pulsing_error = "\x1b]9;4;2\x1b\\";
const progress_normal_100 = "\x1b]9;4;1;100\x1b\\";
const progress_error_100 = "\x1b]9;4;2;100\x1b\\";

const TreeSymbol = enum {
    /// ├─
    tee,
    /// │
    line,
    /// └─
    langle,

    const Encoding = enum {
        ansi_escapes,
        code_page_437,
        utf8,
        ascii,
    };

    /// 转义序列的字符串字面量表示
    fn escapeSeq(symbol: TreeSymbol) *const [9:0]u8 {
        return switch (symbol) {
            .tee => "\x1B\x28\x30\x74\x71\x1B\x28\x42 ",
            .line => "\x1B\x28\x30\x78\x1B\x28\x42  ",
            .langle => "\x1B\x28\x30\x6d\x71\x1B\x28\x42 ",
        };
    }

    fn bytes(symbol: TreeSymbol, encoding: Encoding) []const u8 {
        return switch (encoding) {
            .ansi_escapes => escapeSeq(symbol),
            .code_page_437 => switch (symbol) {
                .tee => "\xC3\xC4 ",
                .line => "\xB3  ",
                .langle => "\xC0\xC4 ",
            },
            .utf8 => switch (symbol) {
                .tee => "├─ ",
                .line => "│  ",
                .langle => "└─ ",
            },
            .ascii => switch (symbol) {
                .tee => "|- ",
                .line => "|  ",
                .langle => "+- ",
            },
        };
    }

    fn maxByteLen(symbol: TreeSymbol) usize {
        var max: usize = 0;
        inline for (@typeInfo(Encoding).@"enum".field_names) |field_name| {
            const len = symbol.bytes(@field(Encoding, field_name)).len;
            max = @max(max, len);
        }
        return max;
    }
};

fn appendTreeSymbol(symbol: TreeSymbol, buf: []u8, start_i: usize) usize {
    switch (global_progress.terminal_mode) {
        .off => unreachable,
        .ansi_escape_codes => {
            const bytes = symbol.escapeSeq();
            buf[start_i..][0..bytes.len].* = bytes.*;
            return start_i + bytes.len;
        },
        .windows_api => |windows_api| {
            const bytes = switch (windows_api.code_page) {
                // 代码页 437 是默认代码页,包含框线绘制符号。
                437 => symbol.bytes(.code_page_437),
                // UTF-8
                65001 => symbol.bytes(.utf8),
                // 回退到 ASCII 近似表示
                else => symbol.bytes(.ascii),
            };
            @memcpy(buf[start_i..][0..bytes.len], bytes);
            return start_i + bytes.len;
        },
    }
}

pub fn clearWrittenWithEscapeCodes(file_writer: *Io.File.Writer) Io.Writer.Error!void {
    if (noop_impl or !global_progress.need_clear) return;
    try file_writer.interface.writeAll(clear ++ progress_remove);
    global_progress.need_clear = false;
}

/// U+25BA 或 ►
const windows_api_start_marker = 0x25BA;

fn clearWrittenWindowsApi(io: Io) WindowsApiError!void {
    // 此处采用“标记”策略,思路如下:
    // - 始终在进度内容的开头写入一个标记,这里使用 U+25BA,即 ►。
    // - 获取当前光标位置,即进度内容的末尾。
    // - 减去已写入的行数,得到预期的进度内容起始位置。
    // - 检查进度内容起始处的第一个字符是否为标记。
    // - 若不是标记,继续逐行向前检查,直到找到标记。
    // - 从该位置向下清屏,并将光标设为起始位置。
    //
    // 此策略在自动换行时仍然有效,也能应对窗口
    // 任意调整大小或滚动的情况。
    //
    // 注意:
    // - 理想情况下,标记应使用零宽字符,但 Windows 控制台
    //   似乎不支持渲染零宽字符,会将其显示为空格。
    // - 技术上也可以使用字符属性实现同样的标记思路
    //   (https://learn.microsoft.com/en-us/windows/console/console-screen-buffers#character-attributes)
    //   但必须使用有效属性,并且该属性确实应用于第一个
    //   字符,才能通过 ReadConsoleOutputAttribute 读取。现有属性
    //   似乎都不能同时满足不可见和不影响显示的要求。
    if (!global_progress.need_clear) return;
    const terminal = global_progress.terminal;
    const screen_area = @as(windows.DWORD, global_progress.cols) * global_progress.rows;

    var get_console_info = windows.CONSOLE.USER_IO.GET_SCREEN_BUFFER_INFO;
    switch (try get_console_info.operate(io, terminal)) {
        .SUCCESS => {},
        else => |status| return windows.unexpectedStatus(status),
    }
    var fill_spaces = windows.CONSOLE.USER_IO.FILL(
        .{ .WideCharacter = ' ' },
        screen_area,
        get_console_info.Data.dwCursorPosition,
    );
    switch (try fill_spaces.operate(io, terminal)) {
        .SUCCESS => {},
        else => |status| return windows.unexpectedStatus(status),
    }
}

fn windowsApiMoveToMarker(io: Io, nl_n: usize) WindowsApiError!void {
    const terminal = global_progress.terminal;
    var get_console_info = windows.CONSOLE.USER_IO.GET_SCREEN_BUFFER_INFO;
    switch (try get_console_info.operate(io, terminal)) {
        .SUCCESS => {},
        else => |status| return windows.unexpectedStatus(status),
    }
    const cursor_pos = get_console_info.Data.dwCursorPosition;
    const expected_y = cursor_pos.Y - @as(i16, @intCast(nl_n));
    var start_pos: windows.COORD = .{ .X = 0, .Y = expected_y };
    while (start_pos.Y >= 0) : (start_pos.Y -= 1) {
        var read_output_char = windows.CONSOLE.USER_IO.READ_OUTPUT_CHARACTER(start_pos, .WideCharacter);
        var buffer: [1]windows.WCHAR = undefined;
        switch ((try io.operate(.{ .device_io_control = .{
            .file = .{
                .handle = windows.peb().ProcessParameters.ConsoleHandle,
                .flags = .{ .nonblocking = false },
            },
            .code = windows.IOCTL.CONDRV.ISSUE_USER_IO,
            .in = @ptrCast(&read_output_char.request(terminal, 0, .{}, 1, .{
                .{ .Size = @sizeOf(@TypeOf(buffer)), .Pointer = &buffer },
            })),
        } })).device_io_control.u.Status) {
            .SUCCESS => {},
            .CANCELLED => unreachable,
            else => |status| return windows.unexpectedStatus(status),
        }
        if (read_output_char.Data.nLength >= 1 and buffer[0] == windows_api_start_marker) break;
    } else {
        // 如果找不到标记,则假定没有任何行发生换行。
        start_pos = .{ .X = 0, .Y = expected_y };
    }
    var set_cursor_position = windows.CONSOLE.USER_IO.SET_CURSOR_POSITION(start_pos);
    switch (try set_cursor_position.operate(io, terminal)) {
        .SUCCESS => {},
        else => |status| return windows.unexpectedStatus(status),
    }
}

const Children = struct {
    child: Node.OptionalIndex,
    sibling: Node.OptionalIndex,
};

const Serialized = struct {
    parents: []Node.Parent,
    storage: []Node.Storage,

    const Buffer = struct {
        parents: [node_storage_buffer_len]Node.Parent,
        storage: [node_storage_buffer_len]Node.Storage,

        ipc_start: u8,
        ipc_end: u8,
        ipc_data: [ipc_storage_buffer_len]Ipc.Data,
        ipc_buffers: [ipc_storage_buffer_len][max_packet_len]u8,
        ipc_vecs: [ipc_storage_buffer_len][1][]u8,
        batch_storage: [ipc_storage_buffer_len]Io.Operation.Storage,
        batch: Io.Batch,

        fn init(buffer: *Buffer) void {
            buffer.ipc_start = 0;
            buffer.ipc_end = 0;
            @memset(&buffer.ipc_data, .unused);
            buffer.batch = .init(&buffer.batch_storage);
        }
    };
};

fn serialize(io: Io, serialized_buffer: *Serialized.Buffer) !Serialized {
    var prev_parents: [node_storage_buffer_len]Node.Parent = undefined;
    var prev_storage: [node_storage_buffer_len]Node.Storage = undefined;
    {
        const ipc_start = serialized_buffer.ipc_start;
        const ipc_end = serialized_buffer.ipc_end;
        @memcpy(prev_parents[ipc_start..ipc_end], serialized_buffer.parents[ipc_start..ipc_end]);
        @memcpy(prev_storage[ipc_start..ipc_end], serialized_buffer.storage[ipc_start..ipc_end]);
    }

    // 遍历所有节点,并构造状态的可序列化副本,以便无需原子操作即可检查。
    // 此处调用 `@min`,是因为 `node_end_index` 有时可能短暂超过
    // 节点数量。
    const end_index = @min(
        @atomicLoad(u32, &global_progress.node_end_index, .monotonic),
        node_storage_buffer_len,
    );
    var map: [node_storage_buffer_len]Node.OptionalIndex = undefined;
    var serialized_len: u8 = 0;
    var maybe_ipc_start: ?u8 = null;
    for (
        global_progress.node_parents[0..end_index],
        global_progress.node_storage[0..end_index],
        map[0..end_index],
    ) |*parent_ptr, *storage_ptr, *map_entry| {
        const parent = @atomicLoad(Node.Parent, parent_ptr, .monotonic);
        if (parent == .unused) {
            // 在此循环中,我们可能读到“混合”的节点数据,原因可能是某些特殊的原子操作行为,也可能是循环运行期间某个节点真的被释放。这可能导致父节点引用指向不存在的节点。如果不进行此赋值,映射条目将包含陈旧数据。通过赋值为 none,具有无效父指针的子节点会被安全地从树中省略。
            //
            // 注意,即使读到这种“混合”节点数据,也不必担心产生潜在的“循环”数据:若某节点直接或间接地以自己为父节点,它根本不会被打印。总体思路是性能优先于每帧输出完全正确,因为此 API 很可能用于热点路径。
            //
            //
            //
            //
            //
            //
            //
            //
            map_entry.* = .none;
            continue;
        }
        const dest_storage = &serialized_buffer.storage[serialized_len];
        copyAtomicLoad(&dest_storage.name, &storage_ptr.name);
        dest_storage.estimated_total_count = @atomicLoad(u32, &storage_ptr.estimated_total_count, .acquire); // 与 `setIpcIndex` 中的释放操作同步
        dest_storage.completed_count = @atomicLoad(u32, &storage_ptr.completed_count, .monotonic);

        serialized_buffer.parents[serialized_len] = parent;
        map_entry.* = @fromBackingInt(@intCast(serialized_len));
        if (maybe_ipc_start == null and dest_storage.getIpcIndex() != null) maybe_ipc_start = serialized_len;
        serialized_len += 1;
    }

    // 重新映射父节点,使其指向序列化数组内部。
    for (serialized_buffer.parents[0..serialized_len]) |*parent| {
        parent.* = switch (parent.*) {
            .unused => unreachable,
            .none => .none,
            _ => |p| map[@backingInt(p)].toParent(),
        };
    }

    // 填充管道缓冲区。
    const batch = &serialized_buffer.batch;
    batch.awaitConcurrent(io, .{
        .duration = .{ .raw = .zero, .clock = .awake },
    }) catch |err| switch (err) {
        error.Timeout => {},
        else => |e| return e,
    };
    var ready_len: u8 = 0;
    while (batch.next()) |operation| switch (operation.index) {
        0...ipc_storage_buffer_len - 1 => {
            const ipc_data = &serialized_buffer.ipc_data[operation.index];
            ipc_data.bytes_read += @intCast(
                operation.result.file_read_streaming catch |err| switch (err) {
                    error.EndOfStream => {
                        const file = global_progress.ipc_files[operation.index];
                        const ipc = @atomicRmw(
                            Ipc,
                            &global_progress.ipc[operation.index],
                            .And,
                            .{
                                .locked = false,
                                .valid = true,
                                .generation = std.math.maxInt(Ipc.Generation),
                            },
                            .release,
                        );
                        assert(ipc.locked);
                        if (!ipc.valid) file.close(io);
                        ipc_data.* = .unused;
                        continue;
                    },
                    else => |e| return e,
                },
            );
            assert(ipc_data.state == .pending);
            ipc_data.state = .ready;
            ready_len += 1;
        },
        else => unreachable,
    };

    // 查找与子进程对应的节点。
    const ipc_start = maybe_ipc_start orelse serialized_len;
    serialized_buffer.ipc_start = ipc_start;
    for (
        serialized_buffer.parents[ipc_start..serialized_len],
        serialized_buffer.storage[ipc_start..serialized_len],
        ipc_start..,
    ) |main_parent, *main_storage, main_index| {
        if (main_parent == .unused) continue;
        const ipc_index = main_storage.getIpcIndex() orelse continue;
        const ipc = &global_progress.ipc[ipc_index.slot];
        const ipc_data = &serialized_buffer.ipc_data[ipc_index.slot];
        state: switch (ipc_data.state) {
            .unused => {
                if (@cmpxchgWeak(
                    Ipc,
                    ipc,
                    .{ .locked = false, .valid = true, .generation = ipc_index.generation },
                    .{ .locked = true, .valid = true, .generation = ipc_index.generation },
                    .acquire,
                    .monotonic,
                )) |_| continue;

                const ipc_vec = &serialized_buffer.ipc_vecs[ipc_index.slot];
                ipc_vec.* = .{&serialized_buffer.ipc_buffers[ipc_index.slot]};
                batch.addAt(ipc_index.slot, .{ .file_read_streaming = .{
                    .file = global_progress.ipc_files[ipc_index.slot],
                    .data = ipc_vec,
                } });

                ipc_data.* = .{
                    .state = .pending,
                    .bytes_read = 0,
                    .main_index = @intCast(main_index),
                    .start_index = serialized_len,
                    .nodes_len = 0,
                };
                main_storage.completed_count = 0;
                main_storage.estimated_total_count = 0;
            },
            .pending => {
                const start_index = ipc_data.start_index;
                const nodes_len = @min(ipc_data.nodes_len, node_storage_buffer_len - serialized_len);

                main_storage.copyRoot(&prev_storage[ipc_data.main_index]);
                @memcpy(
                    serialized_buffer.storage[serialized_len..][0..nodes_len],
                    prev_storage[start_index..][0..nodes_len],
                );
                for (
                    serialized_buffer.parents[serialized_len..][0..nodes_len],
                    prev_parents[serialized_len..][0..nodes_len],
                ) |*parent, prev_parent| parent.* = switch (prev_parent) {
                    .none, .unused => .none,
                    _ => if (@backingInt(prev_parent) == ipc_data.main_index)
                        @fromBackingInt(@intCast(main_index))
                    else if (@backingInt(prev_parent) >= start_index and
                        @backingInt(prev_parent) < start_index + nodes_len)
                        @fromBackingInt(@intCast(@backingInt(prev_parent) - start_index + serialized_len))
                    else
                        .none,
                };

                ipc_data.main_index = @intCast(main_index);
                ipc_data.start_index = serialized_len;
                ipc_data.nodes_len = nodes_len;
                serialized_len += nodes_len;
            },
            .ready => {
                const ipc_buffer = &serialized_buffer.ipc_buffers[ipc_index.slot];
                const packet_start, const packet_end = ipc_data.findLastPacket(ipc_buffer);
                const packet_is_empty = packet_end - packet_start <= 1;
                if (!packet_is_empty) {
                    const storage, const parents, const nodes_len = packet_contents: {
                        var packet_index: usize = packet_start;
                        const nodes_len: u16 = ipc_buffer[packet_index];
                        packet_index += 1;
                        const storage_bytes =
                            ipc_buffer[packet_index..][0 .. nodes_len * @sizeOf(Node.Storage)];
                        packet_index += storage_bytes.len;
                        const parents_bytes =
                            ipc_buffer[packet_index..][0 .. nodes_len * @sizeOf(Node.Parent)];
                        packet_index += parents_bytes.len;
                        assert(packet_index == packet_end);
                        const storage: []align(1) const Node.Storage = @ptrCast(storage_bytes);
                        const parents: []align(1) const Node.Parent = @ptrCast(parents_bytes);
                        const children_nodes_len =
                            @min(nodes_len - 1, node_storage_buffer_len - serialized_len);
                        break :packet_contents .{ storage, parents, children_nodes_len };
                    };

                    // 在此挂载根目录。
                    main_storage.copyRoot(&storage[0]);
                    if (is_big_endian) main_storage.byteSwap();

                    // 将树的剩余部分复制到末尾。
                    const serialized_storage =
                        serialized_buffer.storage[serialized_len..][0..nodes_len];
                    @memcpy(serialized_storage, storage[1..][0..nodes_len]);
                    if (is_big_endian) for (serialized_storage) |*s| s.byteSwap();

                    // 根据子树的挂接方式修正父指针。
                    for (
                        serialized_buffer.parents[serialized_len..][0..nodes_len],
                        parents[1..][0..nodes_len],
                    ) |*parent, prev_parent| parent.* = switch (prev_parent) {
                        // 修正无效数据,使其余代码看不到 `unused`。
                        .none, .unused => .none,
                        // 根节点在此处挂载。
                        @as(Node.Parent, @fromBackingInt(@intCast(0))) => @fromBackingInt(@intCast(main_index)),
                        // 末尾挂载的其他节点。
                        // 不要信任子节点数据;若数据超出预期范围,
                        // 则忽略它。这也处理数据被截断的情况。
                        _ => if (@backingInt(prev_parent) <= nodes_len)
                            @fromBackingInt(@intCast(@backingInt(prev_parent) - 1 + serialized_len))
                        else
                            .none,
                    };

                    ipc_data.main_index = @intCast(main_index);
                    ipc_data.start_index = serialized_len;
                    ipc_data.nodes_len = nodes_len;
                    serialized_len += nodes_len;
                }
                const ipc_vec = &serialized_buffer.ipc_vecs[ipc_index.slot];
                ipc_data.rebase(ipc_buffer, ipc_vec, batch, ipc_index.slot, packet_end);
                ready_len -= 1;
                if (packet_is_empty) continue :state .pending;
            },
        }
    }
    serialized_buffer.ipc_end = serialized_len;

    // 忽略未使用管道的数据。这可确保子进程存在时,最终
    // 会遇到 `EndOfStream` 并关闭管道。
    if (ready_len > 0) for (
        &serialized_buffer.ipc_data,
        &serialized_buffer.ipc_buffers,
        &serialized_buffer.ipc_vecs,
        0..,
    ) |*ipc_data, *ipc_buffer, *ipc_vec, ipc_slot| switch (ipc_data.state) {
        .unused, .pending => {},
        .ready => {
            _, const packet_end = ipc_data.findLastPacket(ipc_buffer);
            ipc_data.rebase(ipc_buffer, ipc_vec, batch, @intCast(ipc_slot), packet_end);
            ready_len -= 1;
        },
    };
    assert(ready_len == 0);

    return .{
        .parents = serialized_buffer.parents[0..serialized_len],
        .storage = serialized_buffer.storage[0..serialized_len],
    };
}

fn computeRedraw(io: Io, serialized_buffer: *Serialized.Buffer) !struct { []u8, usize } {
    if (global_progress.rows == 0 or global_progress.cols == 0) return error.WindowTooSmall;

    const serialized = try serialize(io, serialized_buffer);

    // 现在可无需原子操作分析图的副本,并重建
    // 规范数据中不存在的子节点列表。下方遍历树时
    // 需要这些列表。

    var children_buffer: [node_storage_buffer_len]Children = undefined;
    const children = children_buffer[0..serialized.parents.len];

    @memset(children, .{ .child = .none, .sibling = .none });

    for (serialized.parents, 0..) |parent, child_index_usize| {
        const child_index: Node.Index = @fromBackingInt(@intCast(child_index_usize));
        assert(parent != .unused);
        const parent_index = parent.unwrap() orelse continue;
        const children_node = &children[@backingInt(parent_index)];
        if (children_node.child.unwrap()) |existing_child_index| {
            const existing_child = &children[@backingInt(existing_child_index)];
            children[@backingInt(child_index)].sibling = existing_child.sibling;
            existing_child.sibling = child_index.toOptional();
        } else {
            children_node.child = child_index.toOptional();
        }
    }

    // 每次重绘时采用以下策略:
    // 清除到屏幕末尾,写入内容,将光标移到行首,再将光标上移 N 行。
    // 这样可以将光标保持在行首,避免未锁定的 stderr 写入被清除操作吞掉。
    //

    var i: usize = 0;
    const buf = global_progress.draw_buffer;

    if (global_progress.terminal_mode == .ansi_escape_codes) {
        buf[i..][0..start_sync.len].* = start_sync.*;
        i += start_sync.len;
    }

    switch (global_progress.terminal_mode) {
        .off => unreachable,
        .ansi_escape_codes => {
            buf[i..][0..clear.len].* = clear.*;
            i += clear.len;
        },
        .windows_api => {},
    }

    const root_node_index: Node.Index = @fromBackingInt(@intCast(0));
    i, const nl_n = computeNode(buf, i, 0, serialized, children, root_node_index);

    if (global_progress.terminal_mode == .ansi_escape_codes) {
        {
            // 设置进度状态 https://conemu.github.io/en/AnsiEscapeCodes.html#ConEmu_specific_OSC
            const root_storage = &serialized.storage[0];
            const storage = if (root_storage.name[0] != 0 or children[0].child == .none) root_storage else &serialized.storage[@backingInt(children[0].child)];
            const estimated_total = storage.estimated_total_count;
            const completed_items = storage.completed_count;
            const status = @atomicLoad(Status, &global_progress.status, .monotonic);
            switch (status) {
                .working => {
                    if (estimated_total == 0) {
                        buf[i..][0..progress_pulsing.len].* = progress_pulsing.*;
                        i += progress_pulsing.len;
                    } else {
                        const percent = @as(u64, completed_items) * 100 / estimated_total;
                        if (std.mem.print(buf[i..], @"progress_normal {d}", .{percent})) |b| {
                            i += b.len;
                        } else |_| {}
                    }
                },
                .success => {
                    buf[i..][0..progress_remove.len].* = progress_remove.*;
                    i += progress_remove.len;
                },
                .failure => {
                    buf[i..][0..progress_error_100.len].* = progress_error_100.*;
                    i += progress_error_100.len;
                },
                .failure_working => {
                    if (estimated_total == 0) {
                        buf[i..][0..progress_pulsing_error.len].* = progress_pulsing_error.*;
                        i += progress_pulsing_error.len;
                    } else {
                        const percent = @as(u64, completed_items) * 100 / estimated_total;
                        if (std.mem.print(buf[i..], @"progress_error {d}", .{percent})) |b| {
                            i += b.len;
                        } else |_| {}
                    }
                },
            }
        }

        if (nl_n > 0) {
            buf[i] = '\r';
            i += 1;
            for (0..nl_n) |_| {
                buf[i..][0..up_one_line.len].* = up_one_line.*;
                i += up_one_line.len;
            }
        }

        buf[i..][0..finish_sync.len].* = finish_sync.*;
        i += finish_sync.len;
    }

    return .{ buf[0..i], nl_n };
}

fn computePrefix(
    buf: []u8,
    start_i: usize,
    nl_n: usize,
    serialized: Serialized,
    children: []const Children,
    node_index: Node.Index,
) usize {
    var i = start_i;
    const parent_index = serialized.parents[@backingInt(node_index)].unwrap() orelse return i;
    if (serialized.parents[@backingInt(parent_index)] == .none) return i;
    if (@backingInt(serialized.parents[@backingInt(parent_index)]) == 0 and
        serialized.storage[0].name[0] == 0)
    {
        return i;
    }
    i = computePrefix(buf, i, nl_n, serialized, children, parent_index);
    if (children[@backingInt(parent_index)].sibling == .none) {
        const prefix = "   ";
        const upper_bound_len = prefix.len + lineUpperBoundLen(nl_n);
        if (i + upper_bound_len > buf.len) return buf.len;
        buf[i..][0..prefix.len].* = prefix.*;
        i += prefix.len;
    } else {
        const upper_bound_len = TreeSymbol.line.maxByteLen() + lineUpperBoundLen(nl_n);
        if (i + upper_bound_len > buf.len) return buf.len;
        i = appendTreeSymbol(.line, buf, i);
    }
    return i;
}

fn lineUpperBoundLen(nl_n: usize) usize {
    // Windows 上为 \r\n,其他系统上为 \n。
    const nl_len = if (is_windows) 2 else 1;
    return @max(TreeSymbol.tee.maxByteLen(), TreeSymbol.langle.maxByteLen()) +
        "[4294967296/4294967296] ".len + Node.max_name_len + nl_len +
        (1 + (nl_n + 1) * up_one_line.len) +
        finish_sync.len;
}

fn computeNode(
    buf: []u8,
    start_i: usize,
    start_nl_n: usize,
    serialized: Serialized,
    children: []const Children,
    node_index: Node.Index,
) struct { usize, usize } {
    var i = start_i;
    var nl_n = start_nl_n;

    i = computePrefix(buf, i, nl_n, serialized, children, node_index);

    if (i + lineUpperBoundLen(nl_n) > buf.len)
        return .{ start_i, start_nl_n };

    const storage = &serialized.storage[@backingInt(node_index)];
    const estimated_total = storage.estimated_total_count;
    const completed_items = storage.completed_count;
    const name = if (std.mem.findScalar(u8, &storage.name, 0)) |end| storage.name[0..end] else &storage.name;
    const parent = serialized.parents[@backingInt(node_index)];

    if (parent != .none) p: {
        if (@backingInt(parent) == 0 and serialized.storage[0].name[0] == 0) {
            break :p;
        }
        if (children[@backingInt(node_index)].sibling == .none) {
            i = appendTreeSymbol(.langle, buf, i);
        } else {
            i = appendTreeSymbol(.tee, buf, i);
        }
    }

    const is_empty_root = @backingInt(node_index) == 0 and serialized.storage[0].name[0] == 0;
    if (!is_empty_root) {
        if (name.len != 0 or estimated_total > 0) {
            if (estimated_total > 0) {
                if (std.mem.print(buf[i..], "[{d}/{d}] ", .{ completed_items, estimated_total })) |b| {
                    i += b.len;
                } else |_| {}
            } else if (completed_items != 0) {
                if (std.mem.print(buf[i..], "[{d}] ", .{completed_items})) |b| {
                    i += b.len;
                } else |_| {}
            }
            if (name.len != 0) {
                if (std.mem.print(buf[i..], "{s}", .{name})) |b| {
                    i += b.len;
                } else |_| {}
            }
        }

        i = @min(global_progress.cols + start_i, i);
        if (is_windows) {
            // Windows 上需要 \r\n,才能使设置了
            // ENABLE_VIRTUAL_TERMINAL_PROCESSING | DISABLE_NEWLINE_AUTO_RETURN
            // 控制台模式的旧控制台正常工作。
            buf[i] = '\r';
            i += 1;
        }
        buf[i] = '\n';
        i += 1;
        nl_n += 1;
    }

    if (global_progress.withinRowLimit(nl_n)) {
        if (children[@backingInt(node_index)].child.unwrap()) |child| {
            i, nl_n = computeNode(buf, i, nl_n, serialized, children, child);
        }
    }

    if (global_progress.withinRowLimit(nl_n)) {
        if (children[@backingInt(node_index)].sibling.unwrap()) |sibling| {
            i, nl_n = computeNode(buf, i, nl_n, serialized, children, sibling);
        }
    }

    return .{ i, nl_n };
}

fn withinRowLimit(p: *Progress, nl_n: usize) bool {
    // 此处加 2,避免 PS1 滚出终端顶部。
    // 加一是因为光标保持在下一行,
    // 再加一以计入 PS1。
    return nl_n + 2 < p.rows;
}

fn writeIpc(writer: *Io.Writer, serialized: Serialized) Io.Writer.Error!void {
    // 必要时交换字节序,确保管道中使用小端序。需要这样做,
    // 因为父进程或子进程可能在 qemu 中运行。
    if (is_big_endian) for (serialized.storage) |*s| s.byteSwap();

    assert(serialized.parents.len == serialized.storage.len);
    const serialized_len: u8 = @intCast(serialized.parents.len);
    const header = std.mem.asBytes(&serialized_len);
    const storage = std.mem.sliceAsBytes(serialized.storage);
    const parents = std.mem.sliceAsBytes(serialized.parents);

    var vec = [3][]const u8{ header, storage, parents };
    try writer.writeVecAll(&vec);
}

fn maybeUpdateSize(io: Io, resize_flag: bool) !void {
    if (!resize_flag) return;

    const file = global_progress.terminal;

    if (is_windows) {
        var get_console_info = windows.CONSOLE.USER_IO.GET_SCREEN_BUFFER_INFO;
        switch (try get_console_info.operate(io, file)) {
            .SUCCESS => {
                global_progress.rows = @intCast(get_console_info.Data.dwWindowSize.Y);
                global_progress.cols = @intCast(get_console_info.Data.dwWindowSize.X);
            },
            else => {
                std.log.debug("failed to determine terminal size; using conservative guess 80x25", .{});
                global_progress.rows = 25;
                global_progress.cols = 80;
            },
        }
    } else {
        var winsize: posix.winsize = .{
            .row = 0,
            .col = 0,
            .xpixel = 0,
            .ypixel = 0,
        };

        const err = (try io.operate(.{ .device_io_control = .{
            .file = file,
            .code = posix.T.IOCGWINSZ,
            .arg = &winsize,
        } })).device_io_control;

        if (err >= 0) {
            global_progress.rows = winsize.row;
            global_progress.cols = winsize.col;
        } else {
            std.log.debug("failed to determine terminal size; using conservative guess 80x25", .{});
            global_progress.rows = 25;
            global_progress.cols = 80;
        }
    }
}

fn handleSigWinch(sig: posix.SIG, info: *const posix.siginfo_t, ctx_ptr: ?*anyopaque) callconv(.c) void {
    _ = info;
    _ = ctx_ptr;
    assert(sig == .WINCH);
    global_progress.redraw_event.set(global_progress.io);
}

const have_sigwinch = switch (builtin.os.tag) {
    .linux,
    .plan9,
    .illumos,
    .netbsd,
    .openbsd,
    .haiku,
    .driverkit,
    .ios,
    .maccatalyst,
    .macos,
    .tvos,
    .visionos,
    .watchos,
    .dragonfly,
    .freebsd,
    .serenity,
    => true,

    else => false,
};

fn copyAtomicStore(dest: []align(@alignOf(usize)) u8, src: []const u8) void {
    assert(dest.len == src.len);
    const chunked_len = dest.len / @sizeOf(usize);
    const dest_chunked: []usize = @as([*]usize, @ptrCast(dest))[0..chunked_len];
    const src_chunked: []align(1) const usize = @as([*]align(1) const usize, @ptrCast(src))[0..chunked_len];
    for (dest_chunked, src_chunked) |*d, s| {
        @atomicStore(usize, d, s, .monotonic);
    }
    const remainder_start = chunked_len * @sizeOf(usize);
    for (dest[remainder_start..], src[remainder_start..]) |*d, s| {
        @atomicStore(u8, d, s, .monotonic);
    }
}

fn copyAtomicLoad(
    dest: *align(@alignOf(usize)) [Node.max_name_len]u8,
    src: *align(@alignOf(usize)) const [Node.max_name_len]u8,
) void {
    const chunked_len = @divExact(dest.len, @sizeOf(usize));
    const dest_chunked: *[chunked_len]usize = @ptrCast(dest);
    const src_chunked: *const [chunked_len]usize = @ptrCast(src);
    for (dest_chunked, src_chunked) |*d, *s| {
        d.* = @atomicLoad(usize, s, .monotonic);
    }
}