跳转到内容

std.zon.Serializer

标准库Zig 0.17.1官方原文
源码std/zon/Serializer.zig

第 1 行

对序列化提供更底层的控制,可通过 serializer 创建新实例。

适用于需要控制序列化哪些字段、字段的表示方式, 或希望写入内存中并不存在的 ZON 对象的场景。

可使用 value 序列化值。序列化递归类型时提供以下方法:

还可使用具体表示法序列化值:

手动序列化容器,参见:

字段

options: Options = .{}
indent_level: u8 = 0
writer: *Writer

std.zon.Serializer.A

别名

第 893 行

别名目标 std.zon.Serializer

std.zon.Serializer.assert

别名

第 30 行

别名目标 std.debug.assert

std.zon.Serializer.assertCanSerializeType

函数

第 977 行

inline fn assertCanSerializeType(T: type) void

参数

T: type

std.zon.Serializer.beginStruct

函数

第 565 行

创建 Struct,用于逐字段写入 ZON 结构体。

pub fn beginStruct(self: *Serializer, options: ContainerOptions) Error!Struct

参数

self: *Serializer
options: ContainerOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.beginTuple

函数

第 570 行

创建用于逐字段写入 ZON 元组的 Tuple。

pub fn beginTuple(self: *Serializer, options: ContainerOptions) Error!Tuple

参数

self: *Serializer
options: ContainerOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.canSerializeType

函数

第 981 行

inline fn canSerializeType(T: type) bool

参数

T: type

用法示例

test canSerializeType {
    try std.testing.expect(!comptime canSerializeType(void));
    try std.testing.expect(!comptime canSerializeType(struct { f: [*]u8 }));
    try std.testing.expect(!comptime canSerializeType(struct { error{foo} }));
    try std.testing.expect(!comptime canSerializeType(union(enum) { a: void, f: [*c]u8 }));
    try std.testing.expect(!comptime canSerializeType(@Vector(0, [*c]u8)));
    try std.testing.expect(!comptime canSerializeType(*?[*c]u8));
    try std.testing.expect(!comptime canSerializeType(enum(u8) { _ }));
    try std.testing.expect(!comptime canSerializeType(union { foo: void }));
    try std.testing.expect(comptime canSerializeType(union(enum) { foo: void }));
    try std.testing.expect(comptime canSerializeType(comptime_float));
    try std.testing.expect(comptime canSerializeType(comptime_int));
    try std.testing.expect(!comptime canSerializeType(struct { comptime foo: ??u8 = null }));
    try std.testing.expect(comptime canSerializeType(@TypeOf(.foo)));
    try std.testing.expect(comptime canSerializeType(?u8));
    try std.testing.expect(comptime canSerializeType(*?*u8));
    try std.testing.expect(comptime canSerializeType(?struct {
        foo: ?struct {
            ?union(enum) {
                a: ?@Vector(0, ?*u8),
            },
            ?struct {
                f: ?[]?u8,
            },
        },
    }));
    try std.testing.expect(!comptime canSerializeType(??u8));
    try std.testing.expect(!comptime canSerializeType(?*?u8));
    try std.testing.expect(!comptime canSerializeType(*?*?*u8));
    try std.testing.expect(comptime canSerializeType(struct { x: comptime_int = 2 }));
    try std.testing.expect(comptime canSerializeType(struct { x: comptime_float = 2 }));
    try std.testing.expect(comptime canSerializeType(struct { comptime_int }));
    try std.testing.expect(comptime canSerializeType(struct { comptime x: @TypeOf(.foo) = .foo }));
    const Recursive = struct { foo: ?*@This() };
    try std.testing.expect(comptime canSerializeType(Recursive));

    // 确保在因已经遇到类型递归而提前退出之前,
    // 先验证嵌套的可选类型!
    try std.testing.expect(!comptime canSerializeType(struct {
        add_to_visited: ?u8,
        retrieve_from_visited: ??u8,
    }));
}

std.zon.Serializer.canSerializeTypeInner

函数

第 985 行

fn canSerializeTypeInner( T: type, visited: []const type, parent_is_optional: bool, ) bool

参数

T: type
visited: []const type

已访问的结构体和联合体,用于避免无限递归。 无需跟踪更多类型;可选类型嵌套也会使跟踪更复杂。

parent_is_optional: bool

std.zon.Serializer.checkValueDepth

函数

第 909 行

fn checkValueDepth(val: anytype, depth: usize) error{ExceededMaxDepth}!void

参数

depth: usize

错误

ExceededMaxDepth

用法示例

test checkValueDepth {
    try expectValueDepthEquals(1, 10);
    try expectValueDepthEquals(2, .{ .x = 1, .y = 2 });
    try expectValueDepthEquals(2, .{ 1, 2 });
    try expectValueDepthEquals(3, .{ 1, .{ 2, 3 } });
    try expectValueDepthEquals(3, .{ .{ 1, 2 }, 3 });
    try expectValueDepthEquals(3, .{ .x = 0, .y = 1, .z = .{ .x = 3 } });
    try expectValueDepthEquals(3, .{ .x = 0, .y = .{ .x = 1 }, .z = 2 });
    try expectValueDepthEquals(3, .{ .x = .{ .x = 0 }, .y = 1, .z = 2 });
    try expectValueDepthEquals(2, @as(?u32, 1));
    try expectValueDepthEquals(1, @as(?u32, null));
    try expectValueDepthEquals(1, null);
    try expectValueDepthEquals(3, &@as(?u32, 1));

    // 该指针会丢失隐式编译时属性,因此这里需要显式指定 'comptime'。
    try comptime expectValueDepthEquals(2, &1);

    const Union = union(enum) {
        x: u32,
        y: struct { x: u32 },
    };
    try expectValueDepthEquals(2, Union{ .x = 1 });
    try expectValueDepthEquals(3, Union{ .y = .{ .x = 1 } });

    const Recurse = struct { r: ?*const @This() };
    try expectValueDepthEquals(2, Recurse{ .r = null });
    try expectValueDepthEquals(5, Recurse{ .r = &Recurse{ .r = null } });
    try expectValueDepthEquals(8, Recurse{ .r = &Recurse{ .r = &Recurse{ .r = null } } });

    try expectValueDepthEquals(2, @as([]const u8, &.{ 1, 2, 3 }));
    try expectValueDepthEquals(3, @as([]const []const u8, &.{&.{ 1, 2, 3 }}));
}

std.zon.Serializer.codePoint

函数

第 297 行

将 val 序列化为 Unicode 码点。

若 val 不是有效 Unicode 码点,则返回 error.InvalidCodepoint。

pub fn codePoint( self: *Serializer, val: u21, options: CodePointOptions, ) CodePointError!void

参数

self: *Serializer
val: u21
options: CodePointOptions

错误

InvalidCodepoint
WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.CodePointError

错误集合

第 288 行

错误

InvalidCodepoint
WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.CodePointOptions

容器

第 290 行

码点格式化选项。

字段

escape_non_ascii: bool = false

std.zon.Serializer.Container

容器

第 752 行

字段

serializer: *Serializer
field_style: FieldStyle
options: ContainerOptions
empty: bool

std.zon.Serializer.Container.begin

函数

第 760 行

fn begin( sz: *Serializer, field_style: FieldStyle, options: ContainerOptions, ) Error!Container

参数

sz: *Serializer
field_style: FieldStyle
options: ContainerOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Container.end

函数

第 775 行

fn end(self: *Container) Error!void

参数

self: *Container

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Container.field

函数

第 811 行

fn field( self: *Container, name: ?[]const u8, val: anytype, options: ValueOptions, ) Error!void

参数

self: *Container
name: ?[]const u8
options: ValueOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Container.fieldArbitraryDepth

函数

第 833 行

fn fieldArbitraryDepth( self: *Container, name: ?[]const u8, val: anytype, options: ValueOptions, ) Error!void

参数

self: *Container
name: ?[]const u8
options: ValueOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Container.fieldMaxDepth

函数

第 822 行

超过 depth 时返回 error.ExceededMaxDepth。

fn fieldMaxDepth( self: *Container, name: ?[]const u8, val: anytype, options: ValueOptions, depth: usize, ) DepthError!void

参数

self: *Container
name: ?[]const u8
options: ValueOptions
depth: usize

错误

ExceededMaxDepth
WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Container.fieldPrefix

函数

第 792 行

fn fieldPrefix(self: *Container, name: ?[]const u8) Error!void

参数

self: *Container
name: ?[]const u8

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Container.FieldStyle

容器

第 753 行

字段

named
anon

std.zon.Serializer.Container.shouldElideSpaces

函数

第 843 行

fn shouldElideSpaces(self: *const Container) bool

参数

self: *const Container

std.zon.Serializer.ContainerOptions

容器

第 42 行

手动序列化容器类型的选项。

字段

whitespace_style: union(enum) {
    /// 若为 true,每个字段均换行;若为 false,则不换行。
    wrap: bool,
    /// 根据字段数量自动决定是否换行。遵循通常经验规则,
    /// 字段超过两个的容器会换行。
    fields: usize,
} = .{ .wrap = true }

此容器应采用的空白样式。关闭空白处理时忽略。

std.zon.Serializer.ContainerOptions.shouldWrap

函数

第 52 行

fn shouldWrap(self: ContainerOptions) bool

参数

std.zon.Serializer.DepthError

错误集合

第 34 行

错误

ExceededMaxDepth
WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.EmitCodepointLiterals

容器

第 71 行

确定何时将 Unicode 码点输出为字面量,而不是整数。

字段

never

绝不发出 Unicode 码点字面量。

printable_ascii

对可打印 ASCII 范围内的任意 u8 生成 Unicode 码点字面量。

always

对任何不超过 21 位、且值为有效非代理码点的无符号整数, 输出 Unicode 码点字面量。

std.zon.Serializer.EmitCodepointLiterals.emitAsCodepoint

函数

第 81 行

若该值应作为 Unicode 码点输出,则将其作为 u21 返回。

fn emitAsCodepoint(self: @This(), val: anytype) ?u21

参数

self: @This()

std.zon.Serializer.Error

别名

第 33 行

别名目标 std.Io.Writer.Error

std.zon.Serializer.expectValueDepthEquals

函数

第 939 行

fn expectValueDepthEquals(expected: usize, v: anytype) !void

参数

expected: usize

std.zon.Serializer.float

函数

第 259 行

序列化浮点数。

pub fn float(self: *Serializer, val: anytype) Error!void

参数

self: *Serializer

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.fuzzString

函数

第 478 行

fn fuzzString(options: StringOptions, smith: *std.testing.Smith) !void

参数

options: StringOptions
smith: *std.testing.Smith

std.zon.Serializer.ident

函数

第 284 行

将 name 序列化为带 . 前缀的标识符。

必要时转义标识符。

pub fn ident(self: *Serializer, name: []const u8) Error!void

参数

self: *Serializer
name: []const u8

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.indent

函数

第 574 行

fn indent(self: *Serializer) Error!void

参数

self: *Serializer

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.int

函数

第 254 行

序列化整数。

pub fn int(self: *Serializer, val: anytype) Error!void

参数

self: *Serializer

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.multilineString

函数

第 523 行

类似 value,但始终序列化为多行字符串字面量。

如果 val 包含后面未跟换行符的 CR,则返回 error.InnerCarriageReturn, 因为多行字符串不能表示不带后续换行符的 CR。

pub fn multilineString( self: *Serializer, val: []const u8, options: MultilineStringOptions, ) MultilineStringError!void

参数

self: *Serializer
val: []const u8
options: MultilineStringOptions

错误

InnerCarriageReturn
WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.MultilineStringError

错误集合

第 517 行

错误

InnerCarriageReturn
WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.MultilineStringOptions

容器

第 510 行

多行字符串的格式化选项。

字段

top_level: bool = false

若 top level 为 true,则省略多行字符串前后的空白。 若其为 true,则先打印换行符,再打印值,随后再打印换行符; 若 whitespace 为 true,则在之后添加必要缩进。

std.zon.Serializer.newline

函数

第 580 行

fn newline(self: *Serializer) Error!void

参数

self: *Serializer

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.newlineOrSpace

函数

第 586 行

fn newlineOrSpace(self: *Serializer, len: usize) Error!void

参数

self: *Serializer
len: usize

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Options

容器

第 36 行

字段

whitespace: bool = true

若为 false,则仅输出语法必需的空白字符。

std.zon.Serializer.Serializer

别名

第 28 行

别名目标 std.zon.Serializer

std.zon.Serializer.space

函数

第 594 行

fn space(self: *Serializer) Error!void

参数

self: *Serializer

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.std

别名

第 29 行

别名目标 std

std.zon.Serializer.string

函数

第 412 行

类似于 value,但始终将 val 序列化为字符串。

pub fn string(self: *Serializer, val: []const u8, options: StringOptions) Writer.Error!void

参数

self: *Serializer
val: []const u8
options: StringOptions

错误

WriteFailed

详细诊断信息见 Writer 实现。

用法示例

test string {
    try testString("\"foobar\"", "foobar", .{});
    try testString("\"€\"", "€", .{});
    try testString("\"\\u{20ac}\"", "€", .{ .escape_non_ascii = true });
    try testString("\"ÿ\"", "ÿ", .{});
    try testString("\"\\u{ff}\"", "ÿ", .{ .escape_non_ascii = true });
    try testString("\"\\xff\"", &.{0xff}, .{});
    try testString("\"\\xff\"", &.{0xff}, .{ .escape_non_ascii = true });

    // 截断的 UTF-8 序列(0xe2 开始一个 3 字节序列,0x80 是有效的后续字节)。
    try testString("\"\\xe2\\x80\"", &.{ 0xe2, 0x80 }, .{});
    try testString("\"\\xe2\\x80\"", &.{ 0xe2, 0x80 }, .{ .escape_non_ascii = true });
}

std.zon.Serializer.StringOptions

容器

第 407 行

字段

escape_non_ascii: bool = false

std.zon.Serializer.Struct

容器

第 674 行

逐字段写出 ZON 结构体。

字段

container: Container

std.zon.Serializer.Struct.begin

函数

第 677 行

fn begin(parent: *Serializer, options: ContainerOptions) Error!Struct

参数

parent: *Serializer
options: ContainerOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Struct.beginStructField

函数

第 725 行

开始一个以结构体为值的字段,并返回该结构体。

pub fn beginStructField( self: *Struct, name: []const u8, options: ContainerOptions, ) Error!Struct

参数

self: *Struct
name: []const u8
options: ContainerOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Struct.beginTupleField

函数

第 735 行

开始一个以元组为值的字段,并返回该元组。

pub fn beginTupleField( self: *Struct, name: []const u8, options: ContainerOptions, ) Error!Tuple

参数

self: *Struct
name: []const u8
options: ContainerOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Struct.end

函数

第 686 行

完成结构体序列化。

按配置在适当时打印尾随逗号,并打印闭合括号。

pub fn end(self: *Struct) Error!void

参数

self: *Struct

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Struct.field

函数

第 692 行

序列化字段。等价于依次调用 fieldPrefix 和 value。

pub fn field( self: *Struct, name: []const u8, val: anytype, options: ValueOptions, ) Error!void

参数

self: *Struct
name: []const u8
options: ValueOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Struct.fieldArbitraryDepth

函数

第 715 行

序列化字段。等同于先调用 fieldPrefix,再调用 valueArbitraryDepth。

pub fn fieldArbitraryDepth( self: *Struct, name: []const u8, val: anytype, options: ValueOptions, ) Error!void

参数

self: *Struct
name: []const u8
options: ValueOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Struct.fieldMaxDepth

函数

第 703 行

序列化字段。等价于依次调用 fieldPrefix 和 valueMaxDepth。 超过 depth 时返回 error.ExceededMaxDepth。

pub fn fieldMaxDepth( self: *Struct, name: []const u8, val: anytype, options: ValueOptions, depth: usize, ) DepthError!void

参数

self: *Struct
name: []const u8
options: ValueOptions
depth: usize

错误

ExceededMaxDepth
WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Struct.fieldPrefix

函数

第 747 行

打印字段前缀,包括必要的逗号、字段名(必要时转义), 以及按配置设置的空白。适用于 希望自行序列化字段值的情况。

pub fn fieldPrefix(self: *Struct, name: []const u8) Error!void

参数

self: *Struct
name: []const u8

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.testString

函数

第 461 行

fn testString(expected: []const u8, input: []const u8, options: StringOptions) !void

参数

expected: []const u8
input: []const u8
options: StringOptions

std.zon.Serializer.tuple

函数

第 313 行

类似 value,但始终将 val 序列化为元组。

若 val 不是元组、数组、数组指针或切片,则在编译期失败。

pub fn tuple(self: *Serializer, val: anytype, options: ValueOptions) Error!void

参数

self: *Serializer
options: ValueOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Tuple

容器

第 601 行

逐字段写出 ZON 元组。

字段

container: Container

std.zon.Serializer.Tuple.begin

函数

第 604 行

fn begin(parent: *Serializer, options: ContainerOptions) Error!Tuple

参数

parent: *Serializer
options: ContainerOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Tuple.beginStructField

函数

第 649 行

开始一个以结构体为值的字段,并返回该结构体。

pub fn beginStructField( self: *Tuple, options: ContainerOptions, ) Error!Struct

参数

self: *Tuple
options: ContainerOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Tuple.beginTupleField

函数

第 658 行

开始一个以元组为值的字段,并返回该元组。

pub fn beginTupleField( self: *Tuple, options: ContainerOptions, ) Error!Tuple

参数

self: *Tuple
options: ContainerOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Tuple.end

函数

第 613 行

完成元组的序列化。

按配置在适当情况下输出末尾逗号,并输出右括号。

pub fn end(self: *Tuple) Error!void

参数

self: *Tuple

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Tuple.field

函数

第 619 行

序列化字段。等价于依次调用 fieldPrefix 和 value。

pub fn field( self: *Tuple, val: anytype, options: ValueOptions, ) Error!void

参数

self: *Tuple
options: ValueOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Tuple.fieldArbitraryDepth

函数

第 640 行

序列化字段。等同于先调用 fieldPrefix,再调用 valueArbitraryDepth。

pub fn fieldArbitraryDepth( self: *Tuple, val: anytype, options: ValueOptions, ) Error!void

参数

self: *Tuple
options: ValueOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Tuple.fieldMaxDepth

函数

第 629 行

序列化字段。等价于依次调用 fieldPrefix 和 valueMaxDepth。 超过 depth 时返回 error.ExceededMaxDepth。

pub fn fieldMaxDepth( self: *Tuple, val: anytype, options: ValueOptions, depth: usize, ) DepthError!void

参数

self: *Tuple
options: ValueOptions
depth: usize

错误

ExceededMaxDepth
WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.Tuple.fieldPrefix

函数

第 668 行

打印字段前缀。根据配置打印必要的逗号和空白。若希望自行序列化字段值,此函数很有用。

pub fn fieldPrefix(self: *Tuple) Error!void

参数

self: *Tuple

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.tupleArbitraryDepth

函数

第 334 行

类似于 tuple,但允许递归类型。

调用方负责确保 val 不包含环。

pub fn tupleArbitraryDepth( self: *Serializer, val: anytype, options: ValueOptions, ) Error!void

参数

self: *Serializer
options: ValueOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.tupleImpl

函数

第 342 行

fn tupleImpl(self: *Serializer, val: anytype, options: ValueOptions) Error!void

参数

self: *Serializer
options: ValueOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.tupleMaxDepth

函数

第 321 行

类似于 tuple,但允许递归类型。

超过 depth 时返回 error.ExceededMaxDepth。

pub fn tupleMaxDepth( self: *Serializer, val: anytype, options: ValueOptions, depth: usize, ) DepthError!void

参数

self: *Serializer
options: ValueOptions
depth: usize

错误

ExceededMaxDepth
WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.typeIsRecursive

函数

第 861 行

inline fn typeIsRecursive(comptime T: type) bool

参数

T: type

用法示例

test typeIsRecursive {
    try std.testing.expect(!typeIsRecursive(bool));
    try std.testing.expect(!typeIsRecursive(struct { x: i32, y: i32 }));
    try std.testing.expect(!typeIsRecursive(struct { i32, i32 }));
    try std.testing.expect(typeIsRecursive(struct { x: i32, y: i32, z: *@This() }));
    try std.testing.expect(typeIsRecursive(struct {
        a: struct {
            const A = @This();
            b: struct {
                c: *struct {
                    a: ?A,
                },
            },
        },
    }));
    try std.testing.expect(typeIsRecursive(struct {
        a: [3]*@This(),
    }));
    try std.testing.expect(typeIsRecursive(struct {
        a: union { a: i32, b: *@This() },
    }));
}

std.zon.Serializer.typeIsRecursiveInner

函数

第 865 行

fn typeIsRecursiveInner(comptime T: type, comptime prev_visited: []const type) bool

参数

T: type
prev_visited: []const type

std.zon.Serializer.value

函数

第 112 行

序列化一个值,类似于 serialize。

pub fn value(self: *Serializer, val: anytype, options: ValueOptions) Error!void

参数

self: *Serializer
options: ValueOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.valueArbitraryDepth

函数

第 125 行

序列化一个值,类似于 serializeArbitraryDepth。

pub fn valueArbitraryDepth(self: *Serializer, val: anytype, options: ValueOptions) Error!void

参数

self: *Serializer
options: ValueOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.valueArbitraryDepthArray

函数

第 243 行

fn valueArbitraryDepthArray(s: *Serializer, comptime A: type, array: *const A, options: ValueOptions) Error!void

参数

s: *Serializer
A: type
array: *const A
options: ValueOptions

错误

WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.valueMaxDepth

函数

第 119 行

序列化一个值,类似于 serializeMaxDepth。 可能返回 error.ExceededMaxDepth。

pub fn valueMaxDepth(self: *Serializer, val: anytype, options: ValueOptions, depth: usize) DepthError!void

参数

self: *Serializer
options: ValueOptions
depth: usize

错误

ExceededMaxDepth
WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.ValueOptions

容器

第 63 行

单个值的序列化选项。

这些选项的更多信息参见 SerializeOptions。

字段

emit_codepoint_literals: EmitCodepointLiterals = .never
emit_strings_as_containers: bool = false
emit_default_optional_fields: bool = true
escape_non_ascii: bool = false

std.zon.Serializer.writeCodepoint

函数

第 373 行

使用给定选项将 Unicode 码点写入写入器。

若 codepoint 不是有效 Unicode 码点,则返回 error.InvalidCodepoint。

fn writeCodepoint( self: *Serializer, codepoint: u21, options: WriteCodepointOptions, ) CodePointError!void

参数

self: *Serializer
codepoint: u21
options: WriteCodepointOptions

错误

InvalidCodepoint
WriteFailed Error

详细诊断信息见 Writer 实现。

std.zon.Serializer.WriteCodepointOptions

容器

第 364 行

写入 Unicode 码点的选项。

字段

escape_non_ascii: bool = false
quote_style: enum { single, double } = .single

采用单引号风格时转义单引号,否则转义双引号。

std.zon.Serializer.Writer

别名

第 31 行

别名目标 std.Io.Writer

源码

std/zon/Serializer.zig

//! 对序列化提供更底层的控制,可通过 `serializer` 创建新实例。
//!
//! 适用于需要控制序列化哪些字段、字段的表示方式,
//! 或希望写入内存中并不存在的 ZON 对象的场景。
//!
//! 可使用 `value` 序列化值。序列化递归类型时提供以下方法:
//! * `valueMaxDepth`
//! * `valueArbitraryDepth`
//!
//! 还可使用具体表示法序列化值:
//! * `int`
//! * `float`
//! * `codePoint`
//! * `tuple`
//! * `tupleMaxDepth`
//! * `tupleArbitraryDepth`
//! * `string`
//! * `multilineString`
//!
//! 手动序列化容器,参见:
//! * `beginStruct`
//! * `beginTuple`

options: Options = .{},
indent_level: u8 = 0,
writer: *Writer,

const Serializer = @This();
const std = @import("std");
const assert = std.debug.assert;
const Writer = std.Io.Writer;

pub const Error = Writer.Error;
pub const DepthError = Error || error{ExceededMaxDepth};

pub const Options = struct {
    /// 若为 false,则仅输出语法必需的空白字符。
    whitespace: bool = true,
};

/// 手动序列化容器类型的选项。
pub const ContainerOptions = struct {
    /// 此容器应采用的空白样式。关闭空白处理时忽略。
    whitespace_style: union(enum) {
        /// 若为 true,每个字段均换行;若为 false,则不换行。
        wrap: bool,
        /// 根据字段数量自动决定是否换行。遵循通常经验规则,
        /// 字段超过两个的容器会换行。
        fields: usize,
    } = .{ .wrap = true },

    fn shouldWrap(self: ContainerOptions) bool {
        return switch (self.whitespace_style) {
            .wrap => |wrap| wrap,
            .fields => |fields| fields > 2,
        };
    }
};

/// 单个值的序列化选项。
///
/// 这些选项的更多信息参见 `SerializeOptions`。
pub const ValueOptions = struct {
    emit_codepoint_literals: EmitCodepointLiterals = .never,
    emit_strings_as_containers: bool = false,
    emit_default_optional_fields: bool = true,
    escape_non_ascii: bool = false,
};

/// 确定何时将 Unicode 码点输出为字面量,而不是整数。
pub const EmitCodepointLiterals = enum {
    /// 绝不发出 Unicode 码点字面量。
    never,
    /// 对可打印 ASCII 范围内的任意 `u8` 生成 Unicode 码点字面量。
    printable_ascii,
    /// 对任何不超过 21 位、且值为有效非代理码点的无符号整数,
    /// 输出 Unicode 码点字面量。
    always,

    /// 若该值应作为 Unicode 码点输出,则将其作为 u21 返回。
    fn emitAsCodepoint(self: @This(), val: anytype) ?u21 {
        // 排除不兼容的整数类型
        switch (@typeInfo(@TypeOf(val))) {
            .int => |int_info| if (int_info.signedness == .signed or int_info.bits > 21) {
                return null;
            },
            .comptime_int => {},
            else => comptime unreachable,
        }

        // 若该值不应作为 Unicode 码点打印,返回 null;否则返回
        // 转换为 u21 的值。
        switch (self) {
            .always => {
                const c = std.math.cast(u21, val) orelse return null;
                if (!std.unicode.utf8ValidCodepoint(c)) return null;
                return c;
            },
            .printable_ascii => {
                const c = std.math.cast(u8, val) orelse return null;
                if (!std.ascii.isPrint(c)) return null;
                return c;
            },
            .never => {
                return null;
            },
        }
    }
};

/// 序列化一个值,类似于 `serialize`。
pub fn value(self: *Serializer, val: anytype, options: ValueOptions) Error!void {
    comptime assert(!typeIsRecursive(@TypeOf(val)));
    return self.valueArbitraryDepth(val, options);
}

/// 序列化一个值,类似于 `serializeMaxDepth`。
/// 可能返回 `error.ExceededMaxDepth`。
pub fn valueMaxDepth(self: *Serializer, val: anytype, options: ValueOptions, depth: usize) DepthError!void {
    try checkValueDepth(val, depth);
    return self.valueArbitraryDepth(val, options);
}

/// 序列化一个值,类似于 `serializeArbitraryDepth`。
pub fn valueArbitraryDepth(self: *Serializer, val: anytype, options: ValueOptions) Error!void {
    comptime assertCanSerializeType(@TypeOf(val));
    switch (@typeInfo(@TypeOf(val))) {
        .int, .comptime_int => if (options.emit_codepoint_literals.emitAsCodepoint(val)) |c| {
            self.codePoint(c, .{ .escape_non_ascii = options.escape_non_ascii }) catch |err| switch (err) {
                error.InvalidCodepoint => unreachable, // 已验证
                else => |e| return e,
            };
        } else {
            try self.int(val);
        },
        .float, .comptime_float => try self.float(val),
        .bool, .null => try self.writer.print("{}", .{val}),
        .enum_literal => try self.ident(@tagName(val)),
        .@"enum" => try self.ident(@tagName(val)),
        .pointer => |pointer| {
            // 尝试序列化为字符串
            const item: ?type = switch (@typeInfo(pointer.child)) {
                .array => |array| array.child,
                else => if (pointer.size == .slice) pointer.child else null,
            };
            if (item == u8 and
                (pointer.sentinel() == null or pointer.sentinel() == 0) and
                !options.emit_strings_as_containers)
            {
                return try self.string(val, .{ .escape_non_ascii = options.escape_non_ascii });
            }

            // 序列化为元组或子类型
            switch (pointer.size) {
                .slice => try self.tupleImpl(val, options),
                .one => try self.valueArbitraryDepth(val.*, options),
                else => comptime unreachable,
            }
        },
        .array => {
            try valueArbitraryDepthArray(self, @TypeOf(val), &val, options);
        },
        .vector => |vector| {
            const array: [vector.len]vector.child = val;
            try valueArbitraryDepthArray(self, @TypeOf(array), &array, options);
        },
        .@"struct" => |@"struct"| if (@"struct".is_tuple) {
            var container = try self.beginTuple(
                .{ .whitespace_style = .{ .fields = @"struct".field_names.len } },
            );
            inline for (val) |field_value| {
                try container.fieldArbitraryDepth(field_value, options);
            }
            try container.end();
        } else {
            // 决定输出哪些字段
            const fields, const skipped: [@"struct".field_names.len]bool = if (options.emit_default_optional_fields) b: {
                break :b .{ @"struct".field_names.len, @splat(false) };
            } else b: {
                var fields = @"struct".field_names.len;
                var skipped: [@"struct".field_names.len]bool = @splat(false);
                inline for (
                    @"struct".field_names,
                    @"struct".field_types,
                    @"struct".field_attrs,
                    &skipped,
                ) |field_name, field_type, field_attrs, *skip| {
                    if (field_attrs.default_value_ptr) |ptr| {
                        const default: *const field_type = @ptrCast(@alignCast(ptr));
                        const field_value = @field(val, field_name);
                        if (std.meta.eql(field_value, default.*)) {
                            skip.* = true;
                            fields -= 1;
                        }
                    }
                }
                break :b .{ fields, skipped };
            };

            // 输出这些字段
            var container = try self.beginStruct(
                .{ .whitespace_style = .{ .fields = fields } },
            );
            inline for (@"struct".field_names, skipped) |field_name, skip| {
                if (!skip) {
                    try container.fieldArbitraryDepth(
                        field_name,
                        @field(val, field_name),
                        options,
                    );
                }
            }
            try container.end();
        },
        .@"union" => |@"union"| {
            comptime assert(@"union".tag_type != null);
            switch (val) {
                inline else => |pl, tag| if (@TypeOf(pl) == void)
                    try self.writer.print(".{s}", .{@tagName(tag)})
                else {
                    var container = try self.beginStruct(.{ .whitespace_style = .{ .fields = 1 } });

                    try container.fieldArbitraryDepth(
                        @tagName(tag),
                        pl,
                        options,
                    );

                    try container.end();
                },
            }
        },
        .optional => if (val) |inner| {
            try self.valueArbitraryDepth(inner, options);
        } else {
            try self.writer.writeAll("null");
        },

        else => comptime unreachable,
    }
}

fn valueArbitraryDepthArray(s: *Serializer, comptime A: type, array: *const A, options: ValueOptions) Error!void {
    var container = try s.beginTuple(
        .{ .whitespace_style = .{ .fields = array.len } },
    );
    for (array) |elem| {
        try container.fieldArbitraryDepth(elem, options);
    }
    try container.end();
}

/// 序列化整数。
pub fn int(self: *Serializer, val: anytype) Error!void {
    try self.writer.printInt(val, 10, .lower, .{});
}

/// 序列化浮点数。
pub fn float(self: *Serializer, val: anytype) Error!void {
    switch (@typeInfo(@TypeOf(val))) {
        .float => if (std.math.isNan(val)) {
            return self.writer.writeAll("nan");
        } else if (std.math.isPositiveInf(val)) {
            return self.writer.writeAll("inf");
        } else if (std.math.isNegativeInf(val)) {
            return self.writer.writeAll("-inf");
        } else if (std.math.isNegativeZero(val)) {
            return self.writer.writeAll("-0.0");
        } else {
            try self.writer.print("{d}", .{val});
        },
        .comptime_float => if (val == 0) {
            return self.writer.writeAll("0");
        } else {
            try self.writer.print("{d}", .{val});
        },
        else => comptime unreachable,
    }
}

/// 将 `name` 序列化为带 `.` 前缀的标识符。
///
/// 必要时转义标识符。
pub fn ident(self: *Serializer, name: []const u8) Error!void {
    try self.writer.print(".{f}", .{std.zig.fmtIdPU(name)});
}

pub const CodePointError = Error || error{InvalidCodepoint};
/// 码点格式化选项。
pub const CodePointOptions = struct {
    escape_non_ascii: bool = false,
};

/// 将 `val` 序列化为 Unicode 码点。
///
/// 若 `val` 不是有效 Unicode 码点,则返回 `error.InvalidCodepoint`。
pub fn codePoint(
    self: *Serializer,
    val: u21,
    options: CodePointOptions,
) CodePointError!void {
    try self.writer.writeByte('\'');
    try self.writeCodepoint(val, .{
        .escape_non_ascii = options.escape_non_ascii,
        .quote_style = .single,
    });
    try self.writer.writeByte('\'');
}

/// 类似 `value`,但始终将 `val` 序列化为元组。
///
/// 若 `val` 不是元组、数组、数组指针或切片,则在编译期失败。
pub fn tuple(self: *Serializer, val: anytype, options: ValueOptions) Error!void {
    comptime assert(!typeIsRecursive(@TypeOf(val)));
    try self.tupleArbitraryDepth(val, options);
}

/// 类似于 `tuple`,但允许递归类型。
///
/// 超过 `depth` 时返回 `error.ExceededMaxDepth`。
pub fn tupleMaxDepth(
    self: *Serializer,
    val: anytype,
    options: ValueOptions,
    depth: usize,
) DepthError!void {
    try checkValueDepth(val, depth);
    try self.tupleArbitraryDepth(val, options);
}

/// 类似于 `tuple`,但允许递归类型。
///
/// 调用方负责确保 `val` 不包含环。
pub fn tupleArbitraryDepth(
    self: *Serializer,
    val: anytype,
    options: ValueOptions,
) Error!void {
    try self.tupleImpl(val, options);
}

fn tupleImpl(self: *Serializer, val: anytype, options: ValueOptions) Error!void {
    comptime assertCanSerializeType(@TypeOf(val));
    switch (@typeInfo(@TypeOf(val))) {
        .@"struct" => {
            var container = try self.beginTuple(.{ .whitespace_style = .{ .fields = val.len } });
            inline for (val) |item_val| {
                try container.fieldArbitraryDepth(item_val, options);
            }
            try container.end();
        },
        .pointer, .array => {
            var container = try self.beginTuple(.{ .whitespace_style = .{ .fields = val.len } });
            for (val) |item_val| {
                try container.fieldArbitraryDepth(item_val, options);
            }
            try container.end();
        },
        else => comptime unreachable,
    }
}

/// 写入 Unicode 码点的选项。
const WriteCodepointOptions = struct {
    escape_non_ascii: bool = false,
    /// 采用单引号风格时转义单引号,否则转义双引号。
    quote_style: enum { single, double } = .single,
};

/// 使用给定选项将 Unicode 码点写入写入器。
///
/// 若 `codepoint` 不是有效 Unicode 码点,则返回 `error.InvalidCodepoint`。
fn writeCodepoint(
    self: *Serializer,
    codepoint: u21,
    options: WriteCodepointOptions,
) CodePointError!void {
    switch (codepoint) {
        // 可打印 ASCII
        ' ', '!', '#'...'&', '('...'[', ']'...'~' => try self.writer.writeByte(@intCast(codepoint)),
        // 不可打印的 ASCII
        0x00...0x08, 0x0B, 0x0C, 0x0E...0x1F, 0x7F => try self.writer.print("\\x{x:0>2}", .{codepoint}),
        // 带特殊转义的 ASCII
        '\n' => try self.writer.writeAll("\\n"),
        '\r' => try self.writer.writeAll("\\r"),
        '\t' => try self.writer.writeAll("\\t"),
        '\\' => try self.writer.writeAll("\\\\"),
        // 引号与当前使用的引号字符冲突时,需要转义。
        '\'' => if (options.quote_style == .single) try self.writer.writeAll("\\'") else try self.writer.writeByte('\''),
        '\"' => if (options.quote_style == .double) try self.writer.writeAll("\\\"") else try self.writer.writeByte('"'),

        // 代理项只能通过转义写出
        0xD800...0xDFFF => try self.writer.print("\\u{{{x}}}", .{codepoint}),
        // 其他有效码点
        0x80...0xD7FF, 0xE000...0x10FFFF => if (options.escape_non_ascii) {
            try self.writer.print("\\u{{{x}}}", .{codepoint});
        } else {
            var buf: [7]u8 = undefined;
            const len = std.unicode.utf8Encode(codepoint, &buf) catch unreachable;
            try self.writer.writeAll(buf[0..len]);
        },
        // 码点无效
        0x110000...std.math.maxInt(u21) => return error.InvalidCodepoint,
    }
}

pub const StringOptions = struct {
    escape_non_ascii: bool = false,
};

/// 类似于 `value`,但始终将 `val` 序列化为字符串。
pub fn string(self: *Serializer, val: []const u8, options: StringOptions) Writer.Error!void {
    if (!options.escape_non_ascii) {
        return try self.writer.print("{q}", .{val});
    }

    try self.writer.writeByte('"');
    var i: usize = 0;
    while (i < val.len) {
        const byte = val[i];

        if (byte >= 0x80) {
            if (std.unicode.utf8ByteSequenceLength(byte)) |ulen| utf8: {
                if (val[i..].len < ulen) {
                    // 截断的 UTF-8 序列
                    break :utf8;
                }
                const codepoint = std.unicode.utf8Decode(val[i..][0..ulen]) catch break :utf8;
                self.writeCodepoint(codepoint, .{
                    .escape_non_ascii = true,
                    .quote_style = .double,
                }) catch unreachable;
                i += ulen;
                continue;
            } else |err| switch (err) {
                error.Utf8InvalidStartByte => {},
            }
        }

        try std.zig.stringEscape(&.{byte}, self.writer);
        i += 1;
    }

    try self.writer.writeByte('"');
}

test string {
    try testString("\"foobar\"", "foobar", .{});
    try testString("\"€\"", "€", .{});
    try testString("\"\\u{20ac}\"", "€", .{ .escape_non_ascii = true });
    try testString("\"ÿ\"", "ÿ", .{});
    try testString("\"\\u{ff}\"", "ÿ", .{ .escape_non_ascii = true });
    try testString("\"\\xff\"", &.{0xff}, .{});
    try testString("\"\\xff\"", &.{0xff}, .{ .escape_non_ascii = true });

    // 截断的 UTF-8 序列(0xe2 开始一个 3 字节序列,0x80 是有效的后续字节)。
    try testString("\"\\xe2\\x80\"", &.{ 0xe2, 0x80 }, .{});
    try testString("\"\\xe2\\x80\"", &.{ 0xe2, 0x80 }, .{ .escape_non_ascii = true });
}

fn testString(expected: []const u8, input: []const u8, options: StringOptions) !void {
    var allocating: Writer.Allocating = .init(std.testing.allocator);
    defer allocating.deinit();
    var s: Serializer = .{ .writer = &allocating.writer };

    try s.string(input, options);
    try std.testing.expectEqualSlices(u8, expected, allocating.written());
}

test "fuzz string non-escaping" {
    try std.testing.fuzz(StringOptions{ .escape_non_ascii = false }, fuzzString, .{});
}

test "fuzz string escaping" {
    try std.testing.fuzz(StringOptions{ .escape_non_ascii = true }, fuzzString, .{});
}

fn fuzzString(options: StringOptions, smith: *std.testing.Smith) !void {
    const gpa = std.testing.allocator;

    var arena_state: std.heap.ArenaAllocator = .init(gpa);
    defer arena_state.deinit();
    const arena = arena_state.allocator();

    var allocating: Writer.Allocating = .init(gpa);
    defer allocating.deinit();
    var s: Serializer = .{ .writer = &allocating.writer };

    var buf: [0x100]u8 = undefined;
    const input = buf[0..smith.slice(&buf)];
    try s.string(input, options);

    var parse_diags: std.zon.parse.Diagnostics = undefined;
    const actual = std.zon.parse.fromSlice([]const u8, .{
        .gpa = gpa,
        .arena = arena,
        .source = try arena.dupeSentinel(u8, allocating.written(), 0),
        .diagnostics = &parse_diags,
    }) catch |err| switch (err) {
        error.OutOfMemory => |e| return e,
        error.ParseZon => |e| {
            std.log.err("failed to parse serialized ZON: {f}", .{parse_diags.fmt("fuzz_input")});
            return e;
        },
    };
    try std.testing.expectEqualSlices(u8, input, actual);
}

/// 多行字符串的格式化选项。
pub const MultilineStringOptions = struct {
    /// 若 top level 为 true,则省略多行字符串前后的空白。
    /// 若其为 true,则先打印换行符,再打印值,随后再打印换行符;
    /// 若 whitespace 为 true,则在之后添加必要缩进。
    top_level: bool = false,
};

pub const MultilineStringError = Error || error{InnerCarriageReturn};

/// 类似 `value`,但始终序列化为多行字符串字面量。
///
/// 如果 `val` 包含后面未跟换行符的 CR,则返回 `error.InnerCarriageReturn`,
/// 因为多行字符串不能表示不带后续换行符的 CR。
pub fn multilineString(
    self: *Serializer,
    val: []const u8,
    options: MultilineStringOptions,
) MultilineStringError!void {
    // 确保字符串不包含后面未跟换行符的回车符。
    var i: usize = 0;
    while (i < val.len) : (i += 1) {
        if (val[i] == '\r') {
            if (i + 1 < val.len) {
                if (val[i + 1] == '\n') {
                    i += 1;
                    continue;
                }
            }
            return error.InnerCarriageReturn;
        }
    }

    if (!options.top_level) {
        try self.newline();
        try self.indent();
    }

    try self.writer.writeAll("\\\\");
    for (val) |c| {
        if (c != '\r') {
            try self.writer.writeByte(c); // 即使关闭空白输出,此处仍写入换行符
            if (c == '\n') {
                try self.indent();
                try self.writer.writeAll("\\\\");
            }
        }
    }

    if (!options.top_level) {
        try self.writer.writeByte('\n'); // 即使空白被关闭
        try self.indent();
    }
}

/// 创建 `Struct`,用于逐字段写入 ZON 结构体。
pub fn beginStruct(self: *Serializer, options: ContainerOptions) Error!Struct {
    return Struct.begin(self, options);
}

/// 创建用于逐字段写入 ZON 元组的 `Tuple`。
pub fn beginTuple(self: *Serializer, options: ContainerOptions) Error!Tuple {
    return Tuple.begin(self, options);
}

fn indent(self: *Serializer) Error!void {
    if (self.options.whitespace) {
        try self.writer.splatByteAll(' ', 4 * self.indent_level);
    }
}

fn newline(self: *Serializer) Error!void {
    if (self.options.whitespace) {
        try self.writer.writeByte('\n');
    }
}

fn newlineOrSpace(self: *Serializer, len: usize) Error!void {
    if (self.containerShouldWrap(len)) {
        try self.newline();
    } else {
        try self.space();
    }
}

fn space(self: *Serializer) Error!void {
    if (self.options.whitespace) {
        try self.writer.writeByte(' ');
    }
}

/// 逐字段写出 ZON 元组。
pub const Tuple = struct {
    container: Container,

    fn begin(parent: *Serializer, options: ContainerOptions) Error!Tuple {
        return .{
            .container = try Container.begin(parent, .anon, options),
        };
    }

    /// 完成元组的序列化。
    ///
    /// 按配置在适当情况下输出末尾逗号,并输出右括号。
    pub fn end(self: *Tuple) Error!void {
        try self.container.end();
        self.* = undefined;
    }

    /// 序列化字段。等价于依次调用 `fieldPrefix` 和 `value`。
    pub fn field(
        self: *Tuple,
        val: anytype,
        options: ValueOptions,
    ) Error!void {
        try self.container.field(null, val, options);
    }

    /// 序列化字段。等价于依次调用 `fieldPrefix` 和 `valueMaxDepth`。
    /// 超过 `depth` 时返回 `error.ExceededMaxDepth`。
    pub fn fieldMaxDepth(
        self: *Tuple,
        val: anytype,
        options: ValueOptions,
        depth: usize,
    ) DepthError!void {
        try self.container.fieldMaxDepth(null, val, options, depth);
    }

    /// 序列化字段。等同于先调用 `fieldPrefix`,再调用 `valueArbitraryDepth`。
    ///
    pub fn fieldArbitraryDepth(
        self: *Tuple,
        val: anytype,
        options: ValueOptions,
    ) Error!void {
        try self.container.fieldArbitraryDepth(null, val, options);
    }

    /// 开始一个以结构体为值的字段,并返回该结构体。
    pub fn beginStructField(
        self: *Tuple,
        options: ContainerOptions,
    ) Error!Struct {
        try self.fieldPrefix();
        return self.container.serializer.beginStruct(options);
    }

    /// 开始一个以元组为值的字段,并返回该元组。
    pub fn beginTupleField(
        self: *Tuple,
        options: ContainerOptions,
    ) Error!Tuple {
        try self.fieldPrefix();
        return self.container.serializer.beginTuple(options);
    }

    /// 打印字段前缀。根据配置打印必要的逗号和空白。若希望自行序列化字段值,此函数很有用。
    ///
    pub fn fieldPrefix(self: *Tuple) Error!void {
        try self.container.fieldPrefix(null);
    }
};

/// 逐字段写出 ZON 结构体。
pub const Struct = struct {
    container: Container,

    fn begin(parent: *Serializer, options: ContainerOptions) Error!Struct {
        return .{
            .container = try Container.begin(parent, .named, options),
        };
    }

    /// 完成结构体序列化。
    ///
    /// 按配置在适当时打印尾随逗号,并打印闭合括号。
    pub fn end(self: *Struct) Error!void {
        try self.container.end();
        self.* = undefined;
    }

    /// 序列化字段。等价于依次调用 `fieldPrefix` 和 `value`。
    pub fn field(
        self: *Struct,
        name: []const u8,
        val: anytype,
        options: ValueOptions,
    ) Error!void {
        try self.container.field(name, val, options);
    }

    /// 序列化字段。等价于依次调用 `fieldPrefix` 和 `valueMaxDepth`。
    /// 超过 `depth` 时返回 `error.ExceededMaxDepth`。
    pub fn fieldMaxDepth(
        self: *Struct,
        name: []const u8,
        val: anytype,
        options: ValueOptions,
        depth: usize,
    ) DepthError!void {
        try self.container.fieldMaxDepth(name, val, options, depth);
    }

    /// 序列化字段。等同于先调用 `fieldPrefix`,再调用 `valueArbitraryDepth`。
    ///
    pub fn fieldArbitraryDepth(
        self: *Struct,
        name: []const u8,
        val: anytype,
        options: ValueOptions,
    ) Error!void {
        try self.container.fieldArbitraryDepth(name, val, options);
    }

    /// 开始一个以结构体为值的字段,并返回该结构体。
    pub fn beginStructField(
        self: *Struct,
        name: []const u8,
        options: ContainerOptions,
    ) Error!Struct {
        try self.fieldPrefix(name);
        return self.container.serializer.beginStruct(options);
    }

    /// 开始一个以元组为值的字段,并返回该元组。
    pub fn beginTupleField(
        self: *Struct,
        name: []const u8,
        options: ContainerOptions,
    ) Error!Tuple {
        try self.fieldPrefix(name);
        return self.container.serializer.beginTuple(options);
    }

    /// 打印字段前缀,包括必要的逗号、字段名(必要时转义),
    /// 以及按配置设置的空白。适用于
    /// 希望自行序列化字段值的情况。
    pub fn fieldPrefix(self: *Struct, name: []const u8) Error!void {
        try self.container.fieldPrefix(name);
    }
};

const Container = struct {
    const FieldStyle = enum { named, anon };

    serializer: *Serializer,
    field_style: FieldStyle,
    options: ContainerOptions,
    empty: bool,

    fn begin(
        sz: *Serializer,
        field_style: FieldStyle,
        options: ContainerOptions,
    ) Error!Container {
        if (options.shouldWrap()) sz.indent_level +|= 1;
        try sz.writer.writeAll(".{");
        return .{
            .serializer = sz,
            .field_style = field_style,
            .options = options,
            .empty = true,
        };
    }

    fn end(self: *Container) Error!void {
        if (self.options.shouldWrap()) self.serializer.indent_level -|= 1;
        if (!self.empty) {
            if (self.options.shouldWrap()) {
                if (self.serializer.options.whitespace) {
                    try self.serializer.writer.writeByte(',');
                }
                try self.serializer.newline();
                try self.serializer.indent();
            } else if (!self.shouldElideSpaces()) {
                try self.serializer.space();
            }
        }
        try self.serializer.writer.writeByte('}');
        self.* = undefined;
    }

    fn fieldPrefix(self: *Container, name: ?[]const u8) Error!void {
        if (!self.empty) {
            try self.serializer.writer.writeByte(',');
        }
        self.empty = false;
        if (self.options.shouldWrap()) {
            try self.serializer.newline();
        } else if (!self.shouldElideSpaces()) {
            try self.serializer.space();
        }
        if (self.options.shouldWrap()) try self.serializer.indent();
        if (name) |n| {
            try self.serializer.ident(n);
            try self.serializer.space();
            try self.serializer.writer.writeByte('=');
            try self.serializer.space();
        }
    }

    fn field(
        self: *Container,
        name: ?[]const u8,
        val: anytype,
        options: ValueOptions,
    ) Error!void {
        comptime assert(!typeIsRecursive(@TypeOf(val)));
        try self.fieldArbitraryDepth(name, val, options);
    }

    /// 超过 `depth` 时返回 `error.ExceededMaxDepth`。
    fn fieldMaxDepth(
        self: *Container,
        name: ?[]const u8,
        val: anytype,
        options: ValueOptions,
        depth: usize,
    ) DepthError!void {
        try checkValueDepth(val, depth);
        try self.fieldArbitraryDepth(name, val, options);
    }

    fn fieldArbitraryDepth(
        self: *Container,
        name: ?[]const u8,
        val: anytype,
        options: ValueOptions,
    ) Error!void {
        try self.fieldPrefix(name);
        try self.serializer.valueArbitraryDepth(val, options);
    }

    fn shouldElideSpaces(self: *const Container) bool {
        return switch (self.options.whitespace_style) {
            .fields => |fields| self.field_style != .named and fields == 1,
            else => false,
        };
    }
};

test Serializer {
    var discarding: Writer.Discarding = .init(&.{});
    var s: Serializer = .{ .writer = &discarding.writer };
    var vec2 = try s.beginStruct(.{});
    try vec2.field("x", 1.5, .{});
    try vec2.fieldPrefix("prefix");
    try s.value(2.5, .{});
    try vec2.end();
}

inline fn typeIsRecursive(comptime T: type) bool {
    return comptime typeIsRecursiveInner(T, &.{});
}

fn typeIsRecursiveInner(comptime T: type, comptime prev_visited: []const type) bool {
    for (prev_visited) |V| {
        if (V == T) return true;
    }
    const visited = prev_visited ++ .{T};

    return switch (@typeInfo(T)) {
        .pointer => |pointer| typeIsRecursiveInner(pointer.child, visited),
        .optional => |optional| typeIsRecursiveInner(optional.child, visited),
        .array => |array| typeIsRecursiveInner(array.child, visited),
        .vector => |vector| typeIsRecursiveInner(vector.child, visited),
        .@"struct" => |@"struct"| for (@"struct".field_types) |field_type| {
            if (typeIsRecursiveInner(field_type, visited)) break true;
        } else false,
        .@"union" => |@"union"| inline for (@"union".field_types) |field_type| {
            if (typeIsRecursiveInner(field_type, visited)) break true;
        } else false,
        else => false,
    };
}

test typeIsRecursive {
    try std.testing.expect(!typeIsRecursive(bool));
    try std.testing.expect(!typeIsRecursive(struct { x: i32, y: i32 }));
    try std.testing.expect(!typeIsRecursive(struct { i32, i32 }));
    try std.testing.expect(typeIsRecursive(struct { x: i32, y: i32, z: *@This() }));
    try std.testing.expect(typeIsRecursive(struct {
        a: struct {
            const A = @This();
            b: struct {
                c: *struct {
                    a: ?A,
                },
            },
        },
    }));
    try std.testing.expect(typeIsRecursive(struct {
        a: [3]*@This(),
    }));
    try std.testing.expect(typeIsRecursive(struct {
        a: union { a: i32, b: *@This() },
    }));
}

fn checkValueDepth(val: anytype, depth: usize) error{ExceededMaxDepth}!void {
    if (depth == 0) return error.ExceededMaxDepth;
    const child_depth = depth - 1;

    switch (@typeInfo(@TypeOf(val))) {
        .pointer => |pointer| switch (pointer.size) {
            .one => try checkValueDepth(val.*, child_depth),
            .slice => for (val) |item| {
                try checkValueDepth(item, child_depth);
            },
            .c, .many => {},
        },
        .array => for (val) |item| {
            try checkValueDepth(item, child_depth);
        },
        .@"struct" => |@"struct"| inline for (@"struct".field_names) |field_name| {
            try checkValueDepth(@field(val, field_name), child_depth);
        },
        .@"union" => |@"union"| if (@"union".tag_type == null) {
            return;
        } else switch (val) {
            inline else => |payload| {
                return checkValueDepth(payload, child_depth);
            },
        },
        .optional => if (val) |inner| try checkValueDepth(inner, child_depth),
        else => {},
    }
}

fn expectValueDepthEquals(expected: usize, v: anytype) !void {
    try checkValueDepth(v, expected);
    try std.testing.expectError(error.ExceededMaxDepth, checkValueDepth(v, expected - 1));
}

test checkValueDepth {
    try expectValueDepthEquals(1, 10);
    try expectValueDepthEquals(2, .{ .x = 1, .y = 2 });
    try expectValueDepthEquals(2, .{ 1, 2 });
    try expectValueDepthEquals(3, .{ 1, .{ 2, 3 } });
    try expectValueDepthEquals(3, .{ .{ 1, 2 }, 3 });
    try expectValueDepthEquals(3, .{ .x = 0, .y = 1, .z = .{ .x = 3 } });
    try expectValueDepthEquals(3, .{ .x = 0, .y = .{ .x = 1 }, .z = 2 });
    try expectValueDepthEquals(3, .{ .x = .{ .x = 0 }, .y = 1, .z = 2 });
    try expectValueDepthEquals(2, @as(?u32, 1));
    try expectValueDepthEquals(1, @as(?u32, null));
    try expectValueDepthEquals(1, null);
    try expectValueDepthEquals(3, &@as(?u32, 1));

    // 该指针会丢失隐式编译时属性,因此这里需要显式指定 'comptime'。
    try comptime expectValueDepthEquals(2, &1);

    const Union = union(enum) {
        x: u32,
        y: struct { x: u32 },
    };
    try expectValueDepthEquals(2, Union{ .x = 1 });
    try expectValueDepthEquals(3, Union{ .y = .{ .x = 1 } });

    const Recurse = struct { r: ?*const @This() };
    try expectValueDepthEquals(2, Recurse{ .r = null });
    try expectValueDepthEquals(5, Recurse{ .r = &Recurse{ .r = null } });
    try expectValueDepthEquals(8, Recurse{ .r = &Recurse{ .r = &Recurse{ .r = null } } });

    try expectValueDepthEquals(2, @as([]const u8, &.{ 1, 2, 3 }));
    try expectValueDepthEquals(3, @as([]const []const u8, &.{&.{ 1, 2, 3 }}));
}

inline fn assertCanSerializeType(T: type) void {
    if (!canSerializeType(T)) @compileError("cannot serialize: " ++ @typeName(T));
}

inline fn canSerializeType(T: type) bool {
    comptime return canSerializeTypeInner(T, &.{}, false);
}

fn canSerializeTypeInner(
    T: type,
    /// 已访问的结构体和联合体,用于避免无限递归。
    /// 无需跟踪更多类型;可选类型嵌套也会使跟踪更复杂。
    visited: []const type,
    parent_is_optional: bool,
) bool {
    return switch (@typeInfo(T)) {
        .bool,
        .int,
        .float,
        .comptime_float,
        .comptime_int,
        .null,
        .enum_literal,
        => true,

        .noreturn,
        .void,
        .type,
        .undefined,
        .error_union,
        .error_set,
        .@"fn",
        .frame,
        .@"anyframe",
        .@"opaque",
        .spirv,
        => false,

        .@"enum" => |@"enum"| @"enum".mode == .exhaustive,

        .pointer => |pointer| switch (pointer.size) {
            .one => canSerializeTypeInner(pointer.child, visited, parent_is_optional),
            .slice => canSerializeTypeInner(pointer.child, visited, false),
            .many, .c => false,
        },

        .optional => |optional| if (parent_is_optional)
            false
        else
            canSerializeTypeInner(optional.child, visited, true),

        .array => |array| canSerializeTypeInner(array.child, visited, false),
        .vector => |vector| canSerializeTypeInner(vector.child, visited, false),

        .@"struct" => |@"struct"| {
            for (visited) |V| if (T == V) return true;
            const new_visited = visited ++ .{T};
            for (@"struct".field_types) |field_type| {
                if (!canSerializeTypeInner(field_type, new_visited, false)) return false;
            }
            return true;
        },
        .@"union" => |@"union"| {
            for (visited) |V| if (T == V) return true;
            const new_visited = visited ++ .{T};
            if (@"union".tag_type == null) return false;
            for (@"union".field_types) |field_type| {
                if (field_type != void and !canSerializeTypeInner(field_type, new_visited, false)) {
                    return false;
                }
            }
            return true;
        },
    };
}

test canSerializeType {
    try std.testing.expect(!comptime canSerializeType(void));
    try std.testing.expect(!comptime canSerializeType(struct { f: [*]u8 }));
    try std.testing.expect(!comptime canSerializeType(struct { error{foo} }));
    try std.testing.expect(!comptime canSerializeType(union(enum) { a: void, f: [*c]u8 }));
    try std.testing.expect(!comptime canSerializeType(@Vector(0, [*c]u8)));
    try std.testing.expect(!comptime canSerializeType(*?[*c]u8));
    try std.testing.expect(!comptime canSerializeType(enum(u8) { _ }));
    try std.testing.expect(!comptime canSerializeType(union { foo: void }));
    try std.testing.expect(comptime canSerializeType(union(enum) { foo: void }));
    try std.testing.expect(comptime canSerializeType(comptime_float));
    try std.testing.expect(comptime canSerializeType(comptime_int));
    try std.testing.expect(!comptime canSerializeType(struct { comptime foo: ??u8 = null }));
    try std.testing.expect(comptime canSerializeType(@TypeOf(.foo)));
    try std.testing.expect(comptime canSerializeType(?u8));
    try std.testing.expect(comptime canSerializeType(*?*u8));
    try std.testing.expect(comptime canSerializeType(?struct {
        foo: ?struct {
            ?union(enum) {
                a: ?@Vector(0, ?*u8),
            },
            ?struct {
                f: ?[]?u8,
            },
        },
    }));
    try std.testing.expect(!comptime canSerializeType(??u8));
    try std.testing.expect(!comptime canSerializeType(?*?u8));
    try std.testing.expect(!comptime canSerializeType(*?*?*u8));
    try std.testing.expect(comptime canSerializeType(struct { x: comptime_int = 2 }));
    try std.testing.expect(comptime canSerializeType(struct { x: comptime_float = 2 }));
    try std.testing.expect(comptime canSerializeType(struct { comptime_int }));
    try std.testing.expect(comptime canSerializeType(struct { comptime x: @TypeOf(.foo) = .foo }));
    const Recursive = struct { foo: ?*@This() };
    try std.testing.expect(comptime canSerializeType(Recursive));

    // 确保在因已经遇到类型递归而提前退出之前,
    // 先验证嵌套的可选类型!
    try std.testing.expect(!comptime canSerializeType(struct {
        add_to_visited: ?u8,
        retrieve_from_visited: ??u8,
    }));
}