字段
vtable: *const VTable
buffer: []u8若长度为零,则写入器不带缓冲,且 flush 为空操作。
end: usize = 0buffer 中此位置之前是已缓冲的字节,之后是 undefined。
Writerbuiltinnative_endianstdassertLimitFiletestingAllocatorArrayListVTableErrorFileAllErrorFileReadingErrorFileErrorfixedhashedfailingbufferedcountSplatcountSendFileLowerBoundwriteVecwriteSplatwriteSplatHeaderwriteSplatHeaderLimitwriteSplatHeaderLimitFinishSplatHeaderTestCasetestWriteSplatHeaderLimitflushdefaultFlushnoopFlushrebasedefaultRebaseunusedCapacitySliceunusedCapacityLenwritableArraywritableSlicewritableSliceGreedywritableSliceGreedyPreservewritableSlicePreserveensureUnusedCapacityundoadvancewriteVecAllwriteSplatAllwritewriteAllprintwriteBytewriteBytePreservesplatByteAllsplatBytePreservesplatBytesplatBytesAllsplatByteswriteIntwriteStructwriteSliceEndianwriteSliceSwapsendFilesendFileHeadersendFileReadingsendFileAllsendFileReadingAllalignBufferalignBufferOptionsprintAddressprintValueoptionsForbiddenprintErrorSetprintEnumExhaustiveprintEnumNonexhaustiveprintStringEscapedprintVectorprintArrayprintIntprintIntAnyprintAsciiCharprintAsciiprintUnicodeCodepointprintFloatprintFloatHexOptionsprintFloatHexByteSizeUnitsprintByteSizeANYstripOptionalOrErrorUnionSpecinvalidFmtErrorprintHexprintBase64writeUleb128writeSleb128writeLeb128testLeb128EncodingSelfTypeformatSelfTypeSelfTypetestPrintIntCasefailingDrainfailingSendFilefailingRebaseDiscardingconsumeconsumeAllunimplementedSendFilefixedDrainunreachableDrainunreachableRebasefromArrayListtoArrayListHashedHashingAllocatingtestSplatBytePreserve
std.Io.Writer.advance
函数
调用 writableSliceGreedy 后,此函数跟踪实际写入的字节数。
使用 writableSlice 或 writableArray 时无需调用。
pub fn advance(w: *Writer, n: usize) void
参数
w: *Writer
n: usize
std.Io.Writer.alignBuffer
函数
pub fn alignBuffer( w: *Writer, buffer: []const u8, width: usize, alignment: std.fmt.Alignment, fill: u8, ) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.alignBufferOptions
函数
pub fn alignBufferOptions(w: *Writer, buffer: []const u8, options: std.fmt.Options) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.Allocating
容器
维护 Writer 状态,使其写入数组列表的未使用容量,在完全填满后才通过虚函数表调用,触发扩容。
因此,格式化输出等使用 Writer 的相同优化非泛型机器码,在使用此接口时会走热点路径。
使用此接口时,无需调用 flush。
字段
initinitAlignedinitCapacityinitOwnedSliceinitOwnedSliceAlignedfromArrayListfromArrayListAlignedvtabledeinittoArrayListtoArrayListAlignedensureUnusedCapacityensureTotalCapacityensureTotalCapacityPrecisetoOwnedSlicetoOwnedSliceSentinelwrittenshrinkRetainingCapacityclearRetainingCapacitydrainsendFilegrowingRebasetestAllocating
std.Io.Writer.Allocating.clearRetainingCapacity
函数
pub fn clearRetainingCapacity(a: *Allocating) void
参数
a: *Allocating
std.Io.Writer.Allocating.deinit
函数
pub fn deinit(a: *Allocating) void
参数
a: *Allocating
std.Io.Writer.Allocating.drain
函数
fn drain(w: *Writer, data: []const []const u8, splat: usize) Error!usize
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.Allocating.ensureTotalCapacity
函数
pub fn ensureTotalCapacity(a: *Allocating, new_capacity: usize) Allocator.Error!void
参数
a: *Allocating
new_capacity: usize
错误
- OutOfMemory
std.Io.Writer.Allocating.ensureTotalCapacityPrecise
函数
pub fn ensureTotalCapacityPrecise(a: *Allocating, new_capacity: usize) Allocator.Error!void
参数
a: *Allocating
new_capacity: usize
错误
- OutOfMemory
std.Io.Writer.Allocating.ensureUnusedCapacity
函数
pub fn ensureUnusedCapacity(a: *Allocating, additional_count: usize) Allocator.Error!void
参数
a: *Allocating
additional_count: usize
错误
- OutOfMemory
std.Io.Writer.Allocating.fromArrayList
函数
将 array_list 替换为空列表,并取得其内存所有权。
pub fn fromArrayList(allocator: Allocator, array_list: *ArrayList(u8)) Allocating
参数
std.Io.Writer.Allocating.fromArrayListAligned
函数
将 array_list 替换为空列表,并取得其内存所有权。
pub fn fromArrayListAligned( allocator: Allocator, comptime alignment: std.mem.Alignment, array_list: *std.array_list.Aligned(u8, alignment), ) Allocating
参数
std.Io.Writer.Allocating.growingRebase
函数
fn growingRebase(w: *Writer, preserve: usize, minimum_len: usize) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.Allocating.init
函数
pub fn init(allocator: Allocator) Allocating
参数
allocator: Allocator
std.Io.Writer.Allocating.initAligned
函数
pub fn initAligned(allocator: Allocator, alignment: std.mem.Alignment) Allocating
参数
std.Io.Writer.Allocating.initCapacity
函数
pub fn initCapacity(allocator: Allocator, capacity: usize) error{OutOfMemory}!Allocating
参数
allocator: Allocator
capacity: usize
错误
- OutOfMemory
std.Io.Writer.Allocating.initOwnedSlice
函数
pub fn initOwnedSlice(allocator: Allocator, slice: []u8) Allocating
参数
allocator: Allocator
slice: []u8
std.Io.Writer.Allocating.initOwnedSliceAligned
函数
pub fn initOwnedSliceAligned( allocator: Allocator, comptime alignment: std.mem.Alignment, slice: []align(alignment.toByteUnits()) u8, ) Allocating
参数
std.Io.Writer.Allocating.sendFile
函数
fn sendFile(w: *Writer, file_reader: *File.Reader, limit: Limit) FileError!usize
参数
错误
- EndOfStream
已到达正在读取的文件末尾。
- ReadFailed
详细诊断信息位于
File.Reader结构体上。- Unimplemented
表示调用方应自行读取文件;被调用方无法 提供更高效的实现。
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.Allocating.shrinkRetainingCapacity
函数
pub fn shrinkRetainingCapacity(a: *Allocating, new_len: usize) void
参数
a: *Allocating
new_len: usize
std.Io.Writer.Allocating.testAllocating
函数
fn testAllocating(comptime alignment: std.mem.Alignment) !void
参数
std.Io.Writer.Allocating.toArrayList
函数
返回取得已分配内存所有权的数组列表。
将 Allocating 重置为空状态。
pub fn toArrayList(a: *Allocating) ArrayList(u8)
参数
a: *Allocating
std.Io.Writer.Allocating.toArrayListAligned
函数
返回取得已分配内存所有权的数组列表。
将 Allocating 重置为空状态。
pub fn toArrayListAligned( a: *Allocating, comptime alignment: std.mem.Alignment, ) std.array_list.Aligned(u8, alignment)
参数
a: *Allocating
alignment: std.mem.Alignment
std.Io.Writer.Allocating.toOwnedSlice
函数
pub fn toOwnedSlice(a: *Allocating) Allocator.Error![]u8
参数
a: *Allocating
错误
- OutOfMemory
std.Io.Writer.Allocating.toOwnedSliceSentinel
函数
pub fn toOwnedSliceSentinel(a: *Allocating, comptime sentinel: u8) Allocator.Error![:sentinel]u8
参数
a: *Allocating
sentinel: u8
错误
- OutOfMemory
std.Io.Writer.Allocating.vtable
常量
VTable
std.Io.Writer.Allocating.written
函数
pub fn written(a: *Allocating) []u8
参数
a: *Allocating
std.Io.Writer.Allocator
别名
别名目标 std.mem.Allocator
std.Io.Writer.ANY
常量
std.Io.Writer.ArrayList
别名
别名目标 std.ArrayList
std.Io.Writer.assert
别名
别名目标 std.debug.assert
std.Io.Writer.buffered
函数
返回尚未排出的内容。
pub fn buffered(w: *const Writer) []u8
参数
w: *const Writer
std.Io.Writer.builtin
常量
std.Io.Writer.ByteSizeUnits
容器
字段
decimal此格式化器以 1000 的倍数表示数字,使用 SI 计量单位,如 kB、MB、GB 等。
binary此格式化器将数值表示为 1024 的倍数,使用 IEC 计量单位(KiB、MiB、GiB 等)。
std.Io.Writer.consume
函数
通过移动缓冲区内容,从 buffer 移除前 n 字节;
若整个缓冲区已被消费,返回其后仍剩余的字节数,
否则返回零。
可用于 VTable.drain 函数实现,以实现部分
排空。
pub fn consume(w: *Writer, n: usize) usize
参数
w: *Writer
n: usize
std.Io.Writer.consumeAll
函数
将 end 设为零并返回零的快捷操作。
等价于以 end 为参数调用 consume。
pub fn consumeAll(w: *Writer) usize
参数
w: *Writer
std.Io.Writer.countSendFileLowerBound
函数
pub fn countSendFileLowerBound(n: usize, file_reader: *File.Reader, limit: Limit) ?usize
参数
std.Io.Writer.countSplat
函数
pub fn countSplat(data: []const []const u8, splat: usize) usize
参数
data: []const []const u8
splat: usize
std.Io.Writer.defaultFlush
函数
反复调用 VTable.drain,直到 end 为零。
pub fn defaultFlush(w: *Writer) Error!void
参数
w: *Writer
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.defaultRebase
函数
pub fn defaultRebase(w: *Writer, preserve: usize, minimum_len: usize) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.Discarding
容器
字段
count: u64
writer: Writer
std.Io.Writer.Discarding.drain
函数
pub fn drain(w: *Writer, data: []const []const u8, splat: usize) Error!usize
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.Discarding.fullCount
函数
包含缓冲的数据(无需刷新)。
pub fn fullCount(d: *const Discarding) u64
参数
d: *const Discarding
std.Io.Writer.Discarding.init
函数
pub fn init(buffer: []u8) Discarding
参数
buffer: []u8
std.Io.Writer.Discarding.sendFile
函数
pub fn sendFile(w: *Writer, file_reader: *File.Reader, limit: Limit) FileError!usize
参数
错误
- EndOfStream
已到达正在读取的文件末尾。
- ReadFailed
详细诊断信息位于
File.Reader结构体上。- Unimplemented
表示调用方应自行读取文件;被调用方无法 提供更高效的实现。
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.ensureUnusedCapacity
函数
pub fn ensureUnusedCapacity(w: *Writer, n: usize) Error!void
参数
w: *Writer
n: usize
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.Error
错误集合
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.failing
常量
Writer
std.Io.Writer.failingDrain
函数
pub fn failingDrain(w: *Writer, data: []const []const u8, splat: usize) Error!usize
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.failingRebase
函数
pub fn failingRebase(w: *Writer, preserve: usize, capacity: usize) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.failingSendFile
函数
pub fn failingSendFile(w: *Writer, file_reader: *File.Reader, limit: Limit) FileError!usize
参数
错误
- EndOfStream
已到达正在读取的文件末尾。
- ReadFailed
详细诊断信息位于
File.Reader结构体上。- Unimplemented
表示调用方应自行读取文件;被调用方无法 提供更高效的实现。
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.File
别名
别名目标 std.Io.File
std.Io.Writer.FileAllError
错误集合
错误
- ReadFailed
详细诊断信息位于
File.Reader结构体上。- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.FileError
错误集合
错误
- EndOfStream
已到达正在读取的文件末尾。
- ReadFailed
详细诊断信息位于
File.Reader结构体上。- Unimplemented
表示调用方应自行读取文件;被调用方无法 提供更高效的实现。
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.FileReadingError
错误集合
错误
- EndOfStream
已到达正在读取的文件末尾。
- ReadFailed
详细诊断信息位于
File.Reader结构体上。- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.fixed
函数
写入 buffer,并在其写满时返回 error.WriteFailed。
pub fn fixed(buffer: []u8) Writer
参数
buffer: []u8
用法示例
test fixed {
{
var buf: [255]u8 = undefined;
var w: Writer = .fixed(&buf);
try w.print("{s}{s}!", .{ "Hello", "World" });
try testing.expectEqualStrings("HelloWorld!", w.buffered());
}
comptime {
var buf: [255]u8 = undefined;
var w: Writer = .fixed(&buf);
try w.print("{s}{s}!", .{ "Hello", "World" });
try testing.expectEqualStrings("HelloWorld!", w.buffered());
}
}
std.Io.Writer.fixedDrain
函数
调用此函数通常意味着缓冲区已满,因此
应当返回错误。但仍需确保所有
可用缓冲区都已填满。此外,也可能从 flush 调用此函数,
此时应成功返回。
pub fn fixedDrain(w: *Writer, data: []const []const u8, splat: usize) Error!usize
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.flush
函数
排空所有剩余的缓冲数据。
pub fn flush(w: *Writer) Error!void
参数
w: *Writer
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.format
函数
pub fn format(self: SelfType, w: *Writer) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.fromArrayList
函数
pub fn fromArrayList(array_list: *ArrayList(u8)) Writer
参数
array_list: *ArrayList(u8)
std.Io.Writer.hashed
函数
pub fn hashed(w: *Writer, hasher: anytype, buffer: []u8) Hashed(@TypeOf(hasher))
参数
w: *Writer
buffer: []u8
std.Io.Writer.Hashed
类型函数
提供基于调用 Hasher.update 的 Writer 实现,同时将
所有数据发送到底层 Writer。
使用时,底层写入器最好不设缓冲,因为所有 写入都会直接转发给它。
由于实现需要通用性,其缓冲策略 并非最优。更好的方案是为每个哈希函数 创建写入器,使重复写入缓冲区能够针对哈希实现的 细节定制。
可与终结流处理管线的 Hashing 对照。
pub fn Hashed(comptime Hasher: type) type
参数
Hasher: type
字段
std.Io.Writer.Hashed.drain
函数
fn drain(w: *Writer, data: []const []const u8, splat: usize) Error!usize
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.Hashed.init
函数
pub fn init(out: *Writer, buffer: []u8) @This()
参数
out: *Writer
buffer: []u8
std.Io.Writer.Hashed.initHasher
函数
pub fn initHasher(out: *Writer, hasher: Hasher, buffer: []u8) @This()
参数
std.Io.Writer.Hashing
类型函数
提供 Writer 实现,基于调用 Hasher.update,并丢弃全部数据。
由于采用通用实现,此实现的缓冲决策并非最优。更好的方案是为每个哈希函数单独创建写入器,使重复写入缓冲区能够根据哈希实现细节调整。
已写入的总字节数保存在 hasher 中。
对比 Hashed,后者还会将数据传给底层流。
pub fn Hashing(comptime Hasher: type) type
参数
Hasher: type
字段
hasher: Hasher
writer: Writer
std.Io.Writer.Hashing.drain
函数
fn drain(w: *Writer, data: []const []const u8, splat: usize) Error!usize
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.Hashing.init
函数
pub fn init(buffer: []u8) @This()
参数
buffer: []u8
std.Io.Writer.Hashing.initHasher
函数
pub fn initHasher(hasher: Hasher, buffer: []u8) @This()
参数
hasher: Hasher
buffer: []u8
std.Io.Writer.invalidFmtError
函数
pub fn invalidFmtError(comptime fmt: []const u8, value: anytype) noreturn
参数
fmt: []const u8
std.Io.Writer.Limit
别名
别名目标 std.Io.Limit
std.Io.Writer.native_endian
常量
std.Io.Writer.noopFlush
函数
不执行任何操作。
pub fn noopFlush(w: *Writer) Error!void
参数
w: *Writer
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.optionsForbidden
函数
fn optionsForbidden(options: std.fmt.Options) void
参数
std.Io.Writer.print
函数
使用 args 渲染 fmt 字符串,并以字节切片调用 w。
格式字符串必须在编译时已知,可以包含下列形式的占位符:
{[argument][specifier]:[fill][alignment][width].[precision]}
上面每个单词及包围它的方括号表示需要替换的参数:
- argument 是要插入参数的数字索引或字段名称。
- 使用字段名称时,必须用方括号包围字段名(标识符),例如
{[score]...};数字索引则可以写成{2...}。
- 使用字段名称时,必须用方括号包围字段名(标识符),例如
- specifier 是依赖类型的格式选项,决定如何格式化该类型,详见下文。
- fill 是用于填充格式化数字的单个字节。
- alignment 是三个字节之一:'<'、'^'、'>',分别使数字左对齐、居中、右对齐。
- 并非所有格式说明符都支持对齐。
- 对齐不识别 Unicode,仅适用于原始字节或 ASCII。
- width 是字段总字节数,仅适用于数字格式化。
- precision 指定格式化数字的小数位数。
多数参数可选,可以省略。如果某分隔符之后的所有参数均省略,也可以省略该分隔符(':' 和 '.')。
fill 是例外:如果指定 width 的同时需要非零 fill 字符,就必须提供 alignment,否则 ':' 后面的数字会被解释为 width。
specifier 支持:
- "x" 和 "X":数值的十六进制表示,或字符串的十六进制字节表示
- "s":
- 对 u8 多项指针和 C 指针,按照null 结尾的 C 字符串打印
- 对 u8 切片,将整个切片作为字符串打印,不使用null 结尾
- "t":
- 对枚举和标记联合,打印标记名称
- 对错误集合,打印错误名称
- "b64":将字符串打印为标准 base64
- "e":以科学记数法表示浮点值
- "d":数值的十进制表示
- "b":整数的二进制表示
- "o":整数的八进制表示
- "c":将整数作为 ASCII 字符打印,整数类型最多八位
- "u":将整数作为 UTF-8 序列打印,整数类型最多二十一位
- "B":以 SI 单位(十进制)表示字节数
- "Bi":以 IEC 单位(二进制)表示字节数
- "?":将可选值表示为解包后的值或
null,后面可以跟底层值的格式说明符 - "!":将错误联合表示为解包后的值或格式化错误值,后面可以跟底层值的格式说明符
- "*":打印值的地址而非值本身
- "any":使用默认格式打印任意类型的值
- "f":委托给类型的
format方法,传入*Writer,预期返回Error!void - "q":打印为使用双引号转义的字符串。双引号内的内容保持不变,以下转换除外:
- 转义:'\n'、'\r'、'\t'、'\'、'"'
- 十六进制编码:ASCII 控制字符、无效 UTF-8 序列、非 ASCII 行结束符(U+0085、U+2028、U+2029)、字节顺序标记(U+FEFF)
- "qf":委托给类型的
format方法,同时进行双引号转义
格式字符串中的字面花括号可以通过重复花括号转义,例如 "{{" 或 "}}"。
pub fn print(w: *Writer, comptime fmt: []const u8, args: anytype) Error!void
参数
w: *Writer
fmt: []const u8
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.printAddress
函数
pub fn printAddress(w: *Writer, value: anytype) Error!void
参数
w: *Writer
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.printArray
函数
pub fn printArray( w: *Writer, comptime fmt: []const u8, options: std.fmt.Options, ptr_to_array: anytype, max_depth: usize, ) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.printAscii
函数
pub fn printAscii(w: *Writer, bytes: []const u8, options: std.fmt.Options) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.printAsciiChar
函数
pub fn printAsciiChar(w: *Writer, c: u8, options: std.fmt.Options) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.printBase64
函数
pub fn printBase64(w: *Writer, bytes: []const u8) Error!void
参数
w: *Writer
bytes: []const u8
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.printByteSize
函数
当 value 小于 1kB 时,忽略格式选项 precision
pub fn printByteSize( w: *Writer, value: u64, comptime units: ByteSizeUnits, options: std.fmt.Options, ) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
用法示例
test printByteSize {
try testing.expectFmt("file size: 42B\n", "file size: {B}\n", .{42});
try testing.expectFmt("file size: 42B\n", "file size: {Bi}\n", .{42});
try testing.expectFmt("file size: 63MB\n", "file size: {B}\n", .{63 * 1000 * 1000});
try testing.expectFmt("file size: 63MiB\n", "file size: {Bi}\n", .{63 * 1024 * 1024});
try testing.expectFmt("file size: 42B\n", "file size: {B:.2}\n", .{42});
try testing.expectFmt("file size: 42B\n", "file size: {B:>9.2}\n", .{42});
try testing.expectFmt("file size: 66.06MB\n", "file size: {B:.2}\n", .{63 * 1024 * 1024});
try testing.expectFmt("file size: 60.08MiB\n", "file size: {Bi:.2}\n", .{63 * 1000 * 1000});
try testing.expectFmt("file size: =66.06MB=\n", "file size: {B:=^9.2}\n", .{63 * 1024 * 1024});
try testing.expectFmt("file size: 66.06MB\n", "file size: {B: >9.2}\n", .{63 * 1024 * 1024});
try testing.expectFmt("file size: 66.06MB \n", "file size: {B: <9.2}\n", .{63 * 1024 * 1024});
try testing.expectFmt("file size: 0.01844674407370955ZB\n", "file size: {B}\n", .{std.math.maxInt(u64)});
}
std.Io.Writer.printEnumExhaustive
函数
fn printEnumExhaustive(w: *Writer, value: anytype) Error!void
参数
w: *Writer
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.printEnumNonexhaustive
函数
fn printEnumNonexhaustive(w: *Writer, value: anytype) Error!void
参数
w: *Writer
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.printErrorSet
函数
fn printErrorSet(w: *Writer, error_set: anyerror) Error!void
参数
w: *Writer
error_set: anyerror
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.printFloat
函数
使用较大的栈缓冲区;断言模式为十进制或科学计数法。
pub fn printFloat(w: *Writer, value: anytype, options: std.fmt.Number) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.printFloatHex
函数
pub fn printFloatHex(w: *Writer, value: anytype, case: std.fmt.Case, opt_precision: ?usize) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.printFloatHexOptions
函数
使用较小的栈缓冲区;断言模式不是十进制或科学计数法。
pub fn printFloatHexOptions(w: *Writer, value: anytype, options: std.fmt.Number) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.printHex
函数
pub fn printHex(w: *Writer, bytes: []const u8, case: std.fmt.Case) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.printInt
函数
pub inline fn printInt( w: *Writer, value: anytype, base: u8, case: std.fmt.Case, options: std.fmt.Options, ) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
用法示例
test printInt {
try testPrintIntCase("-1", @as(i1, -1), 10, .lower, .{});
try testPrintIntCase("-101111000110000101001110", @as(i32, -12345678), 2, .lower, .{});
try testPrintIntCase("-12345678", @as(i32, -12345678), 10, .lower, .{});
try testPrintIntCase("-bc614e", @as(i32, -12345678), 16, .lower, .{});
try testPrintIntCase("-BC614E", @as(i32, -12345678), 16, .upper, .{});
try testPrintIntCase("12345678", @as(u32, 12345678), 10, .upper, .{});
try testPrintIntCase(" 666", @as(u32, 666), 10, .lower, .{ .width = 6 });
try testPrintIntCase(" 1234", @as(u32, 0x1234), 16, .lower, .{ .width = 6 });
try testPrintIntCase("1234", @as(u32, 0x1234), 16, .lower, .{ .width = 1 });
try testPrintIntCase("+42", @as(i32, 42), 10, .lower, .{ .width = 3 });
try testPrintIntCase("-42", @as(i32, -42), 10, .lower, .{ .width = 3 });
try testPrintIntCase("123456789123456789", @as(comptime_int, 123456789123456789), 10, .lower, .{});
}
std.Io.Writer.printIntAny
函数
通常优先使用 printInt,以避免泛型爆炸。不过,若需要针对特定整数类型生成最优代码,也可使用此函数。
pub fn printIntAny( w: *Writer, value: anytype, base: u8, case: std.fmt.Case, options: std.fmt.Options, ) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.printStringEscaped
函数
输出双引号,再按 Zig 字符串字面量规则转义字符串, 最后输出双引号。
pub fn printStringEscaped(w: *Writer, bytes: []const u8) Error!void
参数
w: *Writer
bytes: []const u8
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.printUnicodeCodepoint
函数
pub fn printUnicodeCodepoint(w: *Writer, c: u21) Error!void
参数
w: *Writer
c: u21
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.printValue
函数
若 value 为联合体,断言 buffer 的容量至少为 2。
pub fn printValue( w: *Writer, comptime fmt: []const u8, options: std.fmt.Options, value: anytype, max_depth: usize, ) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.printVector
函数
pub fn printVector( w: *Writer, comptime fmt: []const u8, options: std.fmt.Options, value: anytype, max_depth: usize, ) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.rebase
函数
pub fn rebase(w: *Writer, preserve: usize, unused_capacity_len: usize) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.SelfType
别名
别名目标 std.Io.Writer
std.Io.Writer.SelfType
别名
别名目标 std.Io.Writer
std.Io.Writer.SelfType
别名
别名目标 std.Io.Writer
std.Io.Writer.sendFile
函数
与 writeSplat 和 writeVec 不同,即使缓冲区容量
足以容纳文件内容,此函数仍会调用 VTable。
调用方负责刷新缓冲区。虽然实现可能通过绕过缓冲区 进行优化,但不保证如此。
虽然在这种情况下可以直接读入缓冲区,
从而从错误集合中移除 error.Unimplemented,但这里没有
这样做,因为在调用栈更高层处理效率更高,
可避免每次写入都遇到此错误。
另一种错误集合中不含 error.Unimplemented
的方案,参见 sendFileReading。
pub fn sendFile(w: *Writer, file_reader: *File.Reader, limit: Limit) FileError!usize
参数
错误
- EndOfStream
已到达正在读取的文件末尾。
- ReadFailed
详细诊断信息位于
File.Reader结构体上。- Unimplemented
表示调用方应自行读取文件;被调用方无法 提供更高效的实现。
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.sendFileAll
函数
返回逻辑写入的字节数,不包括 buffer 中的字节,因为这些字节此前已完成逻辑写入。
调用者负责刷新。尽管可能作为优化绕过缓冲区,但并不保证如此。
断言缓冲区容量非零。
pub fn sendFileAll(w: *Writer, file_reader: *File.Reader, limit: Limit) FileAllError!usize
参数
错误
- ReadFailed
详细诊断信息位于
File.Reader结构体上。- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.sendFileHeader
函数
返回从 header 和 file_reader 消费的字节数。
limit 仅适用于 file_reader。
pub fn sendFileHeader( w: *Writer, header: []const u8, file_reader: *File.Reader, limit: Limit, ) FileError!usize
参数
错误
- EndOfStream
已到达正在读取的文件末尾。
- ReadFailed
详细诊断信息位于
File.Reader结构体上。- Unimplemented
表示调用方应自行读取文件;被调用方无法 提供更高效的实现。
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.sendFileReading
函数
断言缓冲区容量及 limit 均不为零。
pub fn sendFileReading(w: *Writer, file_reader: *File.Reader, limit: Limit) FileReadingError!usize
参数
错误
- EndOfStream
已到达正在读取的文件末尾。
- ReadFailed
详细诊断信息位于
File.Reader结构体上。- WriteFailed
详细诊断信息见
Writer实现。
用法示例
test sendFileReading {
const io = testing.io;
var tmp_dir = testing.tmpDir(.{});
defer tmp_dir.cleanup();
const file = try tmp_dir.dir.createFile(io, "input.txt", .{ .read = true });
defer file.close(io);
var r_buffer: [2]u8 = undefined;
var file_writer: File.Writer = .init(file, io, &r_buffer);
try file_writer.interface.writeAll("abcd");
try file_writer.interface.flush();
var file_reader = file_writer.moveToReader();
try file_reader.seekTo(0);
try file_reader.interface.fill(2);
var w_buffer: [1]u8 = undefined;
var discarding: Writer.Discarding = .init(&w_buffer);
try testing.expectEqual(4, discarding.writer.sendFileReadingAll(&file_reader, .unlimited));
}
std.Io.Writer.sendFileReadingAll
函数
等价于 sendFileAll,但使用直接的 pread 和 read 调用读取 file,而非使用 sendFile。
通常用于底层实现返回 error.Unimplemented 时的后备方案,因此该错误码不出现在此函数的错误集合中。
断言缓冲区容量非零。
pub fn sendFileReadingAll(w: *Writer, file_reader: *File.Reader, limit: Limit) FileAllError!usize
参数
错误
- ReadFailed
详细诊断信息位于
File.Reader结构体上。- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.splatByte
函数
多次写入同一个字节,允许短写。
底层 VTable.drain 最多调用一次。
pub fn splatByte(w: *Writer, byte: u8, n: usize) Error!usize
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.splatByteAll
函数
多次写入同一字节,按需多次 执行底层写入调用。
pub fn splatByteAll(w: *Writer, byte: u8, n: usize) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
用法示例
test splatByteAll {
var aw: Writer.Allocating = .init(testing.allocator);
defer aw.deinit();
try aw.writer.splatByteAll('7', 45);
try testing.expectEqualStrings(&@as([45]u8, @splat('7')), aw.writer.buffered());
}
std.Io.Writer.splatBytePreserve
函数
多次写入同一字节,按需多次 执行底层写入调用。
成功时,只要已缓冲字节足够,
就至少保留 preserve 个字节在缓冲区中。
只有调用前的 w.end + n 小于 preserve 时,
调用后写入器缓冲的字节数才可能少于 preserve。
有意保留的字节包括此前已缓冲字节中的至多 preserve -| n 个,
以及新写入字节中的 @min(n, preserve_len) 个。
断言缓冲区容量至少为 preserve。
n 可以大于缓冲区容量。
pub fn splatBytePreserve(w: *Writer, preserve: usize, byte: u8, n: usize) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
用法示例
test splatBytePreserve {
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 5, .splat_len = 5 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 9, .preserve = 5, .splat_len = 2 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 5, .splat_len = 6 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 6, .splat_len = 6 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 5, .splat_len = 10 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 6, .splat_len = 10 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 6, .splat_len = 11 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 6, .splat_len = 80 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 6, .splat_len = 85 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 10, .splat_len = 6 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 10, .splat_len = 11 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 10, .splat_len = 80 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 10, .splat_len = 85 });
}
std.Io.Writer.splatBytes
函数
多次写入同一个切片,允许短写。
底层 VTable.drain 最多调用一次。
pub fn splatBytes(w: *Writer, bytes: []const u8, n: usize) Error!usize
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.splatBytesAll
函数
多次写入同一切片,按需多次 执行底层写入调用。
pub fn splatBytesAll(w: *Writer, bytes: []const u8, splat: usize) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
用法示例
test splatBytesAll {
var aw: Writer.Allocating = .init(testing.allocator);
defer aw.deinit();
try aw.writer.splatBytesAll("hello", 3);
try testing.expectEqualStrings("hellohellohello", aw.writer.buffered());
}
std.Io.Writer.SplatHeaderTestCase
容器
字段
writer_type: enum { fixed, allocating }
buf_len: usize = 100writer_type 为 .fixed 时,决定缓冲区大小。 writer_type 为 .allocating 时,决定初始容量。
header: []const u8
data: []const []const u8
splat: u8
limit: u8
expected_res: union(enum) { written: usize, write_failed }
expected_buf_content: []const u8
std.Io.Writer.std
别名
别名目标 std
std.Io.Writer.stripOptionalOrErrorUnionSpec
函数
fn stripOptionalOrErrorUnionSpec(comptime fmt: []const u8) []const u8
参数
fmt: []const u8
std.Io.Writer.testing
别名
别名目标 std.testing
std.Io.Writer.testLeb128Encoding
函数
fn testLeb128Encoding(comptime T: type, value: T, encoding: []const u8) !void
参数
T: type
value: T
encoding: []const u8
std.Io.Writer.testPrintIntCase
函数
fn testPrintIntCase(expected: []const u8, value: anytype, base: u8, case: std.fmt.Case, options: std.fmt.Options) !void
参数
std.Io.Writer.testSplatBytePreserve
函数
fn testSplatBytePreserve(options: struct { buf_len: u4, fill_len: u4, preserve: u4, splat_len: u8 }) !void
参数
options: struct { buf_len: u4, fill_len: u4, preserve: u4, splat_len: u8 }
std.Io.Writer.testWriteSplatHeaderLimit
函数
fn testWriteSplatHeaderLimit(comptime test_case: SplatHeaderTestCase) !void
参数
test_case: SplatHeaderTestCase
std.Io.Writer.toArrayList
函数
pub fn toArrayList(w: *Writer) ArrayList(u8)
参数
w: *Writer
std.Io.Writer.undo
函数
pub fn undo(w: *Writer, n: usize) void
参数
w: *Writer
n: usize
std.Io.Writer.unimplementedSendFile
函数
当 Writer 实现无法提供比对文件执行基本
读写循环更高效的实现时使用。
pub fn unimplementedSendFile(w: *Writer, file_reader: *File.Reader, limit: Limit) FileError!usize
参数
错误
- EndOfStream
已到达正在读取的文件末尾。
- ReadFailed
详细诊断信息位于
File.Reader结构体上。- Unimplemented
表示调用方应自行读取文件;被调用方无法 提供更高效的实现。
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.unreachableDrain
函数
pub fn unreachableDrain(w: *Writer, data: []const []const u8, splat: usize) Error!usize
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.unreachableRebase
函数
pub fn unreachableRebase(w: *Writer, preserve: usize, capacity: usize) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.unusedCapacityLen
函数
pub fn unusedCapacityLen(w: *const Writer) usize
参数
w: *const Writer
std.Io.Writer.unusedCapacitySlice
函数
pub fn unusedCapacitySlice(w: *const Writer) []u8
参数
w: *const Writer
std.Io.Writer.VTable
容器
字段
drain: *const fn (w: *Writer, data: []const []const u8, splat: usize) Error!usize向逻辑接收端发送字节。仅当待写入数据
无法容纳于 buffer,或执行 flush 操作时,才会调用此处。
先消耗 buffer[0..end],再按顺序消耗 data 的
各个切片。data 的元素可以互相别名,但不得与
buffer 别名。
此函数以实现定义的方式修改 Writer.end 和 Writer.buffer。
data.len 必须非零。
data 的最后一个元素会根据需要重复,
使其被写入 splat 次,该次数可以为零。
如果待写入数据本来可以保存在 buffer 中,
则不得调用此函数;待写入数据量
和缓冲区容量均为零的情况也包括在内。
返回从 data 消耗的字节数,不包括来自
buffer 的字节。
返回的字节数可以为零,这并不表示流
结束。后续调用可能返回非零值,也可能通过
error.WriteFailed 表示流结束。
sendFile: *const fn (
w: *Writer,
file_reader: *File.Reader,
/// 从文件读取的最大字节数。实现可以
/// 假定文件大小不超过此值。来自
/// `buffer` 的数据不计入此限制。
limit: Limit,
) FileError!usize = unimplementedSendFile将已打开文件的内容复制到逻辑输出端。先消耗 buffer[0..end],再消耗 limit 字节,来源为 file_reader。
返回逻辑写入的字节数。其中不包括 buffer 中的字节,因为这些字节此前已完成逻辑写入。从 buffer 消耗的字节数量通过修改 end 跟踪。
返回的字节数可能为零,这不表示流已结束。后续调用可能返回非零值,或通过 error.WriteFailed 表示流结束。调用者可以检查 file_reader 状态(File.Reader.atEnd),区分零长度读取或写入与文件结束。
error.Unimplemented 表示被调用方无法提供比调用者自行读取更高效的实现。
flush: *const fn (w: *Writer) Error!void = defaultFlush消费缓冲区中的全部剩余内容。
默认刷新实现会反复调用 drain,直到 end 为
零,但实现也可以合法地以其他方式管理 end。
例如,Allocating 的刷新是空操作。
rebase: *const fn (w: *Writer, preserve: usize, capacity: usize) Error!void = defaultRebase确保无需重新定位缓冲数据即可再缓冲 capacity 字节。
最近的 preserve 字节必须继续保留在缓冲区中。
仅当 buffer 的未用容量无法容纳 capacity 字节时调用。
std.Io.Writer.writableArray
函数
断言所提供缓冲区总容量足以容纳 len。
将缓冲区结束位置推进 len。
pub fn writableArray(w: *Writer, comptime len: usize) Error!*[len]u8
参数
w: *Writer
len: usize
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.writableSlice
函数
断言所提供缓冲区总容量足以容纳 len。
将缓冲区结束位置推进 len。
pub fn writableSlice(w: *Writer, len: usize) Error![]u8
参数
w: *Writer
len: usize
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.writableSliceGreedy
函数
pub fn writableSliceGreedy(w: *Writer, minimum_len: usize) Error![]u8
参数
w: *Writer
minimum_len: usize
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.writableSliceGreedyPreserve
函数
断言提供的缓冲区总容量足以容纳 minimum_len
与 preserve 之和。
不会 advance 缓冲区结束位置。
排空缓冲区时,确保至少保留 preserve 个字节
在缓冲区中。
如果 preserve 为零,等同于 writableSliceGreedy。
pub fn writableSliceGreedyPreserve(w: *Writer, preserve: usize, minimum_len: usize) Error![]u8
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.writableSlicePreserve
函数
断言提供的缓冲区总容量足以容纳 len
与 preserve 之和。
将缓冲区结束位置推进 len。
排空缓冲区时,确保至少保留 preserve 个字节
在缓冲区中。
如果 preserve 为零,等同于 writableSlice。
pub fn writableSlicePreserve(w: *Writer, preserve: usize, len: usize) Error![]u8
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.write
函数
将 bytes 传输到流,至多调用一次 drain。
返回已传输字节数,可能小于 bytes.len,也可能为零。
返回值小于 bytes.len 不表示失败;后续调用可能返回非零值,或者因 error.WriteFailed 失败。
另见:
pub fn write(w: *Writer, bytes: []const u8) Error!usize
参数
w: *Writer
bytes: []const u8
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.writeAll
函数
pub fn writeAll(w: *Writer, bytes: []const u8) Error!void
参数
w: *Writer
bytes: []const u8
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.writeByte
函数
按需反复调用 drain,直到 byte 已传输。
pub fn writeByte(w: *Writer, byte: u8) Error!void
参数
w: *Writer
byte: u8
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.writeBytePreserve
函数
成功时,若已有足够缓冲字节,则至少保留 preserve 字节在缓冲区中。
调用后写入器缓冲的字节数,仅在以下条件下才可能小于 preserve:调用前 w.end + 1 小于 preserve。
有意保留的字节包括此前缓冲数据中最多 preserve -| 1 字节,以及新写入的字节。
断言缓冲区容量至少为 preserve。
pub fn writeBytePreserve(w: *Writer, preserve: usize, byte: u8) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.writeInt
函数
断言 buffer 初始化时容量至少为 @sizeOf(T) 字节。
pub inline fn writeInt(w: *Writer, comptime T: type, value: T, endian: std.lang.Endian) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.writeLeb128
函数
将单个整数以 LEB128 写入给定写入器。
pub fn writeLeb128(w: *Writer, value: anytype) Error!void
参数
w: *Writer
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.Writer
别名
别名目标 std.Io.Writer
std.Io.Writer.writeSleb128
函数
将单个有符号整数以 LEB128 写入给定写入器。
pub fn writeSleb128(w: *Writer, value: anytype) Error!void
参数
w: *Writer
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.writeSliceEndian
函数
pub inline fn writeSliceEndian( w: *Writer, Elem: type, slice: []const Elem, endian: std.lang.Endian, ) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
用法示例
test writeSliceEndian {
var buffer: [5]u8 align(2) = undefined;
var w: Writer = .fixed(&buffer);
try w.writeByte('x');
const array: [2]u16 = .{ 0x1234, 0x5678 };
try writeSliceEndian(&w, u16, &array, .big);
try testing.expectEqualSlices(u8, &.{ 'x', 0x12, 0x34, 0x56, 0x78 }, &buffer);
}
std.Io.Writer.writeSliceSwap
函数
pub fn writeSliceSwap(w: *Writer, Elem: type, slice: []const Elem) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.writeSplat
函数
若根据 data 和 splat 计算出的待写字节数可容纳于
unusedCapacitySlice,则保证此函数不会失败,不会调用
VTable,并返回完整字节数。
pub fn writeSplat(w: *Writer, data: []const []const u8, splat: usize) Error!usize
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.writeSplatAll
函数
data 参数可变,因为此函数需要修改其中字段,
以处理 VTable.writeSplat 的部分写入。
返回之前,data 将恢复为原始状态。
pub fn writeSplatAll(w: *Writer, data: [][]const u8, splat: usize) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
用法示例
test writeSplatAll {
var aw: Writer.Allocating = .init(testing.allocator);
defer aw.deinit();
var buffers = [_][]const u8{ "ba", "na" };
try aw.writer.writeSplatAll(&buffers, 2);
try testing.expectEqualStrings("banana", aw.writer.buffered());
}
std.Io.Writer.writeSplatHeader
函数
返回从 header 和 data 消费的字节数。
pub fn writeSplatHeader( w: *Writer, header: []const u8, data: []const []const u8, splat: usize, ) Error!usize
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.writeSplatHeaderLimit
函数
等价于 writeSplatHeader,但最多写入 limit 字节。
pub fn writeSplatHeaderLimit( w: *Writer, header: []const u8, data: []const []const u8, splat: usize, limit: Limit, ) Error!usize
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.writeSplatHeaderLimitFinish
函数
fn writeSplatHeaderLimitFinish( w: *Writer, header: []const u8, data: []const []const u8, splat: usize, limit: usize, ) Error!usize
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.writeStruct
函数
函数采用内联,以便在 endian 在编译期已知且
与宿主端序相同时,避免生成无用代码。
pub inline fn writeStruct(w: *Writer, value: anytype, endian: std.lang.Endian) Error!void
参数
错误
- WriteFailed
详细诊断信息见
Writer实现。
用法示例
test writeStruct {
var buffer: [16]u8 = undefined;
const S = extern struct { a: u64, b: u32, c: u32 };
const s: S = .{ .a = 1, .b = 2, .c = 3 };
{
var w: Writer = .fixed(&buffer);
try w.writeStruct(s, .little);
try testing.expectEqualSlices(u8, &.{
1, 0, 0, 0, 0, 0, 0, 0, //
2, 0, 0, 0, //
3, 0, 0, 0, //
}, &buffer);
}
{
var w: Writer = .fixed(&buffer);
try w.writeStruct(s, .big);
try testing.expectEqualSlices(u8, &.{
0, 0, 0, 0, 0, 0, 0, 1, //
0, 0, 0, 2, //
0, 0, 0, 3, //
}, &buffer);
}
}
std.Io.Writer.writeUleb128
函数
以 LEB128 格式向指定写入器写入一个无符号整数。
pub fn writeUleb128(w: *Writer, value: anytype) Error!void
参数
w: *Writer
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.writeVec
函数
若 data 的总字节数可容纳于 unusedCapacitySlice,
则保证此函数不会失败,不会调用 VTable,并返回
data 中的总字节数。
pub fn writeVec(w: *Writer, data: []const []const u8) Error!usize
参数
w: *Writer
data: []const []const u8
错误
- WriteFailed
详细诊断信息见
Writer实现。
std.Io.Writer.writeVecAll
函数
data 参数可变,因为此函数需要修改其
字段,以处理 VTable.writeSplat 的部分写入。
pub fn writeVecAll(w: *Writer, data: [][]const u8) Error!void
参数
w: *Writer
data: [][]const u8
错误
- WriteFailed
详细诊断信息见
Writer实现。
源码
std/Io/Writer.zig
const Writer = @This();
const builtin = @import("builtin");
const native_endian = builtin.target.cpu.arch.endian();
const std = @import("../std.zig");
const assert = std.debug.assert;
const Limit = std.Io.Limit;
const File = std.Io.File;
const testing = std.testing;
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
vtable: *const VTable,
/// 若长度为零,则写入器不带缓冲,且 `flush` 为空操作。
buffer: []u8,
/// `buffer` 中此位置之前是已缓冲的字节,之后是 `undefined`。
end: usize = 0,
pub const VTable = struct {
/// 向逻辑接收端发送字节。仅当待写入数据
/// 无法容纳于 `buffer`,或执行 `flush` 操作时,才会调用此处。
///
/// 先消耗 `buffer[0..end]`,再按顺序消耗 `data` 的
/// 各个切片。`data` 的元素可以互相别名,但不得与
/// `buffer` 别名。
///
/// 此函数以实现定义的方式修改 `Writer.end` 和 `Writer.buffer`。
///
/// `data.len` 必须非零。
///
/// `data` 的最后一个元素会根据需要重复,
/// 使其被写入 `splat` 次,该次数可以为零。
///
/// 如果待写入数据本来可以保存在 `buffer` 中,
/// 则不得调用此函数;待写入数据量
/// 和缓冲区容量均为零的情况也包括在内。
///
/// 返回从 `data` 消耗的字节数,不包括来自
/// `buffer` 的字节。
///
/// 返回的字节数可以为零,这并不表示流
/// 结束。后续调用可能返回非零值,也可能通过
/// `error.WriteFailed` 表示流结束。
///
drain: *const fn (w: *Writer, data: []const []const u8, splat: usize) Error!usize,
/// 将已打开文件的内容复制到逻辑输出端。先消耗 `buffer[0..end]`,再消耗 `limit` 字节,来源为 `file_reader`。
///
/// 返回逻辑写入的字节数。其中不包括 `buffer` 中的字节,因为这些字节此前已完成逻辑写入。从 `buffer` 消耗的字节数量通过修改 `end` 跟踪。
///
/// 返回的字节数可能为零,这不表示流已结束。后续调用可能返回非零值,或通过 `error.WriteFailed` 表示流结束。调用者可以检查 `file_reader` 状态(`File.Reader.atEnd`),区分零长度读取或写入与文件结束。
///
/// `error.Unimplemented` 表示被调用方无法提供比调用者自行读取更高效的实现。
///
///
///
///
///
///
///
///
sendFile: *const fn (
w: *Writer,
file_reader: *File.Reader,
/// 从文件读取的最大字节数。实现可以
/// 假定文件大小不超过此值。来自
/// `buffer` 的数据不计入此限制。
limit: Limit,
) FileError!usize = unimplementedSendFile,
/// 消费缓冲区中的全部剩余内容。
///
/// 默认刷新实现会反复调用 drain,直到 `end` 为
/// 零,但实现也可以合法地以其他方式管理 `end`。
/// 例如,`Allocating` 的刷新是空操作。
///
/// `flush` 操作之后仍可能继续调用 `drain`
/// 和 `sendFile`。
flush: *const fn (w: *Writer) Error!void = defaultFlush,
/// 确保无需重新定位缓冲数据即可再缓冲 `capacity` 字节。
///
/// 最近的 `preserve` 字节必须继续保留在缓冲区中。
///
/// 仅当 `buffer` 的未用容量无法容纳 `capacity` 字节时调用。
///
rebase: *const fn (w: *Writer, preserve: usize, capacity: usize) Error!void = defaultRebase,
};
pub const Error = error{
/// 详细诊断信息见 `Writer` 实现。
WriteFailed,
};
pub const FileAllError = error{
/// 详细诊断信息位于 `File.Reader` 结构体上。
ReadFailed,
/// 详细诊断信息见 `Writer` 实现。
WriteFailed,
};
pub const FileReadingError = error{
/// 详细诊断信息位于 `File.Reader` 结构体上。
ReadFailed,
/// 详细诊断信息见 `Writer` 实现。
WriteFailed,
/// 已到达正在读取的文件末尾。
EndOfStream,
};
pub const FileError = error{
/// 详细诊断信息位于 `File.Reader` 结构体上。
ReadFailed,
/// 详细诊断信息见 `Writer` 实现。
WriteFailed,
/// 已到达正在读取的文件末尾。
EndOfStream,
/// 表示调用方应自行读取文件;被调用方无法
/// 提供更高效的实现。
Unimplemented,
};
/// 写入 `buffer`,并在其写满时返回 `error.WriteFailed`。
pub fn fixed(buffer: []u8) Writer {
return .{
.vtable = &.{
.drain = fixedDrain,
.flush = noopFlush,
.rebase = failingRebase,
},
.buffer = buffer,
};
}
pub fn hashed(w: *Writer, hasher: anytype, buffer: []u8) Hashed(@TypeOf(hasher)) {
return .initHasher(w, hasher, buffer);
}
pub const failing: Writer = .{
.vtable = &.{
.drain = failingDrain,
.sendFile = failingSendFile,
.rebase = failingRebase,
},
.buffer = &.{},
};
test failing {
var fw: Writer = .failing;
try testing.expectError(error.WriteFailed, fw.writeAll("always fails"));
}
/// 返回尚未排出的内容。
pub fn buffered(w: *const Writer) []u8 {
return w.buffer[0..w.end];
}
pub fn countSplat(data: []const []const u8, splat: usize) usize {
var total: usize = 0;
for (data[0 .. data.len - 1]) |buf| total += buf.len;
total += data[data.len - 1].len * splat;
return total;
}
pub fn countSendFileLowerBound(n: usize, file_reader: *File.Reader, limit: Limit) ?usize {
const total: u64 = @min(@backingInt(limit), file_reader.getSize() catch return null);
return std.math.lossyCast(usize, total + n);
}
/// 若 `data` 的总字节数可容纳于 `unusedCapacitySlice`,
/// 则保证此函数不会失败,不会调用 `VTable`,并返回
/// `data` 中的总字节数。
pub fn writeVec(w: *Writer, data: []const []const u8) Error!usize {
return writeSplat(w, data, 1);
}
/// 若根据 `data` 和 `splat` 计算出的待写字节数可容纳于
/// `unusedCapacitySlice`,则保证此函数不会失败,不会调用
/// `VTable`,并返回完整字节数。
pub fn writeSplat(w: *Writer, data: []const []const u8, splat: usize) Error!usize {
assert(data.len > 0);
const buffer = w.buffer;
const count = countSplat(data, splat);
if (w.end + count > buffer.len) return w.vtable.drain(w, data, splat);
for (data[0 .. data.len - 1]) |bytes| {
@memcpy(buffer[w.end..][0..bytes.len], bytes);
w.end += bytes.len;
}
const pattern = data[data.len - 1];
switch (pattern.len) {
0 => {},
1 => {
@memset(buffer[w.end..][0..splat], pattern[0]);
w.end += splat;
},
else => for (0..splat) |_| {
@memcpy(buffer[w.end..][0..pattern.len], pattern);
w.end += pattern.len;
},
}
return count;
}
/// 返回从 `header` 和 `data` 消费的字节数。
pub fn writeSplatHeader(
w: *Writer,
header: []const u8,
data: []const []const u8,
splat: usize,
) Error!usize {
return writeSplatHeaderLimit(w, header, data, splat, .unlimited);
}
/// 等价于 `writeSplatHeader`,但最多写入 `limit` 字节。
pub fn writeSplatHeaderLimit(
w: *Writer,
header: []const u8,
data: []const []const u8,
splat: usize,
limit: Limit,
) Error!usize {
var remaining = @backingInt(limit);
assert(data.len > 0);
{
const copy_len = @min(header.len, remaining);
if (w.buffer.len - w.end < copy_len) return try writeSplatHeaderLimitFinish(w, header, data, splat, remaining);
@memcpy(w.buffer[w.end..][0..copy_len], header[0..copy_len]);
w.end += copy_len;
remaining -= copy_len;
}
remaining_zero: {
if (remaining == 0) break :remaining_zero;
for (data[0 .. data.len - 1], 0..) |bytes, i| {
const copy_len = @min(bytes.len, remaining);
if (w.buffer.len - w.end < copy_len) {
const n = try writeSplatHeaderLimitFinish(w, &.{}, data[i..], splat, remaining);
return @backingInt(limit) - remaining + n;
}
@memcpy(w.buffer[w.end..][0..copy_len], bytes[0..copy_len]);
w.end += copy_len;
remaining -= copy_len;
}
if (remaining == 0) break :remaining_zero;
const pattern = data[data.len - 1];
for (0..splat) |i| {
const copy_len = @min(pattern.len, remaining);
if (w.buffer.len - w.end < copy_len) {
const remaining_splat = splat - i;
const n = try writeSplatHeaderLimitFinish(w, &.{}, data[data.len - 1 ..][0..1], remaining_splat, remaining);
return @backingInt(limit) - remaining + n;
}
@memcpy(w.buffer[w.end..][0..copy_len], pattern[0..copy_len]);
w.end += copy_len;
remaining -= copy_len;
}
}
return @backingInt(limit) - remaining;
}
fn writeSplatHeaderLimitFinish(
w: *Writer,
header: []const u8,
data: []const []const u8,
splat: usize,
limit: usize,
) Error!usize {
var remaining = limit;
var total: usize = 0;
var vecs: [8][]const u8 = undefined;
var i: usize = 0;
if (header.len != 0) {
const copy_len = @min(header.len, remaining);
vecs[i] = header[0..copy_len];
i += 1;
remaining -= copy_len;
if (remaining == 0) {
return w.vtable.drain(w, (&vecs)[0..i], 1);
}
}
for (data[0 .. data.len - 1]) |buf| {
if (buf.len == 0) continue;
const copy_len = @min(buf.len, remaining);
vecs[i] = buf[0..copy_len];
i += 1;
remaining -= copy_len;
if (remaining == 0) {
return w.vtable.drain(w, (&vecs)[0..i], 1);
}
if (i == vecs.len) {
total += try w.vtable.drain(w, &vecs, 1);
i = 0;
}
}
const pattern = data[data.len - 1];
if (splat == 1 or remaining < pattern.len) {
vecs[i] = pattern[0..@min(remaining, pattern.len)];
i += 1;
total += try w.vtable.drain(w, (&vecs)[0..i], 1);
return total;
}
vecs[i] = pattern;
i += 1;
total += try w.vtable.drain(w, (&vecs)[0..i], @min(remaining / pattern.len, splat));
return total;
}
const SplatHeaderTestCase = struct {
writer_type: enum { fixed, allocating },
/// writer_type 为 .fixed 时,决定缓冲区大小。
/// writer_type 为 .allocating 时,决定初始容量。
buf_len: usize = 100,
header: []const u8,
data: []const []const u8,
splat: u8,
limit: u8,
expected_res: union(enum) { written: usize, write_failed },
expected_buf_content: []const u8,
};
fn testWriteSplatHeaderLimit(comptime test_case: SplatHeaderTestCase) !void {
var buf: [test_case.buf_len]u8 = @splat(0);
var aw: Allocating = if (test_case.writer_type == .allocating)
try Allocating.initCapacity(testing.allocator, test_case.buf_len)
else
undefined;
defer if (test_case.writer_type == .allocating) aw.deinit();
var fw: Writer = if (test_case.writer_type == .fixed) .fixed(&buf) else undefined;
var w: *Writer = switch (test_case.writer_type) {
.allocating => &aw.writer,
.fixed => &fw,
};
const n_or_error = w.writeSplatHeaderLimit(test_case.header, test_case.data, test_case.splat, .limited(test_case.limit));
switch (test_case.expected_res) {
.written => |expected_len| {
const n = try n_or_error;
try std.testing.expectEqual(expected_len, n);
},
.write_failed => {
try std.testing.expectError(error.WriteFailed, n_or_error);
},
}
try std.testing.expectEqualStrings(test_case.expected_buf_content, w.buffered());
}
test "fixed writer writeSplatHeaderLimit" {
// 缓冲区大于完整数据大小的固定写入器
try testWriteSplatHeaderLimit(.{ .writer_type = .fixed, .header = "header is longer", .data = &.{""}, .splat = 1, .limit = 6, .expected_res = .{ .written = 6 }, .expected_buf_content = "header" });
try testWriteSplatHeaderLimit(.{ .writer_type = .fixed, .header = "head", .data = &.{"123456"}, .splat = 1, .limit = 5, .expected_res = .{ .written = 5 }, .expected_buf_content = "head1" });
try testWriteSplatHeaderLimit(.{ .writer_type = .fixed, .header = "head", .data = &.{"123"}, .splat = 1, .limit = 10, .expected_res = .{ .written = 7 }, .expected_buf_content = "head123" });
try testWriteSplatHeaderLimit(.{ .writer_type = .fixed, .header = "head", .data = &.{ "1", "abcdefg" }, .splat = 1, .limit = 6, .expected_res = .{ .written = 6 }, .expected_buf_content = "head1a" });
try testWriteSplatHeaderLimit(.{ .writer_type = .fixed, .header = "head", .data = &.{ "123", "abc" }, .splat = 2, .limit = 6, .expected_res = .{ .written = 6 }, .expected_buf_content = "head12" });
try testWriteSplatHeaderLimit(.{ .writer_type = .fixed, .header = "head", .data = &.{ "123", "abc" }, .splat = 2, .limit = 11, .expected_res = .{ .written = 11 }, .expected_buf_content = "head123abca" });
try testWriteSplatHeaderLimit(.{ .writer_type = .fixed, .header = "head", .data = &.{ "123", "a" }, .splat = 2, .limit = 10, .expected_res = .{ .written = 9 }, .expected_buf_content = "head123aa" });
try testWriteSplatHeaderLimit(.{ .writer_type = .fixed, .header = "head", .data = &.{ "123", "abc" }, .splat = 2, .limit = 100, .expected_res = .{ .written = 13 }, .expected_buf_content = "head123abcabc" });
// 缓冲区小于完整数据大小的固定写入器
try testWriteSplatHeaderLimit(.{ .writer_type = .fixed, .header = "header is longer", .data = &.{""}, .splat = 1, .limit = 6, .expected_res = .write_failed, .expected_buf_content = "head", .buf_len = 4 });
try testWriteSplatHeaderLimit(.{ .writer_type = .fixed, .header = "head", .data = &.{"123456"}, .splat = 1, .limit = 8, .expected_res = .write_failed, .expected_buf_content = "head1", .buf_len = 5 });
try testWriteSplatHeaderLimit(.{ .writer_type = .fixed, .header = "head", .data = &.{ "123", "ab" }, .splat = 2, .limit = 100, .expected_res = .write_failed, .expected_buf_content = "head123aba", .buf_len = 10 });
// 在重复写入期间需要扩容的分配型写入器
try testWriteSplatHeaderLimit(.{ .writer_type = .allocating, .buf_len = 8, .header = "hhhh", .data = &.{"PP"}, .splat = 3, .limit = 100, .expected_res = .{ .written = 10 }, .expected_buf_content = "hhhhPPPPPP" });
try testWriteSplatHeaderLimit(.{ .writer_type = .allocating, .buf_len = 2, .header = "", .data = &.{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "X", "Y", "ZZ" }, .splat = 2, .limit = 100, .expected_res = .{ .written = 16 }, .expected_buf_content = "0123456789XYZZZZ" });
try testWriteSplatHeaderLimit(.{ .writer_type = .allocating, .buf_len = 2, .header = "", .data = &.{ "0", "1", "2", "", "", "3", "4" }, .splat = 2, .limit = 4, .expected_res = .{ .written = 4 }, .expected_buf_content = "0123" });
}
test "writeSplatHeader splatting avoids buffer aliasing temptation" {
const initial_buf = try testing.allocator.alloc(u8, 8);
var aw: Allocating = .initOwnedSlice(testing.allocator, initial_buf);
defer aw.deinit();
// 此测试假定此函数中的向量缓冲区数量为 8。
const n = try aw.writer.writeSplatHeader("header which is longer than buf ", &.{
"1", "2", "3", "4", "5", "6", "foo", "bar", "foo",
}, 3);
try testing.expectEqual(53, n);
try testing.expectEqualStrings(
"header which is longer than buf 123456foobarfoofoofoo",
aw.writer.buffered(),
);
}
/// 排空所有剩余的缓冲数据。
pub fn flush(w: *Writer) Error!void {
return w.vtable.flush(w);
}
/// 反复调用 `VTable.drain`,直到 `end` 为零。
pub fn defaultFlush(w: *Writer) Error!void {
const drainFn = w.vtable.drain;
while (w.end != 0) _ = try drainFn(w, &.{""}, 1);
}
/// 不执行任何操作。
pub fn noopFlush(w: *Writer) Error!void {
_ = w;
}
test "fixed buffer flush" {
var buffer: [1]u8 = undefined;
var writer: Writer = .fixed(&buffer);
try writer.writeByte(10);
try writer.flush();
try testing.expectEqual(10, buffer[0]);
}
pub fn rebase(w: *Writer, preserve: usize, unused_capacity_len: usize) Error!void {
if (w.buffer.len - w.end >= unused_capacity_len) {
@branchHint(.likely);
return;
}
return w.vtable.rebase(w, preserve, unused_capacity_len);
}
pub fn defaultRebase(w: *Writer, preserve: usize, minimum_len: usize) Error!void {
while (w.buffer.len - w.end < minimum_len) {
{
// TODO: 在 Writer 中引入定位索引,
// 替代这段向实现“隐藏”数据的逻辑。
const preserved_head = w.end -| preserve;
const preserved_tail = w.end;
const preserved_len = preserved_tail - preserved_head;
w.end = preserved_head;
defer w.end += preserved_len;
assert(0 == try w.vtable.drain(w, &.{""}, 1));
assert(w.end <= preserved_head + preserved_len);
@memmove(w.buffer[w.end..][0..preserved_len], w.buffer[preserved_head..preserved_tail]);
}
// 若循环条件为 false,此断言无论如何都会通过。
// 否则,先让实现有机会扩展缓冲区,
// 再对缓冲区长度执行断言。
assert(w.buffer.len - preserve >= minimum_len);
}
}
pub fn unusedCapacitySlice(w: *const Writer) []u8 {
return w.buffer[w.end..];
}
pub fn unusedCapacityLen(w: *const Writer) usize {
return w.buffer.len - w.end;
}
/// 断言所提供缓冲区总容量足以容纳 `len`。
///
/// 将缓冲区结束位置推进 `len`。
pub fn writableArray(w: *Writer, comptime len: usize) Error!*[len]u8 {
const big_slice = try w.writableSliceGreedy(len);
advance(w, len);
return big_slice[0..len];
}
/// 断言所提供缓冲区总容量足以容纳 `len`。
///
/// 将缓冲区结束位置推进 `len`。
pub fn writableSlice(w: *Writer, len: usize) Error![]u8 {
const big_slice = try w.writableSliceGreedy(len);
advance(w, len);
return big_slice[0..len];
}
/// 断言所提供缓冲区的总容量足以容纳 `minimum_len`。
///
/// 不会通过 `advance` 推进缓冲区结束位置。
///
/// 若 `minimum_len` 为零,则等价于 `unusedCapacitySlice`。
pub fn writableSliceGreedy(w: *Writer, minimum_len: usize) Error![]u8 {
return writableSliceGreedyPreserve(w, 0, minimum_len);
}
/// 断言提供的缓冲区总容量足以容纳 `minimum_len`
/// 与 `preserve` 之和。
///
/// 不会 `advance` 缓冲区结束位置。
///
/// 排空缓冲区时,确保至少保留 `preserve` 个字节
/// 在缓冲区中。
///
/// 如果 `preserve` 为零,等同于 `writableSliceGreedy`。
pub fn writableSliceGreedyPreserve(w: *Writer, preserve: usize, minimum_len: usize) Error![]u8 {
if (w.buffer.len - w.end >= minimum_len) {
@branchHint(.likely);
return w.buffer[w.end..];
}
try w.vtable.rebase(w, preserve, minimum_len);
assert(w.buffer.len >= preserve + minimum_len);
return w.buffer[w.end..];
}
/// 断言提供的缓冲区总容量足以容纳 `len`
/// 与 `preserve` 之和。
///
/// 将缓冲区结束位置推进 `len`。
///
/// 排空缓冲区时,确保至少保留 `preserve` 个字节
/// 在缓冲区中。
///
/// 如果 `preserve` 为零,等同于 `writableSlice`。
pub fn writableSlicePreserve(w: *Writer, preserve: usize, len: usize) Error![]u8 {
const big_slice = try w.writableSliceGreedyPreserve(preserve, len);
advance(w, len);
return big_slice[0..len];
}
pub fn ensureUnusedCapacity(w: *Writer, n: usize) Error!void {
_ = try writableSliceGreedy(w, n);
}
pub fn undo(w: *Writer, n: usize) void {
w.end -= n;
}
/// 调用 `writableSliceGreedy` 后,此函数跟踪实际写入的字节数。
///
/// 使用 `writableSlice` 或 `writableArray` 时无需调用。
///
pub fn advance(w: *Writer, n: usize) void {
const new_end = w.end + n;
assert(new_end <= w.buffer.len);
w.end = new_end;
}
/// `data` 参数可变,因为此函数需要修改其
/// 字段,以处理 `VTable.writeSplat` 的部分写入。
pub fn writeVecAll(w: *Writer, data: [][]const u8) Error!void {
var index: usize = 0;
var truncate: usize = 0;
while (index < data.len) {
{
const untruncated = data[index];
data[index] = untruncated[truncate..];
defer data[index] = untruncated;
truncate += try w.writeVec(data[index..]);
}
while (index < data.len and truncate >= data[index].len) {
truncate -= data[index].len;
index += 1;
}
}
}
/// `data` 参数可变,因为此函数需要修改其中字段,
/// 以处理 `VTable.writeSplat` 的部分写入。
/// 返回之前,`data` 将恢复为原始状态。
pub fn writeSplatAll(w: *Writer, data: [][]const u8, splat: usize) Error!void {
var index: usize = 0;
var truncate: usize = 0;
while (index + 1 < data.len) {
{
const untruncated = data[index];
data[index] = untruncated[truncate..];
defer data[index] = untruncated;
truncate += try w.writeSplat(data[index..], splat);
}
while (truncate >= data[index].len and index + 1 < data.len) {
truncate -= data[index].len;
index += 1;
}
}
// 处理剩余的标量广播
if (data.len != 0 and truncate < data[index].len * splat) {
assert(index == data.len - 1);
var remaining_splat = splat;
while (true) {
remaining_splat -= truncate / data[index].len;
truncate %= data[index].len;
if (remaining_splat == 0) break;
truncate += try w.writeSplat(&.{ data[index][truncate..], data[index] }, remaining_splat - 1);
}
}
}
test writeSplatAll {
var aw: Writer.Allocating = .init(testing.allocator);
defer aw.deinit();
var buffers = [_][]const u8{ "ba", "na" };
try aw.writer.writeSplatAll(&buffers, 2);
try testing.expectEqualStrings("banana", aw.writer.buffered());
}
test "writeSplatAll works with a single buffer" {
var aw: Writer.Allocating = .init(testing.allocator);
defer aw.deinit();
var message: [1][]const u8 = .{"hello"};
try aw.writer.writeSplatAll(&message, 3);
try testing.expectEqualStrings("hellohellohello", aw.writer.buffered());
}
/// 将 `bytes` 传输到流,至多调用一次 `drain`。
///
/// 返回已传输字节数,可能小于 `bytes.len`,也可能为零。
///
/// 返回值小于 `bytes.len` 不表示失败;后续调用可能返回非零值,或者因 `error.WriteFailed` 失败。
///
/// 另见:
/// * `writeAll`
/// * `writeVec`
///
///
pub fn write(w: *Writer, bytes: []const u8) Error!usize {
if (w.end + bytes.len <= w.buffer.len) {
@branchHint(.likely);
@memcpy(w.buffer[w.end..][0..bytes.len], bytes);
w.end += bytes.len;
return bytes.len;
}
return w.vtable.drain(w, &.{bytes}, 1);
}
/// 将 `bytes` 传输到流中,按需多次调用 `drain`,
/// 直到全部 `bytes` 传输完成。
///
/// 另见:
/// * `print`
/// * `writeVecAll`
/// * `write`
pub fn writeAll(w: *Writer, bytes: []const u8) Error!void {
var index: usize = 0;
while (index < bytes.len) index += try w.write(bytes[index..]);
}
/// 使用 `args` 渲染 `fmt` 字符串,并以字节切片调用 `w`。
///
/// 格式字符串必须在编译时已知,可以包含下列形式的占位符:
/// ```
/// {[argument][specifier]:[fill][alignment][width].[precision]}
/// ```
///
/// 上面每个单词及包围它的方括号表示需要替换的参数:
///
/// - **argument** 是要插入参数的数字索引或字段名称。
/// - 使用字段名称时,必须用方括号包围字段名(标识符),例如 `{[score]...}`;数字索引则可以写成 `{2...}`。
/// - **specifier** 是依赖类型的格式选项,决定如何格式化该类型,详见下文。
/// - **fill** 是用于填充格式化数字的单个字节。
/// - **alignment** 是三个字节之一:'<'、'^'、'>',分别使数字左对齐、居中、右对齐。
/// - 并非所有格式说明符都支持对齐。
/// - 对齐不识别 Unicode,仅适用于原始字节或 ASCII。
/// - **width** 是字段总字节数,仅适用于数字格式化。
/// - **precision** 指定格式化数字的小数位数。
///
/// 多数参数可选,可以省略。如果某分隔符之后的所有参数均省略,也可以省略该分隔符(':' 和 '.')。
///
/// **fill** 是例外:如果指定 **width** 的同时需要非零 **fill** 字符,就必须提供 **alignment**,否则 ':' 后面的数字会被解释为 **width**。
///
/// **specifier** 支持:
/// - "x" 和 "X":数值的十六进制表示,或字符串的十六进制字节表示
/// - "s":
/// - 对 u8 多项指针和 C 指针,按照null 结尾的 C 字符串打印
/// - 对 u8 切片,将整个切片作为字符串打印,不使用null 结尾
/// - "t":
/// - 对枚举和标记联合,打印标记名称
/// - 对错误集合,打印错误名称
/// - "b64":将字符串打印为标准 base64
/// - "e":以科学记数法表示浮点值
/// - "d":数值的十进制表示
/// - "b":整数的二进制表示
/// - "o":整数的八进制表示
/// - "c":将整数作为 ASCII 字符打印,整数类型最多八位
/// - "u":将整数作为 UTF-8 序列打印,整数类型最多二十一位
/// - "B":以 SI 单位(十进制)表示字节数
/// - "Bi":以 IEC 单位(二进制)表示字节数
/// - "?":将可选值表示为解包后的值或 `null`,后面可以跟底层值的格式说明符
/// - "!":将错误联合表示为解包后的值或格式化错误值,后面可以跟底层值的格式说明符
/// - "*":打印值的地址而非值本身
/// - "any":使用默认格式打印任意类型的值
/// - "f":委托给类型的 `format` 方法,传入 `*Writer`,预期返回 `Error!void`
/// - "q":打印为使用双引号转义的字符串。双引号内的内容保持不变,以下转换除外:
/// - 转义:'\n'、'\r'、'\t'、'\\'、'"'
/// - 十六进制编码:ASCII 控制字符、无效 UTF-8 序列、非 ASCII 行结束符(U+0085、U+2028、U+2029)、字节顺序标记(U+FEFF)
/// - "qf":委托给类型的 `format` 方法,同时进行双引号转义
///
/// 格式字符串中的字面花括号可以通过重复花括号转义,例如 "{{" 或 "}}"。
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
///
pub fn print(w: *Writer, comptime fmt: []const u8, args: anytype) Error!void {
const ArgsType = @TypeOf(args);
const args_type_info = @typeInfo(ArgsType);
if (args_type_info != .@"struct") {
@compileError("expected tuple or struct argument, found " ++ @typeName(ArgsType));
}
const field_names = args_type_info.@"struct".field_names;
const max_format_args = @typeInfo(std.fmt.ArgSetType).int.bits;
if (field_names.len > max_format_args) {
@compileError("32 arguments max are supported per format call");
}
@setEvalBranchQuota(@as(comptime_int, fmt.len) * 1000); // 注意:因 16 位 usize 会溢出,此处提升类型。
comptime var arg_state: std.fmt.ArgState = .{ .args_len = field_names.len };
comptime var i = 0;
comptime var literal: []const u8 = "";
inline while (true) {
const start_index = i;
inline while (i < fmt.len) : (i += 1) {
switch (fmt[i]) {
'{', '}' => break,
else => {},
}
}
comptime var end_index = i;
comptime var unescape_brace = false;
// 处理 {{ 和 }},将其反转义为单个花括号。
if (i + 1 < fmt.len and fmt[i + 1] == fmt[i]) {
unescape_brace = true;
// 将第一个花括号纳入字面量……
end_index += 1;
// ……并跳过两者
i += 2;
}
literal = literal ++ fmt[start_index..end_index];
// 已跳过另一个花括号,重新开始循环
if (unescape_brace) continue;
// 写出字面量
if (literal.len != 0) {
try w.writeAll(literal);
literal = "";
}
if (i >= fmt.len) break;
if (fmt[i] == '}') {
@compileError("missing opening {");
}
// 越过 {
comptime assert(fmt[i] == '{');
i += 1;
const fmt_begin = i;
// 查找右花括号
inline while (i < fmt.len and fmt[i] != '}') : (i += 1) {}
const fmt_end = i;
if (i >= fmt.len) {
@compileError("missing closing }");
}
// 越过 }
comptime assert(fmt[i] == '}');
i += 1;
const placeholder_array = fmt[fmt_begin..fmt_end].*;
const placeholder = comptime std.fmt.Placeholder.parse(&placeholder_array);
const arg_pos = comptime switch (placeholder.arg) {
.none => null,
.number => |pos| pos,
.named => |arg_name| std.meta.fieldIndex(ArgsType, arg_name) orelse
@compileError("no argument with name '" ++ arg_name ++ "'"),
};
const width = switch (placeholder.width) {
.none => null,
.number => |v| v,
.named => |arg_name| blk: {
const arg_i = comptime std.meta.fieldIndex(ArgsType, arg_name) orelse
@compileError("no argument with name '" ++ arg_name ++ "'");
_ = comptime arg_state.nextArg(arg_i) orelse @compileError("too few arguments");
break :blk @field(args, arg_name);
},
};
const precision = switch (placeholder.precision) {
.none => null,
.number => |v| v,
.named => |arg_name| blk: {
const arg_i = comptime std.meta.fieldIndex(ArgsType, arg_name) orelse
@compileError("no argument with name '" ++ arg_name ++ "'");
_ = comptime arg_state.nextArg(arg_i) orelse @compileError("too few arguments");
break :blk @field(args, arg_name);
},
};
const arg_to_print = comptime arg_state.nextArg(arg_pos) orelse
@compileError("too few arguments");
try w.printValue(
placeholder.specifier_arg,
.{
.fill = placeholder.fill,
.alignment = placeholder.alignment,
.width = width,
.precision = precision,
},
@field(args, field_names[arg_to_print]),
std.options.fmt_max_depth,
);
}
if (comptime arg_state.hasUnusedArgs()) {
const missing_count = arg_state.args_len - @popCount(arg_state.used_args);
switch (missing_count) {
0 => unreachable,
1 => @compileError("unused argument in '" ++ fmt ++ "'"),
else => @compileError(std.fmt.comptimePrint("{d}", .{missing_count}) ++ " unused arguments in '" ++ fmt ++ "'"),
}
}
}
/// 按需反复调用 `drain`,直到 `byte` 已传输。
pub fn writeByte(w: *Writer, byte: u8) Error!void {
while (w.buffer.len - w.end == 0) {
const n = try w.vtable.drain(w, &.{&.{byte}}, 1);
if (n > 0) return;
} else {
@branchHint(.likely);
w.buffer[w.end] = byte;
w.end += 1;
}
}
/// 成功时,若已有足够缓冲字节,则至少保留 `preserve` 字节在缓冲区中。
/// 调用后写入器缓冲的字节数,仅在以下条件下才可能小于 `preserve`:调用前 `w.end + 1` 小于 `preserve`。
/// 有意保留的字节包括此前缓冲数据中最多 `preserve -| 1` 字节,以及新写入的字节。
///
/// 断言缓冲区容量至少为 `preserve`。
///
///
///
pub fn writeBytePreserve(w: *Writer, preserve: usize, byte: u8) Error!void {
if (w.buffer.len - w.end == 0) {
@branchHint(.unlikely);
try w.vtable.rebase(w, preserve -| 1, 1);
}
w.buffer[w.end] = byte;
w.end += 1;
}
/// 多次写入同一字节,按需多次
/// 执行底层写入调用。
pub fn splatByteAll(w: *Writer, byte: u8, n: usize) Error!void {
var remaining: usize = n;
while (remaining > 0) remaining -= try w.splatByte(byte, remaining);
}
test splatByteAll {
var aw: Writer.Allocating = .init(testing.allocator);
defer aw.deinit();
try aw.writer.splatByteAll('7', 45);
try testing.expectEqualStrings(&@as([45]u8, @splat('7')), aw.writer.buffered());
}
/// 多次写入同一字节,按需多次
/// 执行底层写入调用。
///
/// 成功时,只要已缓冲字节足够,
/// 就至少保留 `preserve` 个字节在缓冲区中。
/// 只有调用前的 `w.end + n` 小于 `preserve` 时,
/// 调用后写入器缓冲的字节数才可能少于 `preserve`。
/// 有意保留的字节包括此前已缓冲字节中的至多 `preserve -| n` 个,
/// 以及新写入字节中的 `@min(n, preserve_len)` 个。
///
/// 断言缓冲区容量至少为 `preserve`。
/// `n` 可以大于缓冲区容量。
///
pub fn splatBytePreserve(w: *Writer, preserve: usize, byte: u8, n: usize) Error!void {
const new_end = w.end + n;
if (new_end <= w.buffer.len) {
@memset(w.buffer[w.end..][0..n], byte);
w.end = new_end;
return;
}
// `n` 较大时,可以在一定程度上忽略 `preserve`。
var remaining = n;
while (remaining > preserve) {
assert(remaining != 0);
remaining -= try splatByte(w, byte, remaining - preserve);
if (w.end + remaining <= w.buffer.len) {
@memset(w.buffer[w.end..][0..remaining], byte);
w.end += remaining;
return;
}
}
// 确保满足 `rebase` 的约定。
assert(w.end + remaining > w.buffer.len);
// 将要保留的数量减去尚待重复写入的数量,
// 因为剩余重复写入始终属于
// 该保留部分。
try w.vtable.rebase(w, preserve -| remaining, remaining);
@memset(w.buffer[w.end..][0..remaining], byte);
w.end += remaining;
}
/// 多次写入同一个字节,允许短写。
///
/// 底层 `VTable.drain` 最多调用一次。
pub fn splatByte(w: *Writer, byte: u8, n: usize) Error!usize {
if (w.end + n <= w.buffer.len) {
@branchHint(.likely);
@memset(w.buffer[w.end..][0..n], byte);
w.end += n;
return n;
}
return writeSplat(w, &.{&.{byte}}, n);
}
/// 多次写入同一切片,按需多次
/// 执行底层写入调用。
pub fn splatBytesAll(w: *Writer, bytes: []const u8, splat: usize) Error!void {
var remaining_bytes: usize = bytes.len * splat;
remaining_bytes -= try w.splatBytes(bytes, splat);
while (remaining_bytes > 0) {
const leftover_splat = remaining_bytes / bytes.len;
const leftover_bytes = remaining_bytes % bytes.len;
const buffers: [2][]const u8 = .{ bytes[bytes.len - leftover_bytes ..], bytes };
remaining_bytes -= try w.writeSplat(&buffers, leftover_splat);
}
}
test splatBytesAll {
var aw: Writer.Allocating = .init(testing.allocator);
defer aw.deinit();
try aw.writer.splatBytesAll("hello", 3);
try testing.expectEqualStrings("hellohellohello", aw.writer.buffered());
}
/// 多次写入同一个切片,允许短写。
///
/// 底层 `VTable.drain` 最多调用一次。
pub fn splatBytes(w: *Writer, bytes: []const u8, n: usize) Error!usize {
return writeSplat(w, &.{bytes}, n);
}
/// 断言 `buffer` 初始化时容量至少为 `@sizeOf(T)` 字节。
pub inline fn writeInt(w: *Writer, comptime T: type, value: T, endian: std.lang.Endian) Error!void {
var bytes: [@divExact(@typeInfo(T).int.bits, 8)]u8 = undefined;
std.mem.writeInt(std.math.ByteAlignedInt(@TypeOf(value)), &bytes, value, endian);
return w.writeAll(&bytes);
}
/// 函数采用内联,以便在 `endian` 在编译期已知且
/// 与宿主端序相同时,避免生成无用代码。
pub inline fn writeStruct(w: *Writer, value: anytype, endian: std.lang.Endian) Error!void {
switch (@typeInfo(@TypeOf(value))) {
.@"struct" => |info| switch (info.layout) {
.auto => @compileError("ill-defined memory layout"),
.@"extern" => {
if (native_endian == endian) {
return w.writeAll(@ptrCast((&value)[0..1]));
} else {
var copy = value;
std.mem.byteSwapAllFields(@TypeOf(value), ©);
return w.writeAll(@ptrCast((©)[0..1]));
}
},
.@"packed" => {
return writeInt(w, info.backing_integer.?, @bitCast(value), endian);
},
},
else => @compileError("not a struct"),
}
}
pub inline fn writeSliceEndian(
w: *Writer,
Elem: type,
slice: []const Elem,
endian: std.lang.Endian,
) Error!void {
switch (@typeInfo(Elem)) {
.@"struct" => |info| comptime assert(info.layout != .auto),
.int, .@"enum" => {},
else => @compileError("ill-defined memory layout"),
}
if (native_endian == endian) {
return writeAll(w, @ptrCast(slice));
} else {
return writeSliceSwap(w, Elem, slice);
}
}
pub fn writeSliceSwap(w: *Writer, Elem: type, slice: []const Elem) Error!void {
for (slice) |elem| {
var tmp = elem;
std.mem.byteSwapAllFields(Elem, &tmp);
try w.writeAll(@ptrCast(&tmp));
}
}
/// 与 `writeSplat` 和 `writeVec` 不同,即使缓冲区容量
/// 足以容纳文件内容,此函数仍会调用 `VTable`。
///
/// 调用方负责刷新缓冲区。虽然实现可能通过绕过缓冲区
/// 进行优化,但不保证如此。
///
/// 虽然在这种情况下可以直接读入缓冲区,
/// 从而从错误集合中移除 `error.Unimplemented`,但这里没有
/// 这样做,因为在调用栈更高层处理效率更高,
/// 可避免每次写入都遇到此错误。
///
/// 另一种错误集合中不含 `error.Unimplemented`
/// 的方案,参见 `sendFileReading`。
pub fn sendFile(w: *Writer, file_reader: *File.Reader, limit: Limit) FileError!usize {
return w.vtable.sendFile(w, file_reader, limit);
}
/// 返回从 `header` 和 `file_reader` 消费的字节数。
///
/// `limit` 仅适用于 `file_reader`。
pub fn sendFileHeader(
w: *Writer,
header: []const u8,
file_reader: *File.Reader,
limit: Limit,
) FileError!usize {
const new_end = w.end + header.len;
if (new_end <= w.buffer.len) {
@memcpy(w.buffer[w.end..][0..header.len], header);
w.end = new_end;
const file_bytes = w.vtable.sendFile(w, file_reader, limit) catch |err| switch (err) {
error.ReadFailed, error.WriteFailed => |e| return e,
error.EndOfStream, error.Unimplemented => |e| {
// 这些错误并非致命错误,因此只要写入了任何头部字节,就报告已写入字节并抑制错误。仅在没有头部字节时才可返回错误。
//
if (header.len != 0) return header.len;
return e;
},
};
return header.len + file_bytes;
}
const buffered_contents = limit.slice(file_reader.interface.buffered());
const n = try w.vtable.drain(w, &.{ header, buffered_contents }, 1);
file_reader.interface.toss(n -| header.len);
return n;
}
/// 断言缓冲区容量及 `limit` 均不为零。
pub fn sendFileReading(w: *Writer, file_reader: *File.Reader, limit: Limit) FileReadingError!usize {
assert(limit != .nothing);
const dest = limit.slice(try w.writableSliceGreedy(1));
const n = try file_reader.interface.readSliceShort(dest);
if (n == 0) return error.EndOfStream;
w.advance(n);
return n;
}
/// 返回逻辑写入的字节数,不包括 `buffer` 中的字节,因为这些字节此前已完成逻辑写入。
///
/// 调用者负责刷新。尽管可能作为优化绕过缓冲区,但并不保证如此。
///
/// 断言缓冲区容量非零。
///
///
pub fn sendFileAll(w: *Writer, file_reader: *File.Reader, limit: Limit) FileAllError!usize {
// 回退的 sendFileReadingAll() 路径会断言缓冲区容量非零。
// 此处也显式执行同一断言,确保即使未进入
// 回退路径,也能触发该断言。
assert(w.buffer.len > 0);
var remaining = @backingInt(limit);
while (remaining > 0) {
const n = sendFile(w, file_reader, .limited(remaining)) catch |err| switch (err) {
error.EndOfStream => break,
error.Unimplemented => {
file_reader.mode = file_reader.mode.toSimple();
remaining -= try w.sendFileReadingAll(file_reader, .limited(remaining));
break;
},
else => |e| return e,
};
remaining -= n;
}
return @backingInt(limit) - remaining;
}
/// 等价于 `sendFileAll`,但使用直接的 `pread` 和 `read` 调用读取 `file`,而非使用 `sendFile`。
/// 通常用于底层实现返回 `error.Unimplemented` 时的后备方案,因此该错误码不出现在此函数的错误集合中。
///
/// 断言缓冲区容量非零。
///
///
pub fn sendFileReadingAll(w: *Writer, file_reader: *File.Reader, limit: Limit) FileAllError!usize {
var remaining = @backingInt(limit);
while (remaining > 0) {
remaining -= sendFileReading(w, file_reader, .limited(remaining)) catch |err| switch (err) {
error.EndOfStream => break,
else => |e| return e,
};
}
return @backingInt(limit) - remaining;
}
pub fn alignBuffer(
w: *Writer,
buffer: []const u8,
width: usize,
alignment: std.fmt.Alignment,
fill: u8,
) Error!void {
const padding = if (buffer.len < width) width - buffer.len else 0;
if (padding == 0) {
@branchHint(.likely);
return w.writeAll(buffer);
}
switch (alignment) {
.left => {
try w.writeAll(buffer);
try w.splatByteAll(fill, padding);
},
.center => {
const left_padding = padding / 2;
const right_padding = (padding + 1) / 2;
try w.splatByteAll(fill, left_padding);
try w.writeAll(buffer);
try w.splatByteAll(fill, right_padding);
},
.right => {
try w.splatByteAll(fill, padding);
try w.writeAll(buffer);
},
}
}
pub fn alignBufferOptions(w: *Writer, buffer: []const u8, options: std.fmt.Options) Error!void {
return w.alignBuffer(buffer, options.width orelse buffer.len, options.alignment, options.fill);
}
pub fn printAddress(w: *Writer, value: anytype) Error!void {
const T = @TypeOf(value);
switch (@typeInfo(T)) {
.pointer => |info| {
try w.writeAll(@typeName(info.child) ++ "@");
const int = if (info.size == .slice) @intFromPtr(value.ptr) else @intFromPtr(value);
return w.printInt(int, 16, .lower, .{});
},
.optional => |info| {
if (@typeInfo(info.child) == .pointer) {
try w.writeAll(@typeName(info.child) ++ "@");
try w.printInt(@intFromPtr(value), 16, .lower, .{});
return;
}
},
else => {},
}
@compileError("cannot format non-pointer type " ++ @typeName(T) ++ " with * specifier");
}
/// 若 `value` 为联合体,断言 `buffer` 的容量至少为 2。
pub fn printValue(
w: *Writer,
comptime fmt: []const u8,
options: std.fmt.Options,
value: anytype,
max_depth: usize,
) Error!void {
const T = @TypeOf(value);
switch (fmt.len) {
1 => switch (fmt[0]) {
'*' => return w.printAddress(value),
'f' => return value.format(w),
'd' => switch (@typeInfo(T)) {
.float, .comptime_float => return printFloat(w, value, options.toNumber(.decimal, .lower)),
.int, .comptime_int => return printInt(w, value, 10, .lower, options),
.@"struct" => return value.formatNumber(w, options.toNumber(.decimal, .lower)),
.@"enum" => return printInt(w, @backingInt(value), 10, .lower, options),
.vector => return printVector(w, fmt, options, value, max_depth),
else => invalidFmtError(fmt, value),
},
'c' => return w.printAsciiChar(value, options),
'u' => return w.printUnicodeCodepoint(value),
'b' => switch (@typeInfo(T)) {
.int, .comptime_int => return printInt(w, value, 2, .lower, options),
.@"enum" => return printInt(w, @backingInt(value), 2, .lower, options),
.@"struct" => return value.formatNumber(w, options.toNumber(.binary, .lower)),
.vector => return printVector(w, fmt, options, value, max_depth),
else => invalidFmtError(fmt, value),
},
'o' => switch (@typeInfo(T)) {
.int, .comptime_int => return printInt(w, value, 8, .lower, options),
.@"enum" => return printInt(w, @backingInt(value), 8, .lower, options),
.@"struct" => return value.formatNumber(w, options.toNumber(.octal, .lower)),
.vector => return printVector(w, fmt, options, value, max_depth),
else => invalidFmtError(fmt, value),
},
'x' => switch (@typeInfo(T)) {
.float, .comptime_float => return printFloatHexOptions(w, value, options.toNumber(.hex, .lower)),
.int, .comptime_int => return printInt(w, value, 16, .lower, options),
.@"enum" => return printInt(w, @backingInt(value), 16, .lower, options),
.@"struct" => return value.formatNumber(w, options.toNumber(.hex, .lower)),
.pointer => |info| switch (info.size) {
.one, .slice => {
const slice: []const u8 = value;
optionsForbidden(options);
return printHex(w, slice, .lower);
},
.many, .c => {
const slice: [:0]const u8 = std.mem.span(value);
optionsForbidden(options);
return printHex(w, slice, .lower);
},
},
.array => {
const slice: []const u8 = &value;
optionsForbidden(options);
return printHex(w, slice, .lower);
},
.vector => return printVector(w, fmt, options, value, max_depth),
else => invalidFmtError(fmt, value),
},
'X' => switch (@typeInfo(T)) {
.float, .comptime_float => return printFloatHexOptions(w, value, options.toNumber(.hex, .upper)),
.int, .comptime_int => return printInt(w, value, 16, .upper, options),
.@"enum" => return printInt(w, @backingInt(value), 16, .upper, options),
.@"struct" => return value.formatNumber(w, options.toNumber(.hex, .upper)),
.pointer => |info| switch (info.size) {
.one, .slice => {
const slice: []const u8 = value;
optionsForbidden(options);
return printHex(w, slice, .upper);
},
.many, .c => {
const slice: [:0]const u8 = std.mem.span(value);
optionsForbidden(options);
return printHex(w, slice, .upper);
},
},
.array => {
const slice: []const u8 = &value;
optionsForbidden(options);
return printHex(w, slice, .upper);
},
.vector => return printVector(w, fmt, options, value, max_depth),
else => invalidFmtError(fmt, value),
},
's' => switch (@typeInfo(T)) {
.pointer => |info| switch (info.size) {
.one, .slice => {
const slice: []const u8 = value;
return w.alignBufferOptions(slice, options);
},
.many, .c => {
const slice: [:0]const u8 = std.mem.span(value);
return w.alignBufferOptions(slice, options);
},
},
.array => {
const slice: []const u8 = &value;
return w.alignBufferOptions(slice, options);
},
else => invalidFmtError(fmt, value),
},
'q' => switch (@typeInfo(T)) {
.pointer => |info| switch (info.size) {
.one, .slice => return printStringEscaped(w, value),
.many, .c => return printStringEscaped(w, std.mem.span(value)),
},
.array => return printStringEscaped(w, &value),
else => invalidFmtError(fmt, value),
},
'B' => switch (@typeInfo(T)) {
.int, .comptime_int => return w.printByteSize(value, .decimal, options),
.@"struct" => return value.formatByteSize(w, .decimal),
else => invalidFmtError(fmt, value),
},
'e' => switch (@typeInfo(T)) {
.float, .comptime_float => return printFloat(w, value, options.toNumber(.scientific, .lower)),
.@"struct" => return value.formatNumber(w, options.toNumber(.scientific, .lower)),
else => invalidFmtError(fmt, value),
},
'E' => switch (@typeInfo(T)) {
.float, .comptime_float => return printFloat(w, value, options.toNumber(.scientific, .upper)),
.@"struct" => return value.formatNumber(w, options.toNumber(.scientific, .upper)),
else => invalidFmtError(fmt, value),
},
't' => switch (@typeInfo(T)) {
.error_set => return w.alignBufferOptions(@errorName(value), options),
.@"enum", .enum_literal, .@"union" => return w.alignBufferOptions(@tagName(value), options),
else => invalidFmtError(fmt, value),
},
else => {},
},
2 => switch (fmt[0]) {
'B' => switch (fmt[1]) {
'i' => switch (@typeInfo(T)) {
.int, .comptime_int => return w.printByteSize(value, .binary, options),
.@"struct" => return value.formatByteSize(w, .binary),
else => invalidFmtError(fmt, value),
},
else => {},
},
'q' => switch (fmt[1]) {
'f' => {
try w.writeByte('"');
var buffer: [64]u8 = undefined;
var escaping_writer: std.zig.StringEscapeWriter = .init(w, &buffer);
try value.format(&escaping_writer.writer);
try escaping_writer.writer.flush();
try w.writeByte('"');
return;
},
else => {},
},
else => {},
},
3 => if (fmt[0] == 'b' and fmt[1] == '6' and fmt[2] == '4') switch (@typeInfo(T)) {
.pointer => |info| switch (info.size) {
.one, .slice => {
const slice: []const u8 = value;
optionsForbidden(options);
return w.printBase64(slice);
},
.many, .c => {
const slice: [:0]const u8 = std.mem.span(value);
optionsForbidden(options);
return w.printBase64(slice);
},
},
.array => {
const slice: []const u8 = &value;
optionsForbidden(options);
return w.printBase64(slice);
},
else => invalidFmtError(fmt, value),
},
else => {},
}
const is_any = comptime std.mem.eql(u8, fmt, ANY);
switch (@typeInfo(T)) {
.float, .comptime_float => {
if (!is_any and fmt.len != 0) invalidFmtError(fmt, value);
return printFloat(w, value, options.toNumber(.decimal, .lower));
},
.int, .comptime_int => {
if (!is_any and fmt.len != 0) invalidFmtError(fmt, value);
return printInt(w, value, 10, .lower, options);
},
.bool => {
if (!is_any and fmt.len != 0) invalidFmtError(fmt, value);
const string: []const u8 = if (value) "true" else "false";
return w.alignBufferOptions(string, options);
},
.void => {
if (!is_any and fmt.len != 0) invalidFmtError(fmt, value);
return w.alignBufferOptions("void", options);
},
.optional => {
const remaining_fmt = comptime if (fmt.len > 0 and fmt[0] == '?')
stripOptionalOrErrorUnionSpec(fmt)
else if (is_any)
ANY
else
@compileError("cannot print optional without a specifier (i.e. {?} or {any})");
if (value) |payload| {
return w.printValue(remaining_fmt, options, payload, max_depth);
} else {
return w.alignBufferOptions("null", options);
}
},
.error_union => {
const remaining_fmt = comptime if (fmt.len > 0 and fmt[0] == '!')
stripOptionalOrErrorUnionSpec(fmt)
else if (is_any)
ANY
else
@compileError("cannot print error union without a specifier (i.e. {!} or {any})");
if (value) |payload| {
return w.printValue(remaining_fmt, options, payload, max_depth);
} else |err| {
return w.printValue("", options, err, max_depth);
}
},
.error_set => {
if (!is_any and fmt.len != 0) invalidFmtError(fmt, value);
optionsForbidden(options);
return printErrorSet(w, value);
},
.@"enum" => |info| {
if (!is_any and fmt.len != 0) invalidFmtError(fmt, value);
optionsForbidden(options);
if (info.mode == .exhaustive) {
return printEnumExhaustive(w, value);
} else {
return printEnumNonexhaustive(w, value);
}
},
.@"union" => |info| {
if (!is_any) {
if (fmt.len != 0) invalidFmtError(fmt, value);
return printValue(w, ANY, options, value, max_depth);
}
if (max_depth == 0) {
try w.writeAll(".{ ... }");
return;
}
if (info.tag_type) |UnionTagType| {
try w.writeAll(".{ .");
try w.writeAll(@tagName(@as(UnionTagType, value)));
try w.writeAll(" = ");
inline for (info.field_names) |u_field_name| {
if (value == @field(UnionTagType, u_field_name)) {
try w.printValue(ANY, options, @field(value, u_field_name), max_depth - 1);
}
}
try w.writeAll(" }");
} else switch (info.layout) {
.auto => {
return w.writeAll(".{ ... }");
},
.@"extern", .@"packed" => {
if (info.field_names.len == 0) return w.writeAll(".{}");
try w.writeAll(".{ ");
inline for (info.field_names, 1..) |field_name, i| {
try w.writeByte('.');
try w.writeAll(field_name);
try w.writeAll(" = ");
try w.printValue(ANY, options, @field(value, field_name), max_depth - 1);
try w.writeAll(if (i < info.field_names.len) ", " else " }");
}
},
}
},
.@"struct" => |info| {
if (!is_any) {
if (fmt.len != 0) invalidFmtError(fmt, value);
return printValue(w, ANY, options, value, max_depth);
}
if (info.is_tuple) {
// 格式化元组时跳过类型名及字段名。
if (max_depth == 0) {
try w.writeAll(".{ ... }");
return;
}
try w.writeAll(".{");
inline for (info.field_names, 0..) |f_name, i| {
if (i == 0) {
try w.writeAll(" ");
} else {
try w.writeAll(", ");
}
try w.printValue(ANY, options, @field(value, f_name), max_depth - 1);
}
try w.writeAll(" }");
return;
}
if (max_depth == 0) {
try w.writeAll(".{ ... }");
return;
}
try w.writeAll(".{");
inline for (info.field_names, 0..) |f_name, i| {
if (i == 0) {
try w.writeAll(" .");
} else {
try w.writeAll(", .");
}
try w.writeAll(f_name);
try w.writeAll(" = ");
try w.printValue(ANY, options, @field(value, f_name), max_depth - 1);
}
try w.writeAll(" }");
},
.pointer => |ptr_info| switch (ptr_info.size) {
.one => switch (@typeInfo(ptr_info.child)) {
.array => |array_info| return w.printValue(fmt, options, @as([]const array_info.child, value), max_depth),
.@"enum", .@"union", .@"struct" => return w.printValue(fmt, options, value.*, max_depth),
else => {
var buffers: [2][]const u8 = .{ @typeName(ptr_info.child), "@" };
try w.writeVecAll(&buffers);
try w.printInt(@intFromPtr(value), 16, .lower, options);
return;
},
},
.many, .c => {
if (!is_any) @compileError("cannot format pointer without a specifier (i.e. {s} or {*})");
optionsForbidden(options);
try w.printAddress(value);
},
.slice => {
if (!is_any)
@compileError("cannot format slice without a specifier (i.e. {s}, {x}, {b64}, or {any})");
if (max_depth == 0) return w.writeAll("{ ... }");
try w.writeAll("{ ");
for (value, 0..) |elem, i| {
try w.printValue(fmt, options, elem, max_depth - 1);
if (i != value.len - 1) {
try w.writeAll(", ");
}
}
try w.writeAll(" }");
},
},
.array => {
if (!is_any) @compileError("cannot format array without a specifier (i.e. {s} or {any})");
return printArray(w, fmt, options, &value, max_depth);
},
.vector => |vector| {
if (!is_any and fmt.len != 0) invalidFmtError(fmt, value);
const array: [vector.len]vector.child = value;
return printArray(w, fmt, options, &array, max_depth);
},
.@"fn" => @compileError("unable to format function body type, use '*const " ++ @typeName(T) ++ "' for a function pointer type"),
.type => {
if (!is_any and fmt.len != 0) invalidFmtError(fmt, value);
return w.alignBufferOptions(@typeName(value), options);
},
.enum_literal => {
if (!is_any and fmt.len != 0) invalidFmtError(fmt, value);
optionsForbidden(options);
var vecs: [2][]const u8 = .{ ".", @tagName(value) };
return w.writeVecAll(&vecs);
},
.null => {
if (!is_any and fmt.len != 0) invalidFmtError(fmt, value);
return w.alignBufferOptions("null", options);
},
else => @compileError("unable to format type '" ++ @typeName(T) ++ "'"),
}
}
fn optionsForbidden(options: std.fmt.Options) void {
assert(options.precision == null);
assert(options.width == null);
}
fn printErrorSet(w: *Writer, error_set: anyerror) Error!void {
var vecs: [2][]const u8 = .{ "error.", @errorName(error_set) };
try w.writeVecAll(&vecs);
}
fn printEnumExhaustive(w: *Writer, value: anytype) Error!void {
var vecs: [2][]const u8 = .{ ".", @tagName(value) };
try w.writeVecAll(&vecs);
}
fn printEnumNonexhaustive(w: *Writer, value: anytype) Error!void {
if (std.enums.tagName(@TypeOf(value), value)) |tag_name| {
var vecs: [2][]const u8 = .{ ".", tag_name };
try w.writeVecAll(&vecs);
return;
}
try w.writeAll("@fromBackingInt(");
try w.printInt(@backingInt(value), 10, .lower, .{});
try w.writeByte(')');
}
/// 输出双引号,再按 Zig 字符串字面量规则转义字符串,
/// 最后输出双引号。
pub fn printStringEscaped(w: *Writer, bytes: []const u8) Error!void {
try w.writeByte('"');
try std.zig.stringEscape(bytes, w);
try w.writeByte('"');
}
pub fn printVector(
w: *Writer,
comptime fmt: []const u8,
options: std.fmt.Options,
value: anytype,
max_depth: usize,
) Error!void {
const vector = @typeInfo(@TypeOf(value)).vector;
const array: [vector.len]vector.child = value;
return printArray(w, fmt, options, &array, max_depth);
}
pub fn printArray(
w: *Writer,
comptime fmt: []const u8,
options: std.fmt.Options,
ptr_to_array: anytype,
max_depth: usize,
) Error!void {
if (max_depth == 0) return w.writeAll("{ ... }");
try w.writeAll("{ ");
for (ptr_to_array, 0..) |elem, i| {
try w.printValue(fmt, options, elem, max_depth - 1);
if (i < ptr_to_array.len - 1) {
try w.writeAll(", ");
}
}
try w.writeAll(" }");
}
// `printIntAny` 的包装器,通过将较小整数类型统一为 `isize` 和 `usize`,
// 避免此函数的泛型实例数量爆炸。
pub inline fn printInt(
w: *Writer,
value: anytype,
base: u8,
case: std.fmt.Case,
options: std.fmt.Options,
) Error!void {
switch (@TypeOf(value)) {
isize, usize => {},
comptime_int => {
if (comptime std.math.cast(usize, value)) |x| return printIntAny(w, x, base, case, options);
if (comptime std.math.cast(isize, value)) |x| return printIntAny(w, x, base, case, options);
const Int = std.math.IntFittingRange(value, value);
return printIntAny(w, @as(Int, value), base, case, options);
},
else => switch (@typeInfo(@TypeOf(value)).int.signedness) {
.signed => if (std.math.cast(isize, value)) |x| return printIntAny(w, x, base, case, options),
.unsigned => if (std.math.cast(usize, value)) |x| return printIntAny(w, x, base, case, options),
},
}
return printIntAny(w, value, base, case, options);
}
/// 通常优先使用 `printInt`,以避免泛型爆炸。不过,若需要针对特定整数类型生成最优代码,也可使用此函数。
///
///
pub fn printIntAny(
w: *Writer,
value: anytype,
base: u8,
case: std.fmt.Case,
options: std.fmt.Options,
) Error!void {
assert(base >= 2);
const value_info = @typeInfo(@TypeOf(value)).int;
// 该类型必须与 `base` 大小相同或更宽,
// 除法才能正常工作
const min_int_bits = comptime @max(value_info.bits, 8);
const MinInt = @Int(.unsigned, min_int_bits);
const abs_value = @abs(value);
// 所需空间的最坏情况为二进制,另加 1 位符号
var buf: [1 + @max(@as(comptime_int, value_info.bits), 1)]u8 = undefined;
var a: MinInt = abs_value;
var index: usize = buf.len;
if (base == 10) {
while (a >= 100) : (a = @divTrunc(a, 100)) {
index -= 2;
buf[index..][0..2].* = std.fmt.digits2(@intCast(a % 100));
}
if (a < 10) {
index -= 1;
buf[index] = '0' + @as(u8, @intCast(a));
} else {
index -= 2;
buf[index..][0..2].* = std.fmt.digits2(@intCast(a));
}
} else {
while (true) {
const digit = a % base;
index -= 1;
buf[index] = std.fmt.digitToChar(@intCast(digit), case);
a /= base;
if (a == 0) break;
}
}
if (value_info.signedness == .signed) {
if (value < 0) {
// 负整数
index -= 1;
buf[index] = '-';
} else if (options.width == null or options.width.? == 0) {
// 正整数,省略正号
} else {
// 正整数
index -= 1;
buf[index] = '+';
}
}
return w.alignBufferOptions(buf[index..], options);
}
pub fn printAsciiChar(w: *Writer, c: u8, options: std.fmt.Options) Error!void {
return w.alignBufferOptions(@as(*const [1]u8, &c), options);
}
pub fn printAscii(w: *Writer, bytes: []const u8, options: std.fmt.Options) Error!void {
return w.alignBufferOptions(bytes, options);
}
pub fn printUnicodeCodepoint(w: *Writer, c: u21) Error!void {
var buf: [4]u8 = undefined;
const len = std.unicode.utf8Encode(c, &buf) catch |err| switch (err) {
error.Utf8CannotEncodeSurrogateHalf, error.CodepointTooLarge => l: {
buf[0..3].* = std.unicode.replacement_character_utf8;
break :l 3;
},
};
return w.writeAll(buf[0..len]);
}
/// 使用较大的栈缓冲区;断言模式为十进制或科学计数法。
pub fn printFloat(w: *Writer, value: anytype, options: std.fmt.Number) Error!void {
const mode: std.fmt.float.Mode = switch (options.mode) {
.decimal => .decimal,
.scientific => .scientific,
.binary, .octal, .hex => unreachable,
};
var buf: [std.fmt.float.bufferSize(.decimal, f64)]u8 = undefined;
const s = std.fmt.float.render(&buf, value, .{
.mode = mode,
.precision = options.precision,
}) catch |err| switch (err) {
error.BufferTooSmall => "(float)",
};
return w.alignBuffer(s, options.width orelse s.len, options.alignment, options.fill);
}
/// 使用较小的栈缓冲区;断言模式不是十进制或科学计数法。
pub fn printFloatHexOptions(w: *Writer, value: anytype, options: std.fmt.Number) Error!void {
var buf: [50]u8 = undefined; // 用于对齐
var sub_writer: Writer = .fixed(&buf);
switch (options.mode) {
.decimal => unreachable,
.scientific => unreachable,
.binary => @panic("TODO"),
.octal => @panic("TODO"),
.hex => {},
}
printFloatHex(&sub_writer, value, options.case, options.precision) catch unreachable; // buf 足够大
const printed = sub_writer.buffered();
return w.alignBuffer(printed, options.width orelse printed.len, options.alignment, options.fill);
}
pub fn printFloatHex(w: *Writer, value: anytype, case: std.fmt.Case, opt_precision: ?usize) Error!void {
const v = switch (@TypeOf(value)) {
// comptime_float 内部为 f128;这可保留精度。
comptime_float => @as(f128, value),
else => value,
};
if (std.math.signbit(v)) try w.writeByte('-');
if (std.math.isNan(v)) return w.writeAll(switch (case) {
.lower => "nan",
.upper => "NAN",
});
if (std.math.isInf(v)) return w.writeAll(switch (case) {
.lower => "inf",
.upper => "INF",
});
const T = @TypeOf(v);
const TU = @Int(.unsigned, @bitSizeOf(T));
const mantissa_bits = std.math.floatMantissaBits(T);
const fractional_bits = std.math.floatFractionalBits(T);
const exponent_bits = std.math.floatExponentBits(T);
const mantissa_mask = (1 << mantissa_bits) - 1;
const exponent_mask = (1 << exponent_bits) - 1;
const exponent_bias = (1 << (exponent_bits - 1)) - 1;
const as_bits: TU = @bitCast(v);
var mantissa = as_bits & mantissa_mask;
var exponent: i32 = @as(u16, @truncate((as_bits >> mantissa_bits) & exponent_mask));
const is_denormal = exponent == 0 and mantissa != 0;
const is_zero = exponent == 0 and mantissa == 0;
if (is_zero) {
// 在此处理该情况,以简化下方逻辑。
try w.writeAll("0x0");
if (opt_precision) |precision| {
if (precision > 0) {
try w.writeAll(".");
try w.splatByteAll('0', precision);
}
} else {
try w.writeAll(".0");
}
try w.writeAll("p0");
return;
}
if (is_denormal) {
// 调整指数以便打印。
exponent += 1;
} else {
if (fractional_bits == mantissa_bits)
mantissa |= 1 << fractional_bits; // 添加隐含的整数位。
}
const mantissa_digits = (fractional_bits + 3) / 4;
// 填零,使小数部分的宽度补齐为 4 的倍数。
mantissa <<= mantissa_digits * 4 - fractional_bits;
if (opt_precision) |precision| {
// 必要时舍入。
if (precision < mantissa_digits) {
// 始终至少有 4 个额外位。
var extra_bits = (mantissa_digits - precision) * 4;
// 结果的最低有效位是保护位;还需要舍入位和粘滞位,以执行舍入。
//
while (extra_bits > 2) {
mantissa = (mantissa >> 1) | (mantissa & 1);
extra_bits -= 1;
}
// 舍入至最近值,中点取偶数。
mantissa |= @intFromBool(mantissa & 0b100 != 0);
mantissa += 1;
// 丢弃多余位。
mantissa >>= 2;
// 恢复对齐。
mantissa <<= @as(std.math.Log2Int(TU), @intCast((mantissa_digits - precision) * 4));
const overflow = mantissa & (1 << 1 + mantissa_digits * 4) != 0;
// 溢出时优先采用规范化结果。
if (overflow) {
mantissa >>= 1;
exponent += 1;
}
}
}
// 小数部分加 1。
var buf: [1 + mantissa_digits]u8 = undefined;
assert(std.fmt.printInt(&buf, mantissa, 16, case, .{ .fill = '0', .width = 1 + mantissa_digits }) == buf.len);
try w.writeAll("0x");
try w.writeByte(buf[0]);
const trimmed = std.mem.trimEnd(u8, buf[1..], "0");
if (opt_precision) |precision| {
if (precision > 0) try w.writeAll(".");
} else if (trimmed.len > 0) {
try w.writeAll(".");
}
try w.writeAll(trimmed);
// 明确请求时添加尾随零。
if (opt_precision) |precision| if (precision > 0) {
if (precision > trimmed.len)
try w.splatByteAll('0', precision - trimmed.len);
};
try w.writeAll("p");
try w.printInt(exponent - exponent_bias, 10, case, .{});
}
pub const ByteSizeUnits = enum {
/// 此格式化器以 1000 的倍数表示数字,使用 SI
/// 计量单位,如 kB、MB、GB 等。
decimal,
/// 此格式化器将数值表示为 1024 的倍数,使用 IEC
/// 计量单位(KiB、MiB、GiB 等)。
binary,
};
/// 当 `value` 小于 1kB 时,忽略格式选项 `precision`
pub fn printByteSize(
w: *Writer,
value: u64,
comptime units: ByteSizeUnits,
options: std.fmt.Options,
) Error!void {
if (value == 0) return w.alignBufferOptions("0B", options);
// 最坏情况需要 32 字节,再加后缀的 3 字节。
var buf: [std.fmt.float.min_buffer_size + 3]u8 = undefined;
const mags_si = " kMGTPEZY";
const mags_iec = " KMGTPEZY";
const log2 = std.math.log2(value);
const base = switch (units) {
.decimal => 1000,
.binary => 1024,
};
const magnitude = switch (units) {
.decimal => @min(log2 / comptime std.math.log2(1000), mags_si.len - 1),
.binary => @min(log2 / 10, mags_iec.len - 1),
};
const new_value = std.math.lossyCast(f64, value) / std.math.pow(f64, std.math.lossyCast(f64, base), std.math.lossyCast(f64, magnitude));
const suffix = switch (units) {
.decimal => mags_si[magnitude],
.binary => mags_iec[magnitude],
};
const s = switch (magnitude) {
0 => buf[0..std.fmt.printInt(&buf, value, 10, .lower, .{})],
else => std.fmt.float.render(&buf, new_value, .{ .mode = .decimal, .precision = options.precision }) catch |err| switch (err) {
error.BufferTooSmall => unreachable,
},
};
var i: usize = s.len;
if (suffix == ' ') {
buf[i] = 'B';
i += 1;
} else switch (units) {
.decimal => {
buf[i..][0..2].* = [_]u8{ suffix, 'B' };
i += 2;
},
.binary => {
buf[i..][0..3].* = [_]u8{ suffix, 'i', 'B' };
i += 3;
},
}
return w.alignBufferOptions(buf[0..i], options);
}
// 此 ANY 常量用于绕过:https://github.com/ziglang/zig/issues/7948
const ANY = "any";
fn stripOptionalOrErrorUnionSpec(comptime fmt: []const u8) []const u8 {
return if (std.mem.eql(u8, fmt[1..], ANY))
ANY
else
fmt[1..];
}
pub fn invalidFmtError(comptime fmt: []const u8, value: anytype) noreturn {
@compileError("invalid format string '" ++ fmt ++ "' for type '" ++ @typeName(@TypeOf(value)) ++ "'");
}
pub fn printHex(w: *Writer, bytes: []const u8, case: std.fmt.Case) Error!void {
const charset = switch (case) {
.upper => "0123456789ABCDEF",
.lower => "0123456789abcdef",
};
for (bytes) |c| {
try w.writeByte(charset[c >> 4]);
try w.writeByte(charset[c & 15]);
}
}
pub fn printBase64(w: *Writer, bytes: []const u8) Error!void {
var chunker = std.mem.window(u8, bytes, 3, 3);
var temp: [5]u8 = undefined;
while (chunker.next()) |chunk| {
try w.writeAll(std.base64.standard.Encoder.encode(&temp, chunk));
}
}
/// 以 LEB128 格式向指定写入器写入一个无符号整数。
pub fn writeUleb128(w: *Writer, value: anytype) Error!void {
try w.writeLeb128(switch (@typeInfo(@TypeOf(value))) {
.comptime_int => @as(std.math.IntFittingRange(0, @abs(value)), value),
.int => |value_info| switch (value_info.signedness) {
.signed => @as(@Int(.unsigned, value_info.bits -| 1), @intCast(value)),
.unsigned => value,
},
else => comptime unreachable,
});
}
/// 将单个有符号整数以 LEB128 写入给定写入器。
pub fn writeSleb128(w: *Writer, value: anytype) Error!void {
try w.writeLeb128(switch (@typeInfo(@TypeOf(value))) {
.comptime_int => @as(std.math.IntFittingRange(@min(value, -1), @max(0, value)), value),
.int => |value_info| switch (value_info.signedness) {
.signed => value,
.unsigned => @as(@Int(.signed, value_info.bits + 1), value),
},
else => comptime unreachable,
});
}
/// 将单个整数以 LEB128 写入给定写入器。
pub fn writeLeb128(w: *Writer, value: anytype) Error!void {
const T = @TypeOf(value);
const info = switch (@typeInfo(T)) {
.int => |info| info,
else => @compileError(@typeName(T) ++ " not supported"),
};
const BoundInt = @Int(info.signedness, 7);
if (info.bits <= 7 or (value >= std.math.minInt(BoundInt) and value <= std.math.maxInt(BoundInt))) {
const Bits = @Int(info.signedness, 8);
const byte = switch (info.signedness) {
.signed => @as(Bits, @intCast(value)) & 0x7F,
.unsigned => @as(Bits, @intCast(value)),
};
try w.writeByte(@bitCast(byte));
return;
}
const Byte = packed struct { bits: u7, more: bool };
const Int = std.math.ByteAlignedInt(T);
const max_bytes = @divFloor(info.bits - 1, 7) + 1;
const sign_value = value >> (info.bits - 1);
var val: Int = value;
for (0..max_bytes) |_| {
const more = switch (info.signedness) {
.signed => val >> 6 != sign_value,
.unsigned => val > std.math.maxInt(u7),
};
try w.writeByte(@bitCast(@as(Byte, .{
.bits = @intCast(val & 0x7F),
.more = more,
})));
if (!more) return;
val >>= 7;
} else unreachable;
}
test "serialize signed LEB128" {
// 较小的值
try testLeb128Encoding(i7, 9, "\x09");
try testLeb128Encoding(i64, 125, "\xFD\x00");
try testLeb128Encoding(i7, -34, "\x5E");
try testLeb128Encoding(i64, -3, "\x7D");
// 随机值
try testLeb128Encoding(i16, 19373, "\xAD\x97\x01");
try testLeb128Encoding(i32, 1628839242, "\xCA\xBA\xD8\x88\x06");
try testLeb128Encoding(i64, 3789169920125966546, "\xD2\xB1\xD0\xD5\xF6\xBE\xF5\xCA\x34");
try testLeb128Encoding(i128, 704622239050934257305893323522763588, "\xC4\xD6\x83\xC7\xE3\x91\x95\xC3\x96\x80\x8D\xA5\xF5\xDF\xA3\xDA\x87\x01");
try testLeb128Encoding(i16, -14558, "\xA2\x8E\x7F");
try testLeb128Encoding(i32, -1702738165, "\x8B\x8E\x89\xD4\x79");
try testLeb128Encoding(i64, -1709126996960612298, "\xB6\xE0\x87\xB1\xD3\xC1\xFD\xA3\x68");
try testLeb128Encoding(i128, -113498719181566012704681230050325944039, "\x99\xD2\x80\xBC\xE6\x95\xBC\xC8\xDE\xB4\x9D\x81\x9F\xCA\xC6\xF8\x9C\xD5\x7E");
// {min,max} 值
try testLeb128Encoding(i16, std.math.maxInt(i16), "\xFF\xFF\x01");
try testLeb128Encoding(i32, std.math.maxInt(i32), "\xFF\xFF\xFF\xFF\x07");
try testLeb128Encoding(i64, std.math.maxInt(i64), "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x00");
try testLeb128Encoding(i128, std.math.maxInt(i128), "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01");
try testLeb128Encoding(i16, std.math.minInt(i16), "\x80\x80\x7E");
try testLeb128Encoding(i32, std.math.minInt(i32), "\x80\x80\x80\x80\x78");
try testLeb128Encoding(i64, std.math.minInt(i64), "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x7F");
try testLeb128Encoding(i128, std.math.minInt(i128), "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x80\x7E");
// 特定情况
try testLeb128Encoding(i8, 0, "\x00");
try testLeb128Encoding(i2, -1, "\x7F");
try testLeb128Encoding(i8, -1, "\x7F");
try testLeb128Encoding(i2, 1, "\x01");
try testLeb128Encoding(i8, 1, "\x01");
// 编码字节边界
try testLeb128Encoding(i7, std.math.maxInt(i7), "\x3F");
try testLeb128Encoding(i8, std.math.maxInt(i7) + 1, "\xC0\x00");
try testLeb128Encoding(i14, std.math.maxInt(i14), "\xFF\x3F");
try testLeb128Encoding(i15, std.math.maxInt(i14) + 1, "\x80\xC0\x00");
try testLeb128Encoding(i49, std.math.maxInt(i49), "\xFF\xFF\xFF\xFF\xFF\xFF\x3F");
try testLeb128Encoding(i50, std.math.maxInt(i49) + 1, "\x80\x80\x80\x80\x80\x80\xC0\x00");
try testLeb128Encoding(i56, std.math.maxInt(i56), "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x3F");
try testLeb128Encoding(i57, std.math.maxInt(i56) + 1, "\x80\x80\x80\x80\x80\x80\x80\xC0\x00");
try testLeb128Encoding(i63, std.math.maxInt(i63), "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x3F");
try testLeb128Encoding(i64, std.math.maxInt(i63) + 1, "\x80\x80\x80\x80\x80\x80\x80\x80\xC0\x00");
try testLeb128Encoding(i7, std.math.minInt(i7), "\x40");
try testLeb128Encoding(i8, std.math.minInt(i7) - 1, "\xBF\x7F");
try testLeb128Encoding(i14, std.math.minInt(i14), "\x80\x40");
try testLeb128Encoding(i15, std.math.minInt(i14) - 1, "\xFF\xBF\x7F");
try testLeb128Encoding(i49, std.math.minInt(i49), "\x80\x80\x80\x80\x80\x80\x40");
try testLeb128Encoding(i50, std.math.minInt(i49) - 1, "\xFF\xFF\xFF\xFF\xFF\xFF\xBF\x7F");
try testLeb128Encoding(i56, std.math.minInt(i56), "\x80\x80\x80\x80\x80\x80\x80\x40");
try testLeb128Encoding(i57, std.math.minInt(i56) - 1, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xBF\x7F");
try testLeb128Encoding(i63, std.math.minInt(i63), "\x80\x80\x80\x80\x80\x80\x80\x80\x40");
try testLeb128Encoding(i64, std.math.minInt(i63) - 1, "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xBF\x7F");
}
test "serialize unsigned LEB128" {
// 较小的值
try testLeb128Encoding(u7, 12, "\x0C");
try testLeb128Encoding(u64, 201, "\xC9\x01");
// 随机值
try testLeb128Encoding(u8, 254, "\xFE\x01");
try testLeb128Encoding(u16, 30241, "\xA1\xEC\x01");
try testLeb128Encoding(u32, 2173531193, "\xB9\xE8\xB5\x8C\x08");
try testLeb128Encoding(u64, 18321125691115744902, "\x86\xDD\xF2\x81\xF2\xD7\xED\xA0\xFE\x01");
try testLeb128Encoding(u128, 122619209508942982841456325819614676193, "\xE1\x89\xF3\xD9\xE3\xAD\xEC\xF4\x98\x95\xF8\xBB\xD7\xB8\xF2\xCC\xBF\xB8\x01");
// 最大值
try testLeb128Encoding(u8, std.math.maxInt(u8), "\xFF\x01");
try testLeb128Encoding(u16, std.math.maxInt(u16), "\xFF\xFF\x03");
try testLeb128Encoding(u32, std.math.maxInt(u32), "\xFF\xFF\xFF\xFF\x0F");
try testLeb128Encoding(u64, std.math.maxInt(u64), "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x01");
try testLeb128Encoding(u128, std.math.maxInt(u128), "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x03");
// 特定情况
try testLeb128Encoding(u0, 0, "\x00");
try testLeb128Encoding(u1, 0, "\x00");
try testLeb128Encoding(u8, 0, "\x00");
try testLeb128Encoding(u1, 1, "\x01");
try testLeb128Encoding(u8, 1, "\x01");
// 编码字节边界
try testLeb128Encoding(u7, std.math.maxInt(u7), "\x7F");
try testLeb128Encoding(u8, std.math.maxInt(u7) + 1, "\x80\x01");
try testLeb128Encoding(u14, std.math.maxInt(u14), "\xFF\x7F");
try testLeb128Encoding(u15, std.math.maxInt(u14) + 1, "\x80\x80\x01");
try testLeb128Encoding(u49, std.math.maxInt(u49), "\xFF\xFF\xFF\xFF\xFF\xFF\x7F");
try testLeb128Encoding(u50, std.math.maxInt(u49) + 1, "\x80\x80\x80\x80\x80\x80\x80\x01");
try testLeb128Encoding(u56, std.math.maxInt(u56), "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x7F");
try testLeb128Encoding(u57, std.math.maxInt(u56) + 1, "\x80\x80\x80\x80\x80\x80\x80\x80\x01");
try testLeb128Encoding(u63, std.math.maxInt(u63), "\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x7F");
try testLeb128Encoding(u64, std.math.maxInt(u63) + 1, "\x80\x80\x80\x80\x80\x80\x80\x80\x80\x01");
}
fn testLeb128Encoding(comptime T: type, value: T, encoding: []const u8) !void {
const info = @typeInfo(T).int;
const max_bytes = @divFloor(info.bits -| 1, 7) + 1;
var bytes: [max_bytes]u8 = undefined;
var fw: Writer = .fixed(&bytes);
try writeLeb128(&fw, value);
try std.testing.expectEqualSlices(u8, encoding, fw.buffered());
}
test "printValue max_depth" {
const Vec2 = struct {
const SelfType = @This();
x: f32,
y: f32,
pub fn format(self: SelfType, w: *Writer) Error!void {
return w.print("({d:.3},{d:.3})", .{ self.x, self.y });
}
};
const E = enum {
One,
Two,
Three,
};
const TU = union(enum) {
const SelfType = @This();
float: f32,
int: u32,
ptr: ?*SelfType,
};
const S = struct {
const SelfType = @This();
a: ?*SelfType,
tu: TU,
e: E,
vec: Vec2,
};
var inst = S{
.a = null,
.tu = TU{ .ptr = null },
.e = E.Two,
.vec = Vec2{ .x = 10.2, .y = 2.22 },
};
inst.a = &inst;
inst.tu.ptr = &inst.tu;
var buf: [1000]u8 = undefined;
var w: Writer = .fixed(&buf);
try w.printValue("", .{}, inst, 0);
try testing.expectEqualStrings(".{ ... }", w.buffered());
w = .fixed(&buf);
try w.printValue("", .{}, inst, 1);
try testing.expectEqualStrings(".{ .a = .{ ... }, .tu = .{ ... }, .e = .Two, .vec = .{ ... } }", w.buffered());
w = .fixed(&buf);
try w.printValue("", .{}, inst, 2);
try testing.expectEqualStrings(".{ .a = .{ .a = .{ ... }, .tu = .{ ... }, .e = .Two, .vec = .{ ... } }, .tu = .{ .ptr = .{ ... } }, .e = .Two, .vec = .{ .x = 10.2, .y = 2.22 } }", w.buffered());
w = .fixed(&buf);
try w.printValue("", .{}, inst, 3);
try testing.expectEqualStrings(".{ .a = .{ .a = .{ .a = .{ ... }, .tu = .{ ... }, .e = .Two, .vec = .{ ... } }, .tu = .{ .ptr = .{ ... } }, .e = .Two, .vec = .{ .x = 10.2, .y = 2.22 } }, .tu = .{ .ptr = .{ .ptr = .{ ... } } }, .e = .Two, .vec = .{ .x = 10.2, .y = 2.22 } }", w.buffered());
const vec: @Vector(4, i32) = .{ 1, 2, 3, 4 };
w = .fixed(&buf);
try w.printValue("", .{}, vec, 0);
try testing.expectEqualStrings("{ ... }", w.buffered());
w = .fixed(&buf);
try w.printValue("", .{}, vec, 1);
try testing.expectEqualStrings("{ 1, 2, 3, 4 }", w.buffered());
}
test printInt {
try testPrintIntCase("-1", @as(i1, -1), 10, .lower, .{});
try testPrintIntCase("-101111000110000101001110", @as(i32, -12345678), 2, .lower, .{});
try testPrintIntCase("-12345678", @as(i32, -12345678), 10, .lower, .{});
try testPrintIntCase("-bc614e", @as(i32, -12345678), 16, .lower, .{});
try testPrintIntCase("-BC614E", @as(i32, -12345678), 16, .upper, .{});
try testPrintIntCase("12345678", @as(u32, 12345678), 10, .upper, .{});
try testPrintIntCase(" 666", @as(u32, 666), 10, .lower, .{ .width = 6 });
try testPrintIntCase(" 1234", @as(u32, 0x1234), 16, .lower, .{ .width = 6 });
try testPrintIntCase("1234", @as(u32, 0x1234), 16, .lower, .{ .width = 1 });
try testPrintIntCase("+42", @as(i32, 42), 10, .lower, .{ .width = 3 });
try testPrintIntCase("-42", @as(i32, -42), 10, .lower, .{ .width = 3 });
try testPrintIntCase("123456789123456789", @as(comptime_int, 123456789123456789), 10, .lower, .{});
}
test "printFloat with comptime_float" {
var buf: [20]u8 = undefined;
var w: Writer = .fixed(&buf);
try w.printFloat(@as(comptime_float, 1.0), std.fmt.Options.toNumber(.{}, .scientific, .lower));
try testing.expectEqualStrings(w.buffered(), "1e0");
try testing.expectFmt("1", "{}", .{1.0});
}
test "{q} format string" {
const data: []const u8 = "i\tlike\"cheese\x00\x05cheese";
try testing.expectFmt("hello \"i\\tlike\\\"cheese\\x00\\x05cheese\" world", "hello {q} world", .{data});
}
test "{qf} format string" {
const data: []const u8 = "😎";
try testing.expectFmt("hello \"@\\\"😎\\\"\" world", "hello {qf} world", .{std.zig.fmtId(data)});
}
fn testPrintIntCase(expected: []const u8, value: anytype, base: u8, case: std.fmt.Case, options: std.fmt.Options) !void {
var buffer: [100]u8 = undefined;
var w: Writer = .fixed(&buffer);
try w.printInt(value, base, case, options);
try testing.expectEqualStrings(expected, w.buffered());
}
test printByteSize {
try testing.expectFmt("file size: 42B\n", "file size: {B}\n", .{42});
try testing.expectFmt("file size: 42B\n", "file size: {Bi}\n", .{42});
try testing.expectFmt("file size: 63MB\n", "file size: {B}\n", .{63 * 1000 * 1000});
try testing.expectFmt("file size: 63MiB\n", "file size: {Bi}\n", .{63 * 1024 * 1024});
try testing.expectFmt("file size: 42B\n", "file size: {B:.2}\n", .{42});
try testing.expectFmt("file size: 42B\n", "file size: {B:>9.2}\n", .{42});
try testing.expectFmt("file size: 66.06MB\n", "file size: {B:.2}\n", .{63 * 1024 * 1024});
try testing.expectFmt("file size: 60.08MiB\n", "file size: {Bi:.2}\n", .{63 * 1000 * 1000});
try testing.expectFmt("file size: =66.06MB=\n", "file size: {B:=^9.2}\n", .{63 * 1024 * 1024});
try testing.expectFmt("file size: 66.06MB\n", "file size: {B: >9.2}\n", .{63 * 1024 * 1024});
try testing.expectFmt("file size: 66.06MB \n", "file size: {B: <9.2}\n", .{63 * 1024 * 1024});
try testing.expectFmt("file size: 0.01844674407370955ZB\n", "file size: {B}\n", .{std.math.maxInt(u64)});
}
test "bytes.hex" {
const some_bytes = "\xCA\xFE\xBA\xBE";
try testing.expectFmt("lowercase: cafebabe\n", "lowercase: {x}\n", .{some_bytes});
try testing.expectFmt("uppercase: CAFEBABE\n", "uppercase: {X}\n", .{some_bytes});
try testing.expectFmt("uppercase: CAFE\n", "uppercase: {X}\n", .{some_bytes[0..2]});
try testing.expectFmt("lowercase: babe\n", "lowercase: {x}\n", .{some_bytes[2..]});
const bytes_with_zeros = "\x00\x0E\xBA\xBE";
try testing.expectFmt("lowercase: 000ebabe\n", "lowercase: {x}\n", .{bytes_with_zeros});
}
test "padding" {
const foo: enum { foo } = .foo;
try testing.expectFmt("tag: |foo |\n", "tag: |{t:<4}|\n", .{foo});
const bar: error{bar} = error.bar;
try testing.expectFmt("error: |bar |\n", "error: |{t:<4}|\n", .{bar});
}
test fixed {
{
var buf: [255]u8 = undefined;
var w: Writer = .fixed(&buf);
try w.print("{s}{s}!", .{ "Hello", "World" });
try testing.expectEqualStrings("HelloWorld!", w.buffered());
}
comptime {
var buf: [255]u8 = undefined;
var w: Writer = .fixed(&buf);
try w.print("{s}{s}!", .{ "Hello", "World" });
try testing.expectEqualStrings("HelloWorld!", w.buffered());
}
}
test "fixed output" {
var buffer: [10]u8 = undefined;
var w: Writer = .fixed(&buffer);
try w.writeAll("Hello");
try testing.expect(std.mem.eql(u8, w.buffered(), "Hello"));
try w.writeAll("world");
try testing.expect(std.mem.eql(u8, w.buffered(), "Helloworld"));
try testing.expectError(error.WriteFailed, w.writeAll("!"));
try testing.expect(std.mem.eql(u8, w.buffered(), "Helloworld"));
w = .fixed(&buffer);
try testing.expect(w.buffered().len == 0);
try testing.expectError(error.WriteFailed, w.writeAll("Hello world!"));
try testing.expect(std.mem.eql(u8, w.buffered(), "Hello worl"));
}
test "writeSplat 0 len splat larger than capacity" {
var buf: [8]u8 = undefined;
var w: Writer = .fixed(&buf);
const n = try w.writeSplat(&.{"something that overflows buf"}, 0);
try testing.expectEqual(0, n);
}
pub fn failingDrain(w: *Writer, data: []const []const u8, splat: usize) Error!usize {
_ = w;
_ = data;
_ = splat;
return error.WriteFailed;
}
pub fn failingSendFile(w: *Writer, file_reader: *File.Reader, limit: Limit) FileError!usize {
_ = w;
_ = file_reader;
_ = limit;
return error.WriteFailed;
}
pub fn failingRebase(w: *Writer, preserve: usize, capacity: usize) Error!void {
_ = w;
_ = preserve;
_ = capacity;
return error.WriteFailed;
}
pub const Discarding = struct {
count: u64,
writer: Writer,
pub fn init(buffer: []u8) Discarding {
return .{
.count = 0,
.writer = .{
.vtable = &.{
.drain = Discarding.drain,
.sendFile = Discarding.sendFile,
},
.buffer = buffer,
},
};
}
/// 包含缓冲的数据(无需刷新)。
pub fn fullCount(d: *const Discarding) u64 {
return d.count + d.writer.end;
}
pub fn drain(w: *Writer, data: []const []const u8, splat: usize) Error!usize {
const d: *Discarding = @alignCast(@fieldParentPtr("writer", w));
const slice = data[0 .. data.len - 1];
const pattern = data[slice.len];
var written: usize = pattern.len * splat;
for (slice) |bytes| written += bytes.len;
d.count += w.end + written;
w.end = 0;
return written;
}
pub fn sendFile(w: *Writer, file_reader: *File.Reader, limit: Limit) FileError!usize {
if (File.Handle == void) return error.Unimplemented;
const d: *Discarding = @alignCast(@fieldParentPtr("writer", w));
d.count += w.end;
w.end = 0;
if (limit == .nothing) return 0;
if (file_reader.getSize()) |size| {
const n = limit.minInt64(size - file_reader.pos);
if (n == 0) return error.EndOfStream;
file_reader.seekBy(@intCast(n)) catch return error.Unimplemented;
w.end = 0;
d.count += n;
return n;
} else |_| {
// 可以在 `file_reader` 实例上观察到该错误,
// 此时更适合将文件视为管道。
return error.Unimplemented;
}
}
};
/// 通过移动缓冲区内容,从 `buffer` 移除前 `n` 字节;
/// 若整个缓冲区已被消费,返回其后仍剩余的字节数,
/// 否则返回零。
///
/// 可用于 `VTable.drain` 函数实现,以实现部分
/// 排空。
pub fn consume(w: *Writer, n: usize) usize {
if (n < w.end) {
const remaining = w.buffer[n..w.end];
@memmove(w.buffer[0..remaining.len], remaining);
w.end = remaining.len;
return 0;
}
defer w.end = 0;
return n - w.end;
}
/// 将 `end` 设为零并返回零的快捷操作。
/// 等价于以 `end` 为参数调用 `consume`。
pub fn consumeAll(w: *Writer) usize {
w.end = 0;
return 0;
}
/// 当 `Writer` 实现无法提供比对文件执行基本
/// 读写循环更高效的实现时使用。
pub fn unimplementedSendFile(w: *Writer, file_reader: *File.Reader, limit: Limit) FileError!usize {
_ = w;
_ = file_reader;
_ = limit;
return error.Unimplemented;
}
/// 调用此函数通常意味着缓冲区已满,因此
/// 应当返回错误。但仍需确保所有
/// 可用缓冲区都已填满。此外,也可能从 `flush` 调用此函数,
/// 此时应成功返回。
pub fn fixedDrain(w: *Writer, data: []const []const u8, splat: usize) Error!usize {
if (data.len == 0) return 0;
for (data[0 .. data.len - 1]) |bytes| {
const dest = w.buffer[w.end..];
const len = @min(bytes.len, dest.len);
@memcpy(dest[0..len], bytes[0..len]);
w.end += len;
if (bytes.len > dest.len) return error.WriteFailed;
}
const pattern = data[data.len - 1];
const dest = w.buffer[w.end..];
switch (pattern.len) {
0 => return 0,
1 => {
assert(splat >= dest.len);
@memset(dest, pattern[0]);
w.end += dest.len;
return error.WriteFailed;
},
else => {
for (0..splat) |i| {
const remaining = dest[i * pattern.len ..];
const len = @min(pattern.len, remaining.len);
@memcpy(remaining[0..len], pattern[0..len]);
w.end += len;
if (pattern.len > remaining.len) return error.WriteFailed;
}
unreachable;
},
}
}
pub fn unreachableDrain(w: *Writer, data: []const []const u8, splat: usize) Error!usize {
_ = w;
_ = data;
_ = splat;
unreachable;
}
pub fn unreachableRebase(w: *Writer, preserve: usize, capacity: usize) Error!void {
_ = w;
_ = preserve;
_ = capacity;
unreachable;
}
pub fn fromArrayList(array_list: *ArrayList(u8)) Writer {
defer array_list.* = .empty;
array_list.pointer_stability.assertUnlocked();
return .{
.vtable = &.{
.drain = fixedDrain,
.flush = noopFlush,
.rebase = failingRebase,
},
.buffer = array_list.allocatedSlice(),
.end = array_list.items.len,
};
}
pub fn toArrayList(w: *Writer) ArrayList(u8) {
const result: ArrayList(u8) = .{
.items = w.buffer[0..w.end],
.capacity = w.buffer.len,
.pointer_stability = .{},
};
w.buffer = &.{};
w.end = 0;
return result;
}
/// 提供基于调用 `Hasher.update` 的 `Writer` 实现,同时将
/// 所有数据发送到底层 `Writer`。
///
/// 使用时,底层写入器最好不设缓冲,因为所有
/// 写入都会直接转发给它。
///
/// 由于实现需要通用性,其缓冲策略
/// 并非最优。更好的方案是为每个哈希函数
/// 创建写入器,使重复写入缓冲区能够针对哈希实现的
/// 细节定制。
///
/// 可与终结流处理管线的 `Hashing` 对照。
pub fn Hashed(comptime Hasher: type) type {
return struct {
out: *Writer,
hasher: Hasher,
writer: Writer,
pub fn init(out: *Writer, buffer: []u8) @This() {
return .initHasher(out, .{}, buffer);
}
pub fn initHasher(out: *Writer, hasher: Hasher, buffer: []u8) @This() {
return .{
.out = out,
.hasher = hasher,
.writer = .{
.buffer = buffer,
.vtable = &.{ .drain = @This().drain },
},
};
}
fn drain(w: *Writer, data: []const []const u8, splat: usize) Error!usize {
const this: *@This() = @alignCast(@fieldParentPtr("writer", w));
const aux = w.buffered();
const aux_n = try this.out.writeSplatHeader(aux, data, splat);
if (aux_n < w.end) {
this.hasher.update(w.buffer[0..aux_n]);
const remaining = w.buffer[aux_n..w.end];
@memmove(w.buffer[0..remaining.len], remaining);
w.end = remaining.len;
return 0;
}
this.hasher.update(aux);
const n = aux_n - w.end;
w.end = 0;
var remaining: usize = n;
for (data[0 .. data.len - 1]) |slice| {
if (remaining <= slice.len) {
this.hasher.update(slice[0..remaining]);
return n;
}
remaining -= slice.len;
this.hasher.update(slice);
}
const pattern = data[data.len - 1];
assert(remaining <= splat * pattern.len);
switch (pattern.len) {
0 => {
assert(remaining == 0);
},
1 => {
var buffer: [64]u8 = undefined;
@memset(&buffer, pattern[0]);
while (remaining > 0) {
const update_len = @min(remaining, buffer.len);
this.hasher.update(buffer[0..update_len]);
remaining -= update_len;
}
},
else => {
while (remaining > 0) {
const update_len = @min(remaining, pattern.len);
this.hasher.update(pattern[0..update_len]);
remaining -= update_len;
}
},
}
return n;
}
};
}
/// 提供 `Writer` 实现,基于调用 `Hasher.update`,并丢弃全部数据。
///
/// 由于采用通用实现,此实现的缓冲决策并非最优。更好的方案是为每个哈希函数单独创建写入器,使重复写入缓冲区能够根据哈希实现细节调整。
///
/// 已写入的总字节数保存在 `hasher` 中。
///
/// 对比 `Hashed`,后者还会将数据传给底层流。
///
///
///
///
pub fn Hashing(comptime Hasher: type) type {
return struct {
hasher: Hasher,
writer: Writer,
pub fn init(buffer: []u8) @This() {
return .initHasher(.init(.{}), buffer);
}
pub fn initHasher(hasher: Hasher, buffer: []u8) @This() {
return .{
.hasher = hasher,
.writer = .{
.buffer = buffer,
.vtable = &.{ .drain = @This().drain },
},
};
}
fn drain(w: *Writer, data: []const []const u8, splat: usize) Error!usize {
const this: *@This() = @alignCast(@fieldParentPtr("writer", w));
this.hasher.update(w.buffered());
w.end = 0;
var n: usize = 0;
for (data[0 .. data.len - 1]) |slice| {
this.hasher.update(slice);
n += slice.len;
}
for (0..splat) |_| this.hasher.update(data[data.len - 1]);
return n + splat * data[data.len - 1].len;
}
};
}
/// 维护 `Writer` 状态,使其写入数组列表的未使用容量,在完全填满后才通过虚函数表调用,触发扩容。
/// 因此,格式化输出等使用 `Writer` 的相同优化非泛型机器码,在使用此接口时会走热点路径。
///
/// 使用此接口时,无需调用 `flush`。
///
///
///
pub const Allocating = struct {
allocator: Allocator,
writer: Writer,
alignment: std.mem.Alignment,
pub fn init(allocator: Allocator) Allocating {
return .initAligned(allocator, .of(u8));
}
pub fn initAligned(allocator: Allocator, alignment: std.mem.Alignment) Allocating {
return .{
.allocator = allocator,
.writer = .{
.buffer = &.{},
.vtable = &vtable,
},
.alignment = alignment,
};
}
pub fn initCapacity(allocator: Allocator, capacity: usize) error{OutOfMemory}!Allocating {
return .{
.allocator = allocator,
.writer = .{
.buffer = if (capacity == 0)
&.{}
else
(allocator.rawAlloc(capacity, .of(u8), @returnAddress()) orelse
return error.OutOfMemory)[0..capacity],
.vtable = &vtable,
},
.alignment = .of(u8),
};
}
pub fn initOwnedSlice(allocator: Allocator, slice: []u8) Allocating {
return initOwnedSliceAligned(allocator, .of(u8), slice);
}
pub fn initOwnedSliceAligned(
allocator: Allocator,
comptime alignment: std.mem.Alignment,
slice: []align(alignment.toByteUnits()) u8,
) Allocating {
return .{
.allocator = allocator,
.writer = .{
.buffer = slice,
.vtable = &vtable,
},
.alignment = alignment,
};
}
/// 将 `array_list` 替换为空列表,并取得其内存所有权。
pub fn fromArrayList(allocator: Allocator, array_list: *ArrayList(u8)) Allocating {
return fromArrayListAligned(allocator, .of(u8), array_list);
}
/// 将 `array_list` 替换为空列表,并取得其内存所有权。
pub fn fromArrayListAligned(
allocator: Allocator,
comptime alignment: std.mem.Alignment,
array_list: *std.array_list.Aligned(u8, alignment),
) Allocating {
defer array_list.* = .empty;
return .{
.allocator = allocator,
.writer = .{
.vtable = &vtable,
.buffer = array_list.allocatedSlice(),
.end = array_list.items.len,
},
.alignment = alignment,
};
}
const vtable: VTable = .{
.drain = Allocating.drain,
.sendFile = Allocating.sendFile,
.flush = noopFlush,
.rebase = growingRebase,
};
pub fn deinit(a: *Allocating) void {
if (a.writer.buffer.len == 0) return;
a.allocator.rawFree(a.writer.buffer, a.alignment, @returnAddress());
a.* = undefined;
}
/// 返回取得已分配内存所有权的数组列表。
/// 将 `Allocating` 重置为空状态。
pub fn toArrayList(a: *Allocating) ArrayList(u8) {
return toArrayListAligned(a, .of(u8));
}
/// 返回取得已分配内存所有权的数组列表。
/// 将 `Allocating` 重置为空状态。
pub fn toArrayListAligned(
a: *Allocating,
comptime alignment: std.mem.Alignment,
) std.array_list.Aligned(u8, alignment) {
assert(a.alignment == alignment); // 确保 Allocator 实现正确性的必要条件。
const w = &a.writer;
const result: std.array_list.Aligned(u8, alignment) = .{
.items = @alignCast(w.buffer[0..w.end]),
.capacity = w.buffer.len,
.pointer_stability = .{},
};
w.buffer = &.{};
w.end = 0;
return result;
}
pub fn ensureUnusedCapacity(a: *Allocating, additional_count: usize) Allocator.Error!void {
const new_capacity = std.math.add(usize, a.writer.end, additional_count) catch return error.OutOfMemory;
return ensureTotalCapacity(a, new_capacity);
}
pub fn ensureTotalCapacity(a: *Allocating, new_capacity: usize) Allocator.Error!void {
// 防止无必要的增长,因为 better_capacity 会更大。
if (a.writer.buffer.len >= new_capacity) return;
const better_capacity = ArrayList(u8).growCapacity(new_capacity);
return ensureTotalCapacityPrecise(a, better_capacity);
}
pub fn ensureTotalCapacityPrecise(a: *Allocating, new_capacity: usize) Allocator.Error!void {
const old_memory = a.writer.buffer;
if (old_memory.len >= new_capacity) return;
assert(new_capacity != 0);
const alignment = a.alignment;
if (old_memory.len > 0) {
if (a.allocator.rawRemap(old_memory, alignment, new_capacity, @returnAddress())) |new| {
a.writer.buffer = new[0..new_capacity];
return;
}
}
const new_memory = (a.allocator.rawAlloc(new_capacity, alignment, @returnAddress()) orelse
return error.OutOfMemory)[0..new_capacity];
const saved = old_memory[0..a.writer.end];
@memcpy(new_memory[0..saved.len], saved);
if (old_memory.len != 0) a.allocator.rawFree(old_memory, alignment, @returnAddress());
a.writer.buffer = new_memory;
}
pub fn toOwnedSlice(a: *Allocating) Allocator.Error![]u8 {
const old_memory = a.writer.buffer;
const alignment = a.alignment;
const buffered_len = a.writer.end;
if (old_memory.len > 0) {
if (buffered_len == 0) {
a.allocator.rawFree(old_memory, alignment, @returnAddress());
a.writer.buffer = &.{};
a.writer.end = 0;
return old_memory[0..0];
} else if (a.allocator.rawRemap(old_memory, alignment, buffered_len, @returnAddress())) |new| {
a.writer.buffer = &.{};
a.writer.end = 0;
return new[0..buffered_len];
}
}
if (buffered_len == 0)
return a.writer.buffer[0..0];
const new_memory = (a.allocator.rawAlloc(buffered_len, alignment, @returnAddress()) orelse
return error.OutOfMemory)[0..buffered_len];
@memcpy(new_memory, old_memory[0..buffered_len]);
if (old_memory.len != 0) a.allocator.rawFree(old_memory, alignment, @returnAddress());
a.writer.buffer = &.{};
a.writer.end = 0;
return new_memory;
}
pub fn toOwnedSliceSentinel(a: *Allocating, comptime sentinel: u8) Allocator.Error![:sentinel]u8 {
// 此加法不可能溢出,因为 `a.writer.buffer` 不可能占据整个地址空间。
try ensureTotalCapacityPrecise(a, a.writer.end + 1);
a.writer.buffer[a.writer.end] = sentinel;
a.writer.end += 1;
errdefer a.writer.end -= 1;
const result = try toOwnedSlice(a);
return result[0 .. result.len - 1 :sentinel];
}
pub fn written(a: *Allocating) []u8 {
return a.writer.buffered();
}
pub fn shrinkRetainingCapacity(a: *Allocating, new_len: usize) void {
a.writer.end = new_len;
}
pub fn clearRetainingCapacity(a: *Allocating) void {
a.shrinkRetainingCapacity(0);
}
fn drain(w: *Writer, data: []const []const u8, splat: usize) Error!usize {
const a: *Allocating = @fieldParentPtr("writer", w);
assert(data.len != 0);
const count = countSplat(data, splat);
a.ensureUnusedCapacity(count + 1) catch return error.WriteFailed;
for (data[0 .. data.len - 1]) |bytes| {
@memcpy(a.writer.buffer[a.writer.end..][0..bytes.len], bytes);
a.writer.end += bytes.len;
}
const pattern = data[data.len - 1];
switch (pattern.len) {
0 => {},
1 => {
@memset(a.writer.buffer[a.writer.end..][0..splat], pattern[0]);
a.writer.end += splat;
},
else => for (0..splat) |_| {
@memcpy(a.writer.buffer[a.writer.end..][0..pattern.len], pattern);
a.writer.end += pattern.len;
},
}
return count;
}
fn sendFile(w: *Writer, file_reader: *File.Reader, limit: Limit) FileError!usize {
if (File.Handle == void) return error.Unimplemented;
if (limit == .nothing) return 0;
const a: *Allocating = @fieldParentPtr("writer", w);
const pos = file_reader.logicalPos();
const additional, const exact = if (file_reader.getSize()) |size|
.{ size - pos, true }
else |_|
.{ std.atomic.cache_line, false };
if (additional == 0) return error.EndOfStream;
a.ensureUnusedCapacity(limit.minInt64(additional)) catch return error.WriteFailed;
const buffer = a.writer.buffer[a.writer.end..];
const dest = if (exact) buffer[0..limit.minInt64(additional)] else limit.slice(buffer);
const n = try file_reader.interface.readSliceShort(dest);
if (n == 0) return error.EndOfStream;
a.writer.end += n;
return n;
}
fn growingRebase(w: *Writer, preserve: usize, minimum_len: usize) Error!void {
const a: *Allocating = @fieldParentPtr("writer", w);
const total = std.math.add(usize, preserve, minimum_len) catch return error.WriteFailed;
a.ensureTotalCapacity(total) catch return error.WriteFailed;
a.ensureUnusedCapacity(minimum_len) catch return error.WriteFailed;
}
fn testAllocating(comptime alignment: std.mem.Alignment) !void {
var a: Allocating = .initAligned(testing.allocator, alignment);
defer a.deinit();
const w = &a.writer;
const x: i32 = 42;
const y: i32 = 1234;
try w.print("x: {}\ny: {}\n", .{ x, y });
const expected = "x: 42\ny: 1234\n";
try testing.expectEqualSlices(u8, expected, a.written());
// 测试 *Aligned 方法
var l = a.toArrayListAligned(alignment);
defer l.deinit(testing.allocator);
try testing.expectEqualSlices(u8, expected, l.items);
a = .fromArrayListAligned(testing.allocator, alignment, &l);
try testing.expectEqualSlices(u8, expected, a.written());
const slice: []align(alignment.toByteUnits()) u8 = @alignCast(try a.toOwnedSlice());
try testing.expectEqualSlices(u8, expected, slice);
a = .initOwnedSliceAligned(testing.allocator, alignment, slice);
try testing.expectEqualSlices(u8, expected, a.writer.buffer);
}
test Allocating {
try testAllocating(.@"1");
try testAllocating(.@"4");
try testAllocating(.@"8");
try testAllocating(.@"16");
try testAllocating(.@"32");
try testAllocating(.@"64");
}
};
test "discarding sendFile" {
const io = testing.io;
var tmp_dir = testing.tmpDir(.{});
defer tmp_dir.cleanup();
const file = try tmp_dir.dir.createFile(io, "input.txt", .{ .read = true });
defer file.close(io);
var r_buffer: [256]u8 = undefined;
var file_writer: File.Writer = .init(file, io, &r_buffer);
try file_writer.interface.writeByte('h');
try file_writer.interface.flush();
var file_reader = file_writer.moveToReader();
try file_reader.seekTo(0);
var w_buffer: [256]u8 = undefined;
var discarding: Writer.Discarding = .init(&w_buffer);
_ = try file_reader.interface.streamRemaining(&discarding.writer);
}
test "allocating sendFile" {
const io = testing.io;
var tmp_dir = testing.tmpDir(.{});
defer tmp_dir.cleanup();
const file = try tmp_dir.dir.createFile(io, "input.txt", .{ .read = true });
defer file.close(io);
var r_buffer: [2]u8 = undefined;
var file_writer: File.Writer = .init(file, io, &r_buffer);
try file_writer.interface.writeAll("abcd");
try file_writer.interface.flush();
var file_reader = file_writer.moveToReader();
try file_reader.seekTo(0);
try file_reader.interface.fill(2);
var allocating: Writer.Allocating = .init(testing.allocator);
defer allocating.deinit();
try allocating.ensureUnusedCapacity(1);
try testing.expectEqual(4, allocating.writer.sendFileAll(&file_reader, .unlimited));
try testing.expectEqualStrings("abcd", allocating.writer.buffered());
}
test sendFileReading {
const io = testing.io;
var tmp_dir = testing.tmpDir(.{});
defer tmp_dir.cleanup();
const file = try tmp_dir.dir.createFile(io, "input.txt", .{ .read = true });
defer file.close(io);
var r_buffer: [2]u8 = undefined;
var file_writer: File.Writer = .init(file, io, &r_buffer);
try file_writer.interface.writeAll("abcd");
try file_writer.interface.flush();
var file_reader = file_writer.moveToReader();
try file_reader.seekTo(0);
try file_reader.interface.fill(2);
var w_buffer: [1]u8 = undefined;
var discarding: Writer.Discarding = .init(&w_buffer);
try testing.expectEqual(4, discarding.writer.sendFileReadingAll(&file_reader, .unlimited));
}
test writeStruct {
var buffer: [16]u8 = undefined;
const S = extern struct { a: u64, b: u32, c: u32 };
const s: S = .{ .a = 1, .b = 2, .c = 3 };
{
var w: Writer = .fixed(&buffer);
try w.writeStruct(s, .little);
try testing.expectEqualSlices(u8, &.{
1, 0, 0, 0, 0, 0, 0, 0, //
2, 0, 0, 0, //
3, 0, 0, 0, //
}, &buffer);
}
{
var w: Writer = .fixed(&buffer);
try w.writeStruct(s, .big);
try testing.expectEqualSlices(u8, &.{
0, 0, 0, 0, 0, 0, 0, 1, //
0, 0, 0, 2, //
0, 0, 0, 3, //
}, &buffer);
}
}
test writeSliceEndian {
var buffer: [5]u8 align(2) = undefined;
var w: Writer = .fixed(&buffer);
try w.writeByte('x');
const array: [2]u16 = .{ 0x1234, 0x5678 };
try writeSliceEndian(&w, u16, &array, .big);
try testing.expectEqualSlices(u8, &.{ 'x', 0x12, 0x34, 0x56, 0x78 }, &buffer);
}
test "writableSlice with fixed writer" {
var buf: [2]u8 = undefined;
var w: std.Io.Writer = .fixed(&buf);
try w.writeByte(1);
try std.testing.expectError(error.WriteFailed, w.writableSlice(2));
}
test splatBytePreserve {
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 5, .splat_len = 5 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 9, .preserve = 5, .splat_len = 2 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 5, .splat_len = 6 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 6, .splat_len = 6 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 5, .splat_len = 10 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 6, .splat_len = 10 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 6, .splat_len = 11 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 6, .splat_len = 80 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 6, .splat_len = 85 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 10, .splat_len = 6 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 10, .splat_len = 11 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 10, .splat_len = 80 });
try testSplatBytePreserve(.{ .buf_len = 10, .fill_len = 5, .preserve = 10, .splat_len = 85 });
}
fn testSplatBytePreserve(options: struct { buf_len: u4, fill_len: u4, preserve: u4, splat_len: u8 }) !void {
assert(options.fill_len <= options.buf_len);
assert(options.preserve <= options.buf_len);
const fill_buf = "abcdefghijklmno";
const fill = fill_buf[0..options.fill_len];
var expected_out_buf: [256]u8 = @splat('X');
@memcpy(expected_out_buf[0..options.fill_len], fill);
const expected_out = expected_out_buf[0 .. options.fill_len + options.splat_len];
const expected_preserved = expected_out[expected_out.len -| options.preserve..];
var out_buf: [256]u8 = undefined;
var fw: Writer = .fixed(&out_buf);
var indirect_buffer: [16]u8 = undefined;
var twi: std.testing.WriterIndirect = .init(&fw, indirect_buffer[0..options.buf_len]);
const w = &twi.interface;
try w.writeAll(fill);
try w.splatBytePreserve(options.preserve, 'X', options.splat_len);
try std.testing.expectEqualStrings(expected_preserved, w.buffer[w.end -| options.preserve..w.end]);
try w.flush();
try std.testing.expectEqualStrings(expected_out, fw.buffer[0..fw.end]);
}