Zig 0.17.0-dev (Split by item)

Shortcut keys
?
Show these tips
S
Focus search field
Esc
Clear focus & close tips
U
Jump to source code
↑
Move up in search results
↓
Move down in search results
↵
Go to active search result
This is an example of documentation generated by ZigDoc, an alternative to Zig's built-in Auto Doc feature. See also examples in other modes/formats. The project being documented here (as the example) is the Zig standard library. Public Struct

Serializer

Public Struct

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

Namespaces

Structs

Types

Values

Functions

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

Serialize a value, similar to serialize.

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

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

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

Serialize a value, similar to serializeArbitraryDepth.

fn valueArbitraryDepthArray(s: *Serializer, comptime A: type, array: *const A, options: ValueOptions) Error!void
pub fn int(self: *Serializer, val: anytype) Error!void

Serialize an integer.

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

Serialize a float.

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

Serialize name as an identifier prefixed with ..

Escapes the identifier if necessary.

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

Serialize val as a Unicode codepoint.

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

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

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 tupleMaxDepth(self: *Serializer, val: anytype, options: ValueOptions, depth: usize) DepthError!void

Like tuple, but recursive types are allowed.

Returns error.ExceededMaxDepth if depth is exceeded.

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

Like tuple, but recursive types are allowed.

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

fn tupleImpl(self: *Serializer, val: anytype, options: ValueOptions) Error!void
fn writeCodepoint(self: *Serializer, codepoint: u21, options: WriteCodepointOptions) CodePointError!void

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

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

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

Like value, but always serializes val as a string.

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

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 beginStruct(self: *Serializer, options: ContainerOptions) Error!Struct

Create a Struct for writing ZON structs field by field.

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

Creates a Tuple for writing ZON tuples field by field.

fn indent(self: *Serializer) Error!void
fn newline(self: *Serializer) Error!void
fn newlineOrSpace(self: *Serializer, len: usize) Error!void
fn space(self: *Serializer) Error!void
inline fn typeIsRecursive(comptime T: type) bool
fn typeIsRecursiveInner(comptime T: type, comptime prev_visited: []const type) bool
fn checkValueDepth(val: anytype, depth: usize) error
fn expectValueDepthEquals(expected: usize, v: anytype) !void
inline fn assertCanSerializeType(T: type) void
inline fn canSerializeType(T: type) bool
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

File

zon/Serializer.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
//! 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 {
    try self.writer.writeByte('"');
    // Batch write sequences of "raw" bytes (printable ASCII or non-escaped non-ASCII) for performance.
    // `val[start..i]` contains pending raw bytes to write.
    var start: usize = 0;
    var i: usize = 0;
    while (i < val.len) {
        const byte = val[i];
        // Check if this byte can be written as-is
        const is_raw = switch (byte) {
            ' ', '!', '#'...'[', ']'...'~' => true,
            0x80...0xFF => !options.escape_non_ascii,
            else => false,
        };
        if (is_raw) {
            i += 1;
            continue;
        }
        // Flush pending raw bytes
        try self.writer.writeAll(val[start..i]);
        // Handle the special character
        if (byte >= 0x80) {
            // Decode UTF-8 sequence and write the codepoint
            const ulen = std.unicode.utf8ByteSequenceLength(byte) catch unreachable;
            const codepoint = std.unicode.utf8Decode(val[i..][0..ulen]) catch unreachable;
            // InvalidCodepoint cannot occur from valid UTF-8
            self.writeCodepoint(codepoint, .{
                .escape_non_ascii = options.escape_non_ascii,
                .quote_style = .double,
            }) catch unreachable;
            i += ulen;
        } else {
            // ASCII character that needs escaping
            self.writeCodepoint(byte, .{
                .escape_non_ascii = options.escape_non_ascii,
                .quote_style = .double,
            }) catch unreachable; // InvalidCodepoint cannot occur for valid ASCII values
            i += 1;
        }
        start = i;
    }

    try self.writer.writeAll(val[start..]);
    try self.writer.writeByte('"');
}

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