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 Function

string

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

Like value, but always serializes val as a string.

Params

File

zon/Serializer.zig:412
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
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('"');
}