Skip to content
Standard libraryZig 0.17.1Official documentation
Sourcestd/zon/Serializer.zig

Source line 1

Lower level control over serialization, you can create a new instance with serializer.

Useful when you want control over which fields are serialized, how they're represented, or want to write a ZON object that does not exist in memory.

You can serialize values with value. To serialize recursive types, the following are provided:

You can also serialize values using specific notations:

For manual serialization of containers, see:

Fields

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

std.zon.Serializer.A

alias

Source line 893

Alias of std.zon.Serializer

std.zon.Serializer.assert

alias

Source line 30

Alias of std.debug.assert

std.zon.Serializer.assertCanSerializeType

function

Source line 977

inline fn assertCanSerializeType(T: type) void

Parameters

T: type

std.zon.Serializer.beginStruct

function

Source line 565

Create a Struct for writing ZON structs field by field.

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

Parameters

self: *Serializer
options: ContainerOptions

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.beginTuple

function

Source line 570

Creates a Tuple for writing ZON tuples field by field.

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

Parameters

self: *Serializer
options: ContainerOptions

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.canSerializeType

function

Source line 981

inline fn canSerializeType(T: type) bool

Parameters

T: type

Example usage

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));

    // Make sure we validate nested optional before we early out due to already having seen
    // a type recursion!
    try std.testing.expect(!comptime canSerializeType(struct {
        add_to_visited: ?u8,
        retrieve_from_visited: ??u8,
    }));
}

std.zon.Serializer.canSerializeTypeInner

function

Source line 985

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

Parameters

T: type
visited: []const type

Visited structs and unions, to avoid infinite recursion. Tracking more types is unnecessary, and a little complex due to optional nesting.

parent_is_optional: bool

std.zon.Serializer.checkValueDepth

function

Source line 909

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

Parameters

depth: usize

Errors

ExceededMaxDepth

Example usage

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));

    // The pointer drops the implicit comptime-ness, so we need to specify 'comptime' here
    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

function

Source line 297

Serialize val as a Unicode codepoint.

Returns error.InvalidCodepoint if val is not a valid Unicode codepoint.

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

Parameters

self: *Serializer
val: u21
options: CodePointOptions

Errors

InvalidCodepoint
WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.CodePointError

error-set

Source line 288

Errors

InvalidCodepoint
WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.CodePointOptions

container

Source line 290

Options for formatting code points.

Fields

escape_non_ascii: bool = false

std.zon.Serializer.Container

container

Source line 752

Fields

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

std.zon.Serializer.Container.begin

function

Source line 760

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

Parameters

sz: *Serializer
field_style: FieldStyle
options: ContainerOptions

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Container.end

function

Source line 775

fn end(self: *Container) Error!void

Parameters

self: *Container

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Container.field

function

Source line 811

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

Parameters

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

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Container.fieldArbitraryDepth

function

Source line 833

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

Parameters

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

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Container.fieldMaxDepth

function

Source line 822

Returns error.ExceededMaxDepth if depth is exceeded.

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

Parameters

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

Errors

ExceededMaxDepth
WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Container.fieldPrefix

function

Source line 792

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

Parameters

self: *Container
name: ?[]const u8

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Container.FieldStyle

container

Source line 753

Fields

named
anon

std.zon.Serializer.Container.shouldElideSpaces

function

Source line 843

fn shouldElideSpaces(self: *const Container) bool

Parameters

self: *const Container

std.zon.Serializer.ContainerOptions

container

Source line 42

Options for manual serialization of container types.

Fields

whitespace_style: union(enum) {
    /// If true, wrap every field. If false do not.
    wrap: bool,
    /// Automatically decide whether to wrap or not based on the number of fields. Following
    /// the standard rule of thumb, containers with more than two fields are wrapped.
    fields: usize,
} = .{ .wrap = true }

The whitespace style that should be used for this container. Ignored if whitespace is off.

std.zon.Serializer.ContainerOptions.shouldWrap

function

Source line 52

fn shouldWrap(self: ContainerOptions) bool

Parameters

std.zon.Serializer.DepthError

error-set

Source line 34

Errors

ExceededMaxDepth
WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.EmitCodepointLiterals

container

Source line 71

Determines when to emit Unicode code point literals as opposed to integer literals.

Fields

never

Never emit Unicode code point literals.

printable_ascii

Emit Unicode code point literals for any u8 in the printable ASCII range.

always

Emit Unicode code point literals for any unsigned integer with 21 bits or fewer whose value is a valid non-surrogate code point.

std.zon.Serializer.EmitCodepointLiterals.emitAsCodepoint

function

Source line 81

If the value should be emitted as a Unicode codepoint, return it as a u21.

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

Parameters

self: @This()

std.zon.Serializer.Error

alias

Source line 33

Alias of std.Io.Writer.Error

std.zon.Serializer.expectValueDepthEquals

function

Source line 939

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

Parameters

expected: usize

std.zon.Serializer.float

function

Source line 259

Serialize a float.

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

Parameters

self: *Serializer

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.fuzzString

function

Source line 478

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

Parameters

options: StringOptions
smith: *std.testing.Smith

std.zon.Serializer.ident

function

Source line 284

Serialize name as an identifier prefixed with ..

Escapes the identifier if necessary.

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

Parameters

self: *Serializer
name: []const u8

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.indent

function

Source line 574

fn indent(self: *Serializer) Error!void

Parameters

self: *Serializer

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.int

function

Source line 254

Serialize an integer.

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

Parameters

self: *Serializer

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.multilineString

function

Source line 523

Like value, but always serializes to a multiline string literal.

Returns error.InnerCarriageReturn if val contains a CR not followed by a newline, since multiline strings cannot represent CR without a following newline.

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

Parameters

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

Errors

InnerCarriageReturn
WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.MultilineStringError

error-set

Source line 517

Errors

InnerCarriageReturn
WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.MultilineStringOptions

container

Source line 510

Options for formatting multiline strings.

Fields

top_level: bool = false

If top level is true, whitespace before and after the multiline string is elided. If it is true, a newline is printed, then the value, followed by a newline, and if whitespace is true any necessary indentation follows.

std.zon.Serializer.newline

function

Source line 580

fn newline(self: *Serializer) Error!void

Parameters

self: *Serializer

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.newlineOrSpace

function

Source line 586

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

Parameters

self: *Serializer
len: usize

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Options

container

Source line 36

Fields

whitespace: bool = true

If false, only syntactically necessary whitespace is emitted.

std.zon.Serializer.Serializer

alias

Source line 28

Alias of std.zon.Serializer

std.zon.Serializer.space

function

Source line 594

fn space(self: *Serializer) Error!void

Parameters

self: *Serializer

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.std

alias

Source line 29

Alias of std

std.zon.Serializer.string

function

Source line 412

Like value, but always serializes val as a string.

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

Parameters

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

Errors

WriteFailed

See the Writer implementation for detailed diagnostics.

Example usage

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 });

    // Truncated UTF-8 sequence (0xe2 starts a 3-byte sequence, 0x80 is a valid continuation byte)
    try testString("\"\\xe2\\x80\"", &.{ 0xe2, 0x80 }, .{});
    try testString("\"\\xe2\\x80\"", &.{ 0xe2, 0x80 }, .{ .escape_non_ascii = true });
}

std.zon.Serializer.StringOptions

container

Source line 407

Fields

escape_non_ascii: bool = false

std.zon.Serializer.Struct

container

Source line 674

Writes ZON structs field by field.

Fields

container: Container

std.zon.Serializer.Struct.begin

function

Source line 677

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

Parameters

parent: *Serializer
options: ContainerOptions

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Struct.beginStructField

function

Source line 725

Starts a field with a struct as a value. Returns the struct.

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

Parameters

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

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Struct.beginTupleField

function

Source line 735

Starts a field with a tuple as a value. Returns the tuple.

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

Parameters

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

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Struct.end

function

Source line 686

Finishes serializing the struct.

Prints a trailing comma as configured when appropriate, and the closing bracket.

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

Parameters

self: *Struct

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Struct.field

function

Source line 692

Serialize a field. Equivalent to calling fieldPrefix followed by value.

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

Parameters

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

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Struct.fieldArbitraryDepth

function

Source line 715

Serialize a field. Equivalent to calling fieldPrefix followed by valueArbitraryDepth.

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

Parameters

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

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Struct.fieldMaxDepth

function

Source line 703

Serialize a field. Equivalent to calling fieldPrefix followed by valueMaxDepth. Returns error.ExceededMaxDepth if depth is exceeded.

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

Parameters

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

Errors

ExceededMaxDepth
WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Struct.fieldPrefix

function

Source line 747

Print a field prefix. This prints any necessary commas, the field name (escaped if necessary) and whitespace as configured. Useful if you want to serialize the field value yourself.

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

Parameters

self: *Struct
name: []const u8

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.testString

function

Source line 461

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

Parameters

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

std.zon.Serializer.tuple

function

Source line 313

Like value, but always serializes val as a tuple.

Will fail at comptime if val is not a tuple, array, pointer to an array, or slice.

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

Parameters

self: *Serializer
options: ValueOptions

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Tuple

container

Source line 601

Writes ZON tuples field by field.

Fields

container: Container

std.zon.Serializer.Tuple.begin

function

Source line 604

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

Parameters

parent: *Serializer
options: ContainerOptions

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Tuple.beginStructField

function

Source line 649

Starts a field with a struct as a value. Returns the struct.

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

Parameters

self: *Tuple
options: ContainerOptions

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Tuple.beginTupleField

function

Source line 658

Starts a field with a tuple as a value. Returns the tuple.

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

Parameters

self: *Tuple
options: ContainerOptions

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Tuple.end

function

Source line 613

Finishes serializing the tuple.

Prints a trailing comma as configured when appropriate, and the closing bracket.

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

Parameters

self: *Tuple

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Tuple.field

function

Source line 619

Serialize a field. Equivalent to calling fieldPrefix followed by value.

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

Parameters

self: *Tuple
options: ValueOptions

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Tuple.fieldArbitraryDepth

function

Source line 640

Serialize a field. Equivalent to calling fieldPrefix followed by valueArbitraryDepth.

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

Parameters

self: *Tuple
options: ValueOptions

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Tuple.fieldMaxDepth

function

Source line 629

Serialize a field. Equivalent to calling fieldPrefix followed by valueMaxDepth. Returns error.ExceededMaxDepth if depth is exceeded.

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

Parameters

self: *Tuple
options: ValueOptions
depth: usize

Errors

ExceededMaxDepth
WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.Tuple.fieldPrefix

function

Source line 668

Print a field prefix. This prints any necessary commas, and whitespace as configured. Useful if you want to serialize the field value yourself.

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

Parameters

self: *Tuple

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.tupleArbitraryDepth

function

Source line 334

Like tuple, but recursive types are allowed.

It is the caller's responsibility to ensure that val does not contain cycles.

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

Parameters

self: *Serializer
options: ValueOptions

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.tupleImpl

function

Source line 342

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

Parameters

self: *Serializer
options: ValueOptions

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.tupleMaxDepth

function

Source line 321

Like tuple, but recursive types are allowed.

Returns error.ExceededMaxDepth if depth is exceeded.

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

Parameters

self: *Serializer
options: ValueOptions
depth: usize

Errors

ExceededMaxDepth
WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.typeIsRecursive

function

Source line 861

inline fn typeIsRecursive(comptime T: type) bool

Parameters

T: type

Example usage

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

function

Source line 865

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

Parameters

T: type
prev_visited: []const type

std.zon.Serializer.value

function

Source line 112

Serialize a value, similar to serialize.

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

Parameters

self: *Serializer
options: ValueOptions

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.valueArbitraryDepth

function

Source line 125

Serialize a value, similar to serializeArbitraryDepth.

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

Parameters

self: *Serializer
options: ValueOptions

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.valueArbitraryDepthArray

function

Source line 243

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

Parameters

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

Errors

WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.valueMaxDepth

function

Source line 119

Serialize a value, similar to serializeMaxDepth. Can return error.ExceededMaxDepth.

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

Parameters

self: *Serializer
options: ValueOptions
depth: usize

Errors

ExceededMaxDepth
WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.ValueOptions

container

Source line 63

Options for serialization of an individual value.

See SerializeOptions for more information on these options.

Fields

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

function

Source line 373

Write a Unicode codepoint to the writer using the given options.

Returns error.InvalidCodepoint if codepoint is not a valid Unicode codepoint.

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

Parameters

self: *Serializer
codepoint: u21
options: WriteCodepointOptions

Errors

InvalidCodepoint
WriteFailed Error

See the Writer implementation for detailed diagnostics.

std.zon.Serializer.WriteCodepointOptions

container

Source line 364

Options for writing a Unicode codepoint.

Fields

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

If single quote style then single quotes are escaped, otherwise double quotes are escaped.

std.zon.Serializer.Writer

alias

Source line 31

Alias of std.Io.Writer

Source code

std/zon/Serializer.zig

//! Lower level control over serialization, you can create a new instance with `serializer`.
//!
//! Useful when you want control over which fields are serialized, how they're represented,
//! or want to write a ZON object that does not exist in memory.
//!
//! You can serialize values with `value`. To serialize recursive types, the following are provided:
//! * `valueMaxDepth`
//! * `valueArbitraryDepth`
//!
//! You can also serialize values using specific notations:
//! * `int`
//! * `float`
//! * `codePoint`
//! * `tuple`
//! * `tupleMaxDepth`
//! * `tupleArbitraryDepth`
//! * `string`
//! * `multilineString`
//!
//! For manual serialization of containers, see:
//! * `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 {
    /// If false, only syntactically necessary whitespace is emitted.
    whitespace: bool = true,
};

/// Options for manual serialization of container types.
pub const ContainerOptions = struct {
    /// The whitespace style that should be used for this container. Ignored if whitespace is off.
    whitespace_style: union(enum) {
        /// If true, wrap every field. If false do not.
        wrap: bool,
        /// Automatically decide whether to wrap or not based on the number of fields. Following
        /// the standard rule of thumb, containers with more than two fields are wrapped.
        fields: usize,
    } = .{ .wrap = true },

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

/// Options for serialization of an individual value.
///
/// See `SerializeOptions` for more information on these options.
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,
};

/// Determines when to emit Unicode code point literals as opposed to integer literals.
pub const EmitCodepointLiterals = enum {
    /// Never emit Unicode code point literals.
    never,
    /// Emit Unicode code point literals for any `u8` in the printable ASCII range.
    printable_ascii,
    /// Emit Unicode code point literals for any unsigned integer with 21 bits or fewer
    /// whose value is a valid non-surrogate code point.
    always,

    /// If the value should be emitted as a Unicode codepoint, return it as a u21.
    fn emitAsCodepoint(self: @This(), val: anytype) ?u21 {
        // Rule out incompatible integer types
        switch (@typeInfo(@TypeOf(val))) {
            .int => |int_info| if (int_info.signedness == .signed or int_info.bits > 21) {
                return null;
            },
            .comptime_int => {},
            else => comptime unreachable,
        }

        // Return null if the value shouldn't be printed as a Unicode codepoint, or the value casted
        // to a u21 if it should.
        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 a value, similar to `serialize`.
pub fn value(self: *Serializer, val: anytype, options: ValueOptions) Error!void {
    comptime assert(!typeIsRecursive(@TypeOf(val)));
    return self.valueArbitraryDepth(val, options);
}

/// Serialize a value, similar to `serializeMaxDepth`.
/// Can return `error.ExceededMaxDepth`.
pub fn valueMaxDepth(self: *Serializer, val: anytype, options: ValueOptions, depth: usize) DepthError!void {
    try checkValueDepth(val, depth);
    return self.valueArbitraryDepth(val, options);
}

/// Serialize a value, similar to `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, // Already validated
                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| {
            // Try to serialize as a string
            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 });
            }

            // Serialize as either a tuple or as the child type
            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 {
            // Decide which fields to emit
            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 };
            };

            // Emit those fields
            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();
}

/// Serialize an integer.
pub fn int(self: *Serializer, val: anytype) Error!void {
    try self.writer.printInt(val, 10, .lower, .{});
}

/// Serialize a float.
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,
    }
}

/// Serialize `name` as an identifier prefixed with `.`.
///
/// Escapes the identifier if necessary.
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};
/// Options for formatting code points.
pub const CodePointOptions = struct {
    escape_non_ascii: bool = false,
};

/// Serialize `val` as a Unicode codepoint.
///
/// Returns `error.InvalidCodepoint` if `val` is not a valid Unicode codepoint.
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('\'');
}

/// Like `value`, but always serializes `val` as a tuple.
///
/// Will fail at comptime if `val` is not a tuple, array, pointer to an array, or slice.
pub fn tuple(self: *Serializer, val: anytype, options: ValueOptions) Error!void {
    comptime assert(!typeIsRecursive(@TypeOf(val)));
    try self.tupleArbitraryDepth(val, options);
}

/// Like `tuple`, but recursive types are allowed.
///
/// Returns `error.ExceededMaxDepth` if `depth` is exceeded.
pub fn tupleMaxDepth(
    self: *Serializer,
    val: anytype,
    options: ValueOptions,
    depth: usize,
) DepthError!void {
    try checkValueDepth(val, depth);
    try self.tupleArbitraryDepth(val, options);
}

/// Like `tuple`, but recursive types are allowed.
///
/// It is the caller's responsibility to ensure that `val` does not contain cycles.
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,
    }
}

/// Options for writing a Unicode codepoint.
const WriteCodepointOptions = struct {
    escape_non_ascii: bool = false,
    /// If single quote style then single quotes are escaped, otherwise double quotes are escaped.
    quote_style: enum { single, double } = .single,
};

/// Write a Unicode codepoint to the writer using the given options.
///
/// Returns `error.InvalidCodepoint` if `codepoint` is not a valid Unicode codepoint.
fn writeCodepoint(
    self: *Serializer,
    codepoint: u21,
    options: WriteCodepointOptions,
) CodePointError!void {
    switch (codepoint) {
        // Printable ASCII
        ' ', '!', '#'...'&', '('...'[', ']'...'~' => try self.writer.writeByte(@intCast(codepoint)),
        // Unprintable ASCII
        0x00...0x08, 0x0B, 0x0C, 0x0E...0x1F, 0x7F => try self.writer.print("\\x{x:0>2}", .{codepoint}),
        // ASCII with special escapes
        '\n' => try self.writer.writeAll("\\n"),
        '\r' => try self.writer.writeAll("\\r"),
        '\t' => try self.writer.writeAll("\\t"),
        '\\' => try self.writer.writeAll("\\\\"),
        // Quotes need escaping if they conflict with the in-use quote character
        '\'' => 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('"'),

        // Surrogates can only be written with an escape
        0xD800...0xDFFF => try self.writer.print("\\u{{{x}}}", .{codepoint}),
        // Other valid codepoints
        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]);
        },
        // Invalid codepoints
        0x110000...std.math.maxInt(u21) => return error.InvalidCodepoint,
    }
}

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

/// Like `value`, but always serializes `val` as a string.
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) {
                    // Truncated UTF-8 sequence
                    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 });

    // Truncated UTF-8 sequence (0xe2 starts a 3-byte sequence, 0x80 is a valid continuation byte)
    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);
}

/// Options for formatting multiline strings.
pub const MultilineStringOptions = struct {
    /// If top level is true, whitespace before and after the multiline string is elided.
    /// If it is true, a newline is printed, then the value, followed by a newline, and if
    /// whitespace is true any necessary indentation follows.
    top_level: bool = false,
};

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

/// Like `value`, but always serializes to a multiline string literal.
///
/// Returns `error.InnerCarriageReturn` if `val` contains a CR not followed by a newline,
/// since multiline strings cannot represent CR without a following newline.
pub fn multilineString(
    self: *Serializer,
    val: []const u8,
    options: MultilineStringOptions,
) MultilineStringError!void {
    // Make sure the string does not contain any carriage returns not followed by a newline
    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); // We write newlines here even if whitespace off
            if (c == '\n') {
                try self.indent();
                try self.writer.writeAll("\\\\");
            }
        }
    }

    if (!options.top_level) {
        try self.writer.writeByte('\n'); // Even if whitespace off
        try self.indent();
    }
}

/// Create a `Struct` for writing ZON structs field by field.
pub fn beginStruct(self: *Serializer, options: ContainerOptions) Error!Struct {
    return Struct.begin(self, options);
}

/// Creates a `Tuple` for writing ZON tuples field by field.
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(' ');
    }
}

/// Writes ZON tuples field by field.
pub const Tuple = struct {
    container: Container,

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

    /// Finishes serializing the tuple.
    ///
    /// Prints a trailing comma as configured when appropriate, and the closing bracket.
    pub fn end(self: *Tuple) Error!void {
        try self.container.end();
        self.* = undefined;
    }

    /// Serialize a field. Equivalent to calling `fieldPrefix` followed by `value`.
    pub fn field(
        self: *Tuple,
        val: anytype,
        options: ValueOptions,
    ) Error!void {
        try self.container.field(null, val, options);
    }

    /// Serialize a field. Equivalent to calling `fieldPrefix` followed by `valueMaxDepth`.
    /// Returns `error.ExceededMaxDepth` if `depth` is exceeded.
    pub fn fieldMaxDepth(
        self: *Tuple,
        val: anytype,
        options: ValueOptions,
        depth: usize,
    ) DepthError!void {
        try self.container.fieldMaxDepth(null, val, options, depth);
    }

    /// Serialize a field. Equivalent to calling `fieldPrefix` followed by
    /// `valueArbitraryDepth`.
    pub fn fieldArbitraryDepth(
        self: *Tuple,
        val: anytype,
        options: ValueOptions,
    ) Error!void {
        try self.container.fieldArbitraryDepth(null, val, options);
    }

    /// Starts a field with a struct as a value. Returns the struct.
    pub fn beginStructField(
        self: *Tuple,
        options: ContainerOptions,
    ) Error!Struct {
        try self.fieldPrefix();
        return self.container.serializer.beginStruct(options);
    }

    /// Starts a field with a tuple as a value. Returns the tuple.
    pub fn beginTupleField(
        self: *Tuple,
        options: ContainerOptions,
    ) Error!Tuple {
        try self.fieldPrefix();
        return self.container.serializer.beginTuple(options);
    }

    /// Print a field prefix. This prints any necessary commas, and whitespace as
    /// configured. Useful if you want to serialize the field value yourself.
    pub fn fieldPrefix(self: *Tuple) Error!void {
        try self.container.fieldPrefix(null);
    }
};

/// Writes ZON structs field by field.
pub const Struct = struct {
    container: Container,

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

    /// Finishes serializing the struct.
    ///
    /// Prints a trailing comma as configured when appropriate, and the closing bracket.
    pub fn end(self: *Struct) Error!void {
        try self.container.end();
        self.* = undefined;
    }

    /// Serialize a field. Equivalent to calling `fieldPrefix` followed by `value`.
    pub fn field(
        self: *Struct,
        name: []const u8,
        val: anytype,
        options: ValueOptions,
    ) Error!void {
        try self.container.field(name, val, options);
    }

    /// Serialize a field. Equivalent to calling `fieldPrefix` followed by `valueMaxDepth`.
    /// Returns `error.ExceededMaxDepth` if `depth` is exceeded.
    pub fn fieldMaxDepth(
        self: *Struct,
        name: []const u8,
        val: anytype,
        options: ValueOptions,
        depth: usize,
    ) DepthError!void {
        try self.container.fieldMaxDepth(name, val, options, depth);
    }

    /// Serialize a field. Equivalent to calling `fieldPrefix` followed by
    /// `valueArbitraryDepth`.
    pub fn fieldArbitraryDepth(
        self: *Struct,
        name: []const u8,
        val: anytype,
        options: ValueOptions,
    ) Error!void {
        try self.container.fieldArbitraryDepth(name, val, options);
    }

    /// Starts a field with a struct as a value. Returns the struct.
    pub fn beginStructField(
        self: *Struct,
        name: []const u8,
        options: ContainerOptions,
    ) Error!Struct {
        try self.fieldPrefix(name);
        return self.container.serializer.beginStruct(options);
    }

    /// Starts a field with a tuple as a value. Returns the tuple.
    pub fn beginTupleField(
        self: *Struct,
        name: []const u8,
        options: ContainerOptions,
    ) Error!Tuple {
        try self.fieldPrefix(name);
        return self.container.serializer.beginTuple(options);
    }

    /// Print a field prefix. This prints any necessary commas, the field name (escaped if
    /// necessary) and whitespace as configured. Useful if you want to serialize the field
    /// value yourself.
    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);
    }

    /// Returns `error.ExceededMaxDepth` if `depth` is exceeded.
    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));

    // The pointer drops the implicit comptime-ness, so we need to specify 'comptime' here
    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 structs and unions, to avoid infinite recursion.
    /// Tracking more types is unnecessary, and a little complex due to optional nesting.
    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));

    // Make sure we validate nested optional before we early out due to already having seen
    // a type recursion!
    try std.testing.expect(!comptime canSerializeType(struct {
        add_to_visited: ?u8,
        retrieve_from_visited: ??u8,
    }));
}