向流写入 JSON(RFC8259)格式的 数据。
写入 JSON 内容的方法调用序列必须遵循以下语法:
<once> = <value>
<value> =
| <object>
| <array>
| write
| print
| <writeRawStream>
<object> = beginObject ( <field> <value> )* endObject
<field> = objectField | objectFieldRaw | <objectFieldRawStream>
<array> = beginArray ( <value> )* endArray
<writeRawStream> = beginWriteRaw ( stream.writeAll )* endWriteRaw
<objectFieldRawStream> = beginObjectFieldRaw ( stream.writeAll )* endObjectFieldRaw
字段
writer: *Writer
options: Options = .{}
indent_level: usize = 0
next_punctuation: enum {
the_beginning,
none,
comma,
colon,
} = .the_beginning
nesting_stack: switch (safety_checks) {
.checked_to_fixed_depth => |fixed_buffer_size| [(fixed_buffer_size + 7) >> 3]u8,
.assumed_correct => void,
} = switch (safety_checks) {
.checked_to_fixed_depth => @splat(0),
.assumed_correct => {},
}
raw_streaming_mode: if (build_mode_has_safety)
enum { none, value, objectField }
else
void = if (build_mode_has_safety) .none else {}
stdassertAllocatorArrayListBitStackStringifyWriterIndentationModebuild_mode_has_safetysafety_checks_hintsafety_checksErrorbeginArraybeginObjectendArrayendObjectpushIndentationpopIndentationindentvalueStartobjectFieldStartvalueStartAssumeTypeOkvalueDoneisObjectKeyExpectedisCompleteprintbeginWriteRawendWriteRawobjectFieldobjectFieldRawbeginObjectFieldRawendObjectFieldRawwritestringValueOptionsvaluevalueAllocoutputUnicodeEscapeoutputSpecialEscapeencodeJsonStringencodeJsonStringCharstestBasicWriteStreamgetJsonObjectSelfjsonStringifytestStringify
std.json.Stringify.Allocator
别名
别名目标 std.mem.Allocator
std.json.Stringify.ArrayList
别名
别名目标 std.ArrayList
std.json.Stringify.assert
别名
别名目标 std.debug.assert
std.json.Stringify.beginArray
函数
pub fn beginArray(self: *Stringify) Error!void
参数
self: *Stringify
错误
std.json.Stringify.beginObject
函数
pub fn beginObject(self: *Stringify) Error!void
参数
self: *Stringify
错误
std.json.Stringify.beginObjectFieldRaw
函数
极少数情况下可能需要写入很长的对象字段名;
此函数可替代 objectField 和 objectFieldRaw,允许直接写入 .writer 字段,
类似 beginWriteRaw。
完成后调用 endObjectFieldRaw()。
pub fn beginObjectFieldRaw(self: *Stringify) !void
参数
self: *Stringify
std.json.Stringify.beginWriteRaw
函数
替代调用 write 的方式,允许直接写入 .writer 字段,例如 .writer.writeAll()。
先调用 beginWriteRaw(),再将完整值直接写入 .writer 字段,必要时包含引号,
最后调用 endWriteRaw()。
可用于将很长的字符串流式写入输出,而无需先全部缓冲到内存。
pub fn beginWriteRaw(self: *Stringify) !void
参数
self: *Stringify
std.json.Stringify.BitStack
别名
别名目标 std.BitStack
std.json.Stringify.build_mode_has_safety
常量
std.json.Stringify.encodeJsonString
函数
将 string 作为 JSON 编码字符串写入 writer。
pub fn encodeJsonString(string: []const u8, options: Options, writer: *Writer) Error!void
参数
错误
std.json.Stringify.encodeJsonStringChars
函数
将 chars 作为经 JSON 编码的字符串字符写入 writer。
pub fn encodeJsonStringChars(chars: []const u8, options: Options, writer: *Writer) Error!void
参数
错误
std.json.Stringify.endArray
函数
pub fn endArray(self: *Stringify) Error!void
参数
self: *Stringify
错误
std.json.Stringify.endObject
函数
pub fn endObject(self: *Stringify) Error!void
参数
self: *Stringify
错误
std.json.Stringify.endObjectFieldRaw
函数
pub fn endObjectFieldRaw(self: *Stringify) void
参数
self: *Stringify
std.json.Stringify.endWriteRaw
函数
参见 beginWriteRaw。
pub fn endWriteRaw(self: *Stringify) void
参数
self: *Stringify
std.json.Stringify.Error
别名
别名目标 std.Io.Writer.Error
std.json.Stringify.getJsonObject
函数
fn getJsonObject(allocator: std.mem.Allocator) !std.json.Value
参数
std.json.Stringify.indent
函数
fn indent(self: *Stringify) !void
参数
self: *Stringify
std.json.Stringify.IndentationMode
容器
字段
object = 0
array = 1
std.json.Stringify.isComplete
函数
fn isComplete(self: *const Stringify) bool
参数
self: *const Stringify
std.json.Stringify.isObjectKeyExpected
函数
fn isObjectKeyExpected(self: *const Stringify) ?bool
参数
self: *const Stringify
std.json.Stringify.jsonStringify
函数
pub fn jsonStringify(v: @This(), jws: anytype) !void
参数
v: @This()
std.json.Stringify.objectField
函数
何时调用此方法,参见 Stringify。
key 是属性名的字符串内容。
会添加外围引号,并转义所有特殊字符。
另见 objectFieldRaw。
pub fn objectField(self: *Stringify, key: []const u8) Error!void
参数
self: *Stringify
key: []const u8
错误
std.json.Stringify.objectFieldRaw
函数
有关何时调用此方法,请参见 Stringify。
quoted_key 是键的完整字节内容,包括引号和任何必要的转义序列。
对给定值执行若干断言,确保此函数的调用方理解接口约定。
另见 objectField。
pub fn objectFieldRaw(self: *Stringify, quoted_key: []const u8) Error!void
参数
self: *Stringify
quoted_key: []const u8
错误
std.json.Stringify.objectFieldStart
函数
fn objectFieldStart(self: *Stringify) !void
参数
self: *Stringify
std.json.Stringify.Options
容器
字段
whitespace: enum {
minified,
indent_1,
indent_2,
indent_3,
indent_4,
indent_8,
indent_tab,
} = .minified控制输出的空白字符。
默认值 .minified 是紧凑编码,词法单元之间没有空白。
任何非 .minified 的设置都会使用换行、缩进,并在每个“:”后添加空格。
.indent_1 表示每层缩进 1 个空格,.indent_2 表示每层 2 个空格,依此类推。
.indent_tab 每层使用一个制表符。
emit_null_optional_fields: bool = true是否应写入值为 null 的可选字段?
emit_strings_as_arrays: bool = falseu8 数组或切片通常编码为 JSON 字符串。
此选项改为将它们输出为数字数组。
不影响 objectField*() 调用。
escape_unicode: bool = false是否应转义字符串中的 Unicode 字符?
emit_nonportable_numbers_as_strings: bool = false为 true 时,将超出 +-1<<53(f64 可精确表示的整数范围)的数字渲染为十进制 JSON 字符串。
std.json.Stringify.outputSpecialEscape
函数
fn outputSpecialEscape(c: u8, writer: *Writer) Error!void
参数
c: u8
writer: *Writer
错误
std.json.Stringify.outputUnicodeEscape
函数
fn outputUnicodeEscape(codepoint: u21, w: *Writer) Error!void
参数
codepoint: u21
w: *Writer
错误
std.json.Stringify.popIndentation
函数
fn popIndentation(self: *Stringify, expected_mode: IndentationMode) void
参数
self: *Stringify
expected_mode: IndentationMode
std.json.Stringify.print
函数
可替代 write 的调用,使用 std.fmt 格式化值。
此函数执行通常的标点和缩进格式化,
假定得到的格式化字符串表示单个完整值,
例如 "1"、"[]"、"[1,2]",而非 "1,2"。
此函数可用于自行实现数字格式化。
pub fn print(self: *Stringify, comptime fmt: []const u8, args: anytype) Error!void
参数
self: *Stringify
fmt: []const u8
错误
用法示例
test print {
var out_buf: [1024]u8 = undefined;
var out: Writer = .fixed(&out_buf);
var w: Stringify = .{ .writer = &out, .options = .{ .whitespace = .indent_2 } };
try w.beginObject();
try w.objectField("a");
try w.print("[ ]", .{});
try w.objectField("b");
try w.beginArray();
try w.print("[{s}] ", .{"[]"});
try w.print(" {}", .{12345});
try w.endArray();
try w.endObject();
const expected =
\\{
\\ "a": [ ],
\\ "b": [
\\ [[]] ,
\\ 12345
\\ ]
\\}
;
try std.testing.expectEqualStrings(expected, out.buffered());
}
std.json.Stringify.pushIndentation
函数
fn pushIndentation(self: *Stringify, mode: IndentationMode) !void
参数
self: *Stringify
mode: IndentationMode
std.json.Stringify.safety_checks
常量
@TypeOf(safety_checks_hint)
std.json.Stringify.safety_checks_hint
常量
safety_checks_hint 参数决定为启用上述语法遵循性断言而使用的内存量,例如触发断言,而非允许 endObject 输出最后的 },形成 [[[]]}。
这里的“深度”指嵌套 [] 或 {} 表达式的深度,等价于上述 <value> 语法表达式的递归层数。
例如,输出 JSON [[[]]] 需要深度 3。
若使用 .checked_to_fixed_depth,还会断言嵌套深度始终不超过给定限制。
.checked_to_fixed_depth 将所需存储嵌入 Stringify 结构体。
.assumed_correct 不需要存储空间,也不执行任何上述断言。
在快速和最小体积优化模式中,给定的 safety_checks_hint 被忽略,始终按 .assumed_correct 处理。
union(enum) { /// 向上舍入至最近的 8 的倍数。 checked_to_fixed_depth: usize, assumed_correct, }
std.json.Stringify.Self
别名
别名目标 std.json.Stringify
std.json.Stringify.std
别名
别名目标 std
std.json.Stringify.Stringify
别名
别名目标 std.json.Stringify
std.json.Stringify.stringValue
函数
fn stringValue(self: *Stringify, s: []const u8) !void
参数
self: *Stringify
s: []const u8
std.json.Stringify.testBasicWriteStream
函数
fn testBasicWriteStream(w: *Stringify) !void
参数
w: *Stringify
std.json.Stringify.testStringify
函数
fn testStringify(expected: []const u8, v: anytype, options: Options) !void
参数
expected: []const u8
options: Options
std.json.Stringify.value
函数
pub fn value(v: anytype, options: Options, writer: *Writer) Error!void
参数
错误
用法示例
test value {
var out: Writer.Allocating = .init(std.testing.allocator);
const writer = &out.writer;
defer out.deinit();
const T = struct { a: i32, b: []const u8 };
try value(T{ .a = 123, .b = "xy" }, .{}, writer);
try std.testing.expectEqualSlices(u8, "{\"a\":123,\"b\":\"xy\"}", out.written());
try testStringify("9999999999999999", 9999999999999999, .{});
try testStringify("\"9999999999999999\"", 9999999999999999, .{ .emit_nonportable_numbers_as_strings = true });
try testStringify("[1,1]", @as(@Vector(2, u32), @splat(1)), .{});
try testStringify("\"AA\"", @as(@Vector(2, u8), @splat('A')), .{});
try testStringify("[65,65]", @as(@Vector(2, u8), @splat('A')), .{ .emit_strings_as_arrays = true });
// void 字段
try testStringify("{\"foo\":42}", struct {
foo: u32,
bar: void = {},
}{ .foo = 42 }, .{});
const Tuple = struct { []const u8, usize };
try testStringify("[\"foo\",42]", Tuple{ "foo", 42 }, .{});
comptime {
testStringify("false", false, .{}) catch unreachable;
const MyStruct = struct { foo: u32 };
testStringify("[{\"foo\":42},{\"foo\":100},{\"foo\":1000}]", [_]MyStruct{
MyStruct{ .foo = 42 },
MyStruct{ .foo = 100 },
MyStruct{ .foo = 1000 },
}, .{}) catch unreachable;
}
}
std.json.Stringify.valueAlloc
函数
调用 value,将结果存入动态分配的内存,
而非接受写入器。
返回内存的所有权归调用者。
pub fn valueAlloc(gpa: Allocator, v: anytype, options: Options) error{OutOfMemory}![]u8
参数
错误
- OutOfMemory
用法示例
test valueAlloc {
const allocator = std.testing.allocator;
const expected =
\\{"foo":"bar","answer":42,"my_friend":"sammy"}
;
const actual = try valueAlloc(allocator, .{ .foo = "bar", .answer = 42, .my_friend = "sammy" }, .{});
defer allocator.free(actual);
try std.testing.expectEqualStrings(expected, actual);
}
std.json.Stringify.valueDone
函数
fn valueDone(self: *Stringify) void
参数
self: *Stringify
std.json.Stringify.valueStart
函数
fn valueStart(self: *Stringify) !void
参数
self: *Stringify
std.json.Stringify.valueStartAssumeTypeOk
函数
fn valueStartAssumeTypeOk(self: *Stringify) !void
参数
self: *Stringify
std.json.Stringify.write
函数
将给定的 Zig 值表示为 JSON。
支持的类型:
- Zig
bool→ JSONtrue或false。 - Zig
?T→null或T的表示。 - Zig
i32、u64等 → JSON 数字或字符串。- 选项
emit_nonportable_numbers_as_strings为 true 时,若值超出+-1<<53范围(f64 的精确整数范围),则表示为十进制 JSON 字符串;否则表示为 JSON 数字。
- 选项
- Zig 浮点数 → JSON 数字或字符串。
- 若值无法用 f64 精确表示,则表示为 JSON 字符串;否则表示为 JSON 数字。
- TODO: 未来可能修改浮点数表示方式,例如移除不必要的“e+00”。
- Zig
[]const u8、[]u8、*[N]u8、@Vector(N, u8)等 → JSON 字符串。- 参见
Options.emit_strings_as_arrays。 - 若内容不是有效 UTF-8,则改为表示成数字数组。
- 参见
- Zig
[]T、[N]T、*[N]T、@Vector(N, T)等 → 将每项分别表示后组成的 JSON 数组。 - Zig 元组 → 将每项分别表示后组成的 JSON 数组。
- Zig
struct→ 按字段声明顺序组成的 JSON 对象。- 若结构体声明了
pub fn jsonStringify(self: *@This(), jw: anytype) !void方法,则调用它进行序列化,替代默认行为。传入的jw是指向此Stringify的指针。示例见std.json.Value。 - 参见
Options.emit_null_optional_fields。
- 若结构体声明了
- Zig
union(enum)→ 仅含一个字段的 JSON 对象,字段名为当前活动标签,字段值表示其载荷。- 若载荷为
void,输出值为{}。 - 若联合体声明了
pub fn jsonStringify(self: *@This(), jw: anytype) !void方法,则调用它进行序列化,替代默认行为。传入的jw是指向此Stringify的指针。
- 若载荷为
- Zig
enum→ 表示当前活动标签名称的 JSON 字符串。- 若枚举声明了
pub fn jsonStringify(self: *@This(), jw: anytype) !void方法,则调用它进行序列化,替代默认行为。传入的jw是指向此Stringify的指针。 - 若枚举为非穷尽枚举,未命名值表示为整数。
- 若枚举声明了
- Zig 无类型枚举字面量 → 表示当前活动标签名称的 JSON 字符串。
- Zig 错误值 → 表示错误名称的 JSON 字符串。
- Zig
*T→T的表示。注意,这里不防止循环引用导致的无限递归。
另见替代函数 print 和 beginWriteRaw。
写入对象字段名时,应改用 objectField。
pub fn write(self: *Stringify, v: anytype) Error!void
参数
self: *Stringify
错误
std.json.Stringify.Writer
别名
别名目标 std.Io.Writer
源码
std/json/Stringify.zig
//! 向流写入 JSON([RFC8259](https://tools.ietf.org/html/rfc8259))格式的
//! 数据。
//!
//! 写入 JSON 内容的方法调用序列必须遵循以下语法:
//! ```
//! <once> = <value>
//! <value> =
//! | <object>
//! | <array>
//! | write
//! | print
//! | <writeRawStream>
//! <object> = beginObject ( <field> <value> )* endObject
//! <field> = objectField | objectFieldRaw | <objectFieldRawStream>
//! <array> = beginArray ( <value> )* endArray
//! <writeRawStream> = beginWriteRaw ( stream.writeAll )* endWriteRaw
//! <objectFieldRawStream> = beginObjectFieldRaw ( stream.writeAll )* endObjectFieldRaw
//! ```
const std = @import("../std.zig");
const assert = std.debug.assert;
const Allocator = std.mem.Allocator;
const ArrayList = std.ArrayList;
const BitStack = std.BitStack;
const Stringify = @This();
const Writer = std.Io.Writer;
const IndentationMode = enum(u1) {
object = 0,
array = 1,
};
writer: *Writer,
options: Options = .{},
indent_level: usize = 0,
next_punctuation: enum {
the_beginning,
none,
comma,
colon,
} = .the_beginning,
nesting_stack: switch (safety_checks) {
.checked_to_fixed_depth => |fixed_buffer_size| [(fixed_buffer_size + 7) >> 3]u8,
.assumed_correct => void,
} = switch (safety_checks) {
.checked_to_fixed_depth => @splat(0),
.assumed_correct => {},
},
raw_streaming_mode: if (build_mode_has_safety)
enum { none, value, objectField }
else
void = if (build_mode_has_safety) .none else {},
const build_mode_has_safety = switch (@import("builtin").mode) {
.debug, .safe => true,
.fast, .small => false,
};
/// `safety_checks_hint` 参数决定为启用上述语法遵循性断言而使用的内存量,例如触发断言,而非允许 `endObject` 输出最后的 `}`,形成 `[[[]]}`。
/// 这里的“深度”指嵌套 `[]` 或 `{}` 表达式的深度,等价于上述 `<value>` 语法表达式的递归层数。
/// 例如,输出 JSON `[[[]]]` 需要深度 3。
/// 若使用 `.checked_to_fixed_depth`,还会断言嵌套深度始终不超过给定限制。
/// `.checked_to_fixed_depth` 将所需存储嵌入 `Stringify` 结构体。
/// `.assumed_correct` 不需要存储空间,也不执行任何上述断言。
/// 在快速和最小体积优化模式中,给定的 `safety_checks_hint` 被忽略,始终按 `.assumed_correct` 处理。
///
///
const safety_checks_hint: union(enum) {
/// 向上舍入至最近的 8 的倍数。
checked_to_fixed_depth: usize,
assumed_correct,
} = .{ .checked_to_fixed_depth = 256 };
const safety_checks: @TypeOf(safety_checks_hint) = if (build_mode_has_safety)
safety_checks_hint
else
.assumed_correct;
pub const Error = Writer.Error;
pub fn beginArray(self: *Stringify) Error!void {
if (build_mode_has_safety) assert(self.raw_streaming_mode == .none);
try self.valueStart();
try self.writer.writeByte('[');
try self.pushIndentation(.array);
self.next_punctuation = .none;
}
pub fn beginObject(self: *Stringify) Error!void {
if (build_mode_has_safety) assert(self.raw_streaming_mode == .none);
try self.valueStart();
try self.writer.writeByte('{');
try self.pushIndentation(.object);
self.next_punctuation = .none;
}
pub fn endArray(self: *Stringify) Error!void {
if (build_mode_has_safety) assert(self.raw_streaming_mode == .none);
self.popIndentation(.array);
switch (self.next_punctuation) {
.none => {},
.comma => {
try self.indent();
},
.the_beginning, .colon => unreachable,
}
try self.writer.writeByte(']');
self.valueDone();
}
pub fn endObject(self: *Stringify) Error!void {
if (build_mode_has_safety) assert(self.raw_streaming_mode == .none);
self.popIndentation(.object);
switch (self.next_punctuation) {
.none => {},
.comma => {
try self.indent();
},
.the_beginning, .colon => unreachable,
}
try self.writer.writeByte('}');
self.valueDone();
}
fn pushIndentation(self: *Stringify, mode: IndentationMode) !void {
switch (safety_checks) {
.checked_to_fixed_depth => {
BitStack.pushWithStateAssumeCapacity(&self.nesting_stack, &self.indent_level, @backingInt(mode));
},
.assumed_correct => {
self.indent_level += 1;
},
}
}
fn popIndentation(self: *Stringify, expected_mode: IndentationMode) void {
switch (safety_checks) {
.checked_to_fixed_depth => {
assert(BitStack.popWithState(&self.nesting_stack, &self.indent_level) == @backingInt(expected_mode));
},
.assumed_correct => {
self.indent_level -= 1;
},
}
}
fn indent(self: *Stringify) !void {
var char: u8 = ' ';
const n_chars = switch (self.options.whitespace) {
.minified => return,
.indent_1 => 1 * self.indent_level,
.indent_2 => 2 * self.indent_level,
.indent_3 => 3 * self.indent_level,
.indent_4 => 4 * self.indent_level,
.indent_8 => 8 * self.indent_level,
.indent_tab => blk: {
char = '\t';
break :blk self.indent_level;
},
};
try self.writer.writeByte('\n');
try self.writer.splatByteAll(char, n_chars);
}
fn valueStart(self: *Stringify) !void {
if (self.isObjectKeyExpected()) |is_it| assert(!is_it); // 对象键应调用 objectField*(),而非 write()。
return self.valueStartAssumeTypeOk();
}
fn objectFieldStart(self: *Stringify) !void {
if (self.isObjectKeyExpected()) |is_it| assert(is_it); // 预期 write(),而非 objectField*()。
return self.valueStartAssumeTypeOk();
}
fn valueStartAssumeTypeOk(self: *Stringify) !void {
assert(!self.isComplete()); // JSON 文档已完整。
switch (self.next_punctuation) {
.the_beginning => {
// 最开始不缩进。
},
.none => {
// 容器中的首项。
try self.indent();
},
.comma => {
// 容器中的后续条目。
try self.writer.writeByte(',');
try self.indent();
},
.colon => {
try self.writer.writeByte(':');
if (self.options.whitespace != .minified) {
try self.writer.writeByte(' ');
}
},
}
}
fn valueDone(self: *Stringify) void {
self.next_punctuation = .comma;
}
// 仅在启用安全检查时:
fn isObjectKeyExpected(self: *const Stringify) ?bool {
switch (safety_checks) {
.checked_to_fixed_depth => return self.indent_level > 0 and
BitStack.peekWithState(&self.nesting_stack, self.indent_level) == @backingInt(IndentationMode.object) and
self.next_punctuation != .colon,
.assumed_correct => return null,
}
}
fn isComplete(self: *const Stringify) bool {
return self.indent_level == 0 and self.next_punctuation == .comma;
}
/// 可替代 `write` 的调用,使用 `std.fmt` 格式化值。
/// 此函数执行通常的标点和缩进格式化,
/// 假定得到的格式化字符串表示单个完整值,
/// 例如 `"1"`、`"[]"`、`"[1,2]"`,而非 `"1,2"`。
/// 此函数可用于自行实现数字格式化。
pub fn print(self: *Stringify, comptime fmt: []const u8, args: anytype) Error!void {
if (build_mode_has_safety) assert(self.raw_streaming_mode == .none);
try self.valueStart();
try self.writer.print(fmt, args);
self.valueDone();
}
test print {
var out_buf: [1024]u8 = undefined;
var out: Writer = .fixed(&out_buf);
var w: Stringify = .{ .writer = &out, .options = .{ .whitespace = .indent_2 } };
try w.beginObject();
try w.objectField("a");
try w.print("[ ]", .{});
try w.objectField("b");
try w.beginArray();
try w.print("[{s}] ", .{"[]"});
try w.print(" {}", .{12345});
try w.endArray();
try w.endObject();
const expected =
\\{
\\ "a": [ ],
\\ "b": [
\\ [[]] ,
\\ 12345
\\ ]
\\}
;
try std.testing.expectEqualStrings(expected, out.buffered());
}
/// 替代调用 `write` 的方式,允许直接写入 `.writer` 字段,例如 `.writer.writeAll()`。
/// 先调用 `beginWriteRaw()`,再将完整值直接写入 `.writer` 字段,必要时包含引号,
/// 最后调用 `endWriteRaw()`。
/// 可用于将很长的字符串流式写入输出,而无需先全部缓冲到内存。
pub fn beginWriteRaw(self: *Stringify) !void {
if (build_mode_has_safety) {
assert(self.raw_streaming_mode == .none);
self.raw_streaming_mode = .value;
}
try self.valueStart();
}
/// 参见 `beginWriteRaw`。
pub fn endWriteRaw(self: *Stringify) void {
if (build_mode_has_safety) {
assert(self.raw_streaming_mode == .value);
self.raw_streaming_mode = .none;
}
self.valueDone();
}
/// 何时调用此方法,参见 `Stringify`。
/// `key` 是属性名的字符串内容。
/// 会添加外围引号,并转义所有特殊字符。
/// 另见 `objectFieldRaw`。
pub fn objectField(self: *Stringify, key: []const u8) Error!void {
if (build_mode_has_safety) assert(self.raw_streaming_mode == .none);
try self.objectFieldStart();
try encodeJsonString(key, self.options, self.writer);
self.next_punctuation = .colon;
}
/// 有关何时调用此方法,请参见 `Stringify`。
/// `quoted_key` 是键的完整字节内容,包括引号和任何必要的转义序列。
/// 对给定值执行若干断言,确保此函数的调用方理解接口约定。
/// 另见 `objectField`。
pub fn objectFieldRaw(self: *Stringify, quoted_key: []const u8) Error!void {
if (build_mode_has_safety) assert(self.raw_streaming_mode == .none);
assert(quoted_key.len >= 2 and quoted_key[0] == '"' and quoted_key[quoted_key.len - 1] == '"'); // quoted_key 应为 "quoted"。
try self.objectFieldStart();
try self.writer.writeAll(quoted_key);
self.next_punctuation = .colon;
}
/// 极少数情况下可能需要写入很长的对象字段名;
/// 此函数可替代 `objectField` 和 `objectFieldRaw`,允许直接写入 `.writer` 字段,
/// 类似 `beginWriteRaw`。
/// 完成后调用 `endObjectFieldRaw()`。
pub fn beginObjectFieldRaw(self: *Stringify) !void {
if (build_mode_has_safety) {
assert(self.raw_streaming_mode == .none);
self.raw_streaming_mode = .objectField;
}
try self.objectFieldStart();
}
/// 参见 `beginObjectFieldRaw`。
pub fn endObjectFieldRaw(self: *Stringify) void {
if (build_mode_has_safety) {
assert(self.raw_streaming_mode == .objectField);
self.raw_streaming_mode = .none;
}
self.next_punctuation = .colon;
}
/// 将给定的 Zig 值表示为 JSON。
///
/// 支持的类型:
/// * Zig `bool` → JSON `true` 或 `false`。
/// * Zig `?T` → `null` 或 `T` 的表示。
/// * Zig `i32`、`u64` 等 → JSON 数字或字符串。
/// * 选项 `emit_nonportable_numbers_as_strings` 为 true 时,若值超出 `+-1<<53` 范围(f64 的精确整数范围),则表示为十进制 JSON 字符串;否则表示为 JSON 数字。
/// * Zig 浮点数 → JSON 数字或字符串。
/// * 若值无法用 f64 精确表示,则表示为 JSON 字符串;否则表示为 JSON 数字。
/// * TODO: 未来可能修改浮点数表示方式,例如移除不必要的“e+00”。
/// * Zig `[]const u8`、`[]u8`、`*[N]u8`、`@Vector(N, u8)` 等 → JSON 字符串。
/// * 参见 `Options.emit_strings_as_arrays`。
/// * 若内容不是有效 UTF-8,则改为表示成数字数组。
/// * Zig `[]T`、`[N]T`、`*[N]T`、`@Vector(N, T)` 等 → 将每项分别表示后组成的 JSON 数组。
/// * Zig 元组 → 将每项分别表示后组成的 JSON 数组。
/// * Zig `struct` → 按字段声明顺序组成的 JSON 对象。
/// * 若结构体声明了 `pub fn jsonStringify(self: *@This(), jw: anytype) !void` 方法,则调用它进行序列化,替代默认行为。传入的 `jw` 是指向此 `Stringify` 的指针。示例见 `std.json.Value`。
/// * 参见 `Options.emit_null_optional_fields`。
/// * Zig `union(enum)` → 仅含一个字段的 JSON 对象,字段名为当前活动标签,字段值表示其载荷。
/// * 若载荷为 `void`,输出值为 `{}`。
/// * 若联合体声明了 `pub fn jsonStringify(self: *@This(), jw: anytype) !void` 方法,则调用它进行序列化,替代默认行为。传入的 `jw` 是指向此 `Stringify` 的指针。
/// * Zig `enum` → 表示当前活动标签名称的 JSON 字符串。
/// * 若枚举声明了 `pub fn jsonStringify(self: *@This(), jw: anytype) !void` 方法,则调用它进行序列化,替代默认行为。传入的 `jw` 是指向此 `Stringify` 的指针。
/// * 若枚举为非穷尽枚举,未命名值表示为整数。
/// * Zig 无类型枚举字面量 → 表示当前活动标签名称的 JSON 字符串。
/// * Zig 错误值 → 表示错误名称的 JSON 字符串。
/// * Zig `*T` → `T` 的表示。注意,这里不防止循环引用导致的无限递归。
///
/// 另见替代函数 `print` 和 `beginWriteRaw`。
/// 写入对象字段名时,应改用 `objectField`。
pub fn write(self: *Stringify, v: anytype) Error!void {
if (build_mode_has_safety) assert(self.raw_streaming_mode == .none);
const T = @TypeOf(v);
switch (@typeInfo(T)) {
.int => {
try self.valueStart();
if (self.options.emit_nonportable_numbers_as_strings and
(v <= -(1 << 53) or v >= (1 << 53)))
{
try self.writer.print("\"{}\"", .{v});
} else {
try self.writer.print("{}", .{v});
}
self.valueDone();
return;
},
.comptime_int => {
return self.write(@as(std.math.IntFittingRange(v, v), v));
},
.float, .comptime_float => {
if (@as(f64, @floatCast(v)) == v) {
try self.valueStart();
try self.writer.print("{}", .{@as(f64, @floatCast(v))});
self.valueDone();
return;
}
try self.valueStart();
try self.writer.print("\"{}\"", .{v});
self.valueDone();
return;
},
.bool => {
try self.valueStart();
try self.writer.writeAll(if (v) "true" else "false");
self.valueDone();
return;
},
.null => {
try self.valueStart();
try self.writer.writeAll("null");
self.valueDone();
return;
},
.optional => {
if (v) |payload| {
return try self.write(payload);
} else {
return try self.write(null);
}
},
.@"enum" => |enum_info| {
if (std.meta.hasFn(T, "jsonStringify")) {
return v.jsonStringify(self);
}
if (enum_info.mode == .nonexhaustive) {
inline for (enum_info.field_names) |field_name| {
if (v == @field(T, field_name)) {
break;
}
} else {
return self.write(@backingInt(v));
}
}
return self.stringValue(@tagName(v));
},
.enum_literal => {
return self.stringValue(@tagName(v));
},
.@"union" => {
if (std.meta.hasFn(T, "jsonStringify")) {
return v.jsonStringify(self);
}
const info = @typeInfo(T).@"union";
if (info.tag_type) |UnionTagType| {
try self.beginObject();
inline for (info.field_names, info.field_types) |u_field_name, u_field_type| {
if (v == @field(UnionTagType, u_field_name)) {
try self.objectField(u_field_name);
if (u_field_type == void) {
// void 类型的 v 为 {}
try self.beginObject();
try self.endObject();
} else {
try self.write(@field(v, u_field_name));
}
break;
}
} else {
unreachable; // 没有活动标签?
}
try self.endObject();
return;
} else {
@compileError("Unable to stringify untagged union '" ++ @typeName(T) ++ "'");
}
},
.@"struct" => |S| {
if (std.meta.hasFn(T, "jsonStringify")) {
return v.jsonStringify(self);
}
if (S.is_tuple) {
try self.beginArray();
} else {
try self.beginObject();
}
inline for (S.field_names, S.field_types) |field_name, field_type| {
// 不包含 void 字段
if (field_type == void) continue;
var emit_field = true;
// 当 emit_null_optional_fields 为 false 时,不包含值为 null 的可选字段
if (@typeInfo(field_type) == .optional) {
if (self.options.emit_null_optional_fields == false) {
if (@field(v, field_name) == null) {
emit_field = false;
}
}
}
if (emit_field) {
if (!S.is_tuple) {
try self.objectField(field_name);
}
try self.write(@field(v, field_name));
}
}
if (S.is_tuple) {
try self.endArray();
} else {
try self.endObject();
}
return;
},
.error_set => return self.stringValue(@errorName(v)),
.pointer => |ptr_info| switch (ptr_info.size) {
.one => switch (@typeInfo(ptr_info.child)) {
.array => {
// 将 `*[N]T` 强制转换为 `[]const T`。
const Slice = []const std.meta.Elem(ptr_info.child);
return self.write(@as(Slice, v));
},
else => {
return self.write(v.*);
},
},
.many, .slice => {
if (ptr_info.size == .many and ptr_info.sentinel() == null)
@compileError("unable to stringify type '" ++ @typeName(T) ++ "' without sentinel");
const slice = if (ptr_info.size == .many) std.mem.span(v) else v;
if (ptr_info.child == u8) {
// 这是 []const u8 或类似的 Zig 字符串。
if (!self.options.emit_strings_as_arrays and std.unicode.utf8ValidateSlice(slice)) {
return self.stringValue(slice);
}
}
try self.beginArray();
for (slice) |x| {
try self.write(x);
}
try self.endArray();
return;
},
else => @compileError("Unable to stringify type '" ++ @typeName(T) ++ "'"),
},
.array => {
// 将 `[N]T` 强制转换为 `*const [N]T`(再转换为 `[]const T`)。
return self.write(&v);
},
.vector => |info| {
const array: [info.len]info.child = v;
return self.write(&array);
},
else => @compileError("Unable to stringify type '" ++ @typeName(T) ++ "'"),
}
unreachable;
}
fn stringValue(self: *Stringify, s: []const u8) !void {
try self.valueStart();
try encodeJsonString(s, self.options, self.writer);
self.valueDone();
}
pub const Options = struct {
/// 控制输出的空白字符。
/// 默认值 `.minified` 是紧凑编码,词法单元之间没有空白。
/// 任何非 `.minified` 的设置都会使用换行、缩进,并在每个“:”后添加空格。
/// `.indent_1` 表示每层缩进 1 个空格,`.indent_2` 表示每层 2 个空格,依此类推。
/// `.indent_tab` 每层使用一个制表符。
whitespace: enum {
minified,
indent_1,
indent_2,
indent_3,
indent_4,
indent_8,
indent_tab,
} = .minified,
/// 是否应写入值为 null 的可选字段?
emit_null_optional_fields: bool = true,
/// u8 数组或切片通常编码为 JSON 字符串。
/// 此选项改为将它们输出为数字数组。
/// 不影响 `objectField*()` 调用。
emit_strings_as_arrays: bool = false,
/// 是否应转义字符串中的 Unicode 字符?
escape_unicode: bool = false,
/// 为 true 时,将超出 `+-1<<53`(f64 可精确表示的整数范围)的数字渲染为十进制 JSON 字符串。
emit_nonportable_numbers_as_strings: bool = false,
};
/// 将给定值写入 `Writer` 写入器。
/// 有关给定值如何序列化为 JSON,请参见 `Stringify`。
/// 输出 JSON 文档的最大嵌套深度为 256。
pub fn value(v: anytype, options: Options, writer: *Writer) Error!void {
var s: Stringify = .{ .writer = writer, .options = options };
try s.write(v);
}
test value {
var out: Writer.Allocating = .init(std.testing.allocator);
const writer = &out.writer;
defer out.deinit();
const T = struct { a: i32, b: []const u8 };
try value(T{ .a = 123, .b = "xy" }, .{}, writer);
try std.testing.expectEqualSlices(u8, "{\"a\":123,\"b\":\"xy\"}", out.written());
try testStringify("9999999999999999", 9999999999999999, .{});
try testStringify("\"9999999999999999\"", 9999999999999999, .{ .emit_nonportable_numbers_as_strings = true });
try testStringify("[1,1]", @as(@Vector(2, u32), @splat(1)), .{});
try testStringify("\"AA\"", @as(@Vector(2, u8), @splat('A')), .{});
try testStringify("[65,65]", @as(@Vector(2, u8), @splat('A')), .{ .emit_strings_as_arrays = true });
// void 字段
try testStringify("{\"foo\":42}", struct {
foo: u32,
bar: void = {},
}{ .foo = 42 }, .{});
const Tuple = struct { []const u8, usize };
try testStringify("[\"foo\",42]", Tuple{ "foo", 42 }, .{});
comptime {
testStringify("false", false, .{}) catch unreachable;
const MyStruct = struct { foo: u32 };
testStringify("[{\"foo\":42},{\"foo\":100},{\"foo\":1000}]", [_]MyStruct{
MyStruct{ .foo = 42 },
MyStruct{ .foo = 100 },
MyStruct{ .foo = 1000 },
}, .{}) catch unreachable;
}
}
/// 调用 `value`,将结果存入动态分配的内存,
/// 而非接受写入器。
///
/// 返回内存的所有权归调用者。
pub fn valueAlloc(gpa: Allocator, v: anytype, options: Options) error{OutOfMemory}![]u8 {
var aw: Writer.Allocating = .init(gpa);
defer aw.deinit();
value(v, options, &aw.writer) catch return error.OutOfMemory;
return aw.toOwnedSlice();
}
test valueAlloc {
const allocator = std.testing.allocator;
const expected =
\\{"foo":"bar","answer":42,"my_friend":"sammy"}
;
const actual = try valueAlloc(allocator, .{ .foo = "bar", .answer = 42, .my_friend = "sammy" }, .{});
defer allocator.free(actual);
try std.testing.expectEqualStrings(expected, actual);
}
fn outputUnicodeEscape(codepoint: u21, w: *Writer) Error!void {
if (codepoint <= 0xFFFF) {
// 若字符位于基本多文种平面内(U+0000 至 U+FFFF),
// 可表示为六个字符的序列:反斜杠、小写字母 u,
// 随后是编码该字符码点的四个十六进制数字。
try w.writeAll("\\u");
try w.printInt(codepoint, 16, .lower, .{ .width = 4, .fill = '0' });
} else {
assert(codepoint <= 0x10FFFF);
// 转义不在基本多文种平面内的扩展字符时,
// 将字符表示为编码 UTF-16 代理对的 12 字符序列。
const high = @as(u16, @intCast((codepoint - 0x10000) >> 10)) + 0xD800;
const low = @as(u16, @intCast(codepoint & 0x3FF)) + 0xDC00;
try w.writeAll("\\u");
try w.printInt(high, 16, .lower, .{ .width = 4, .fill = '0' });
try w.writeAll("\\u");
try w.printInt(low, 16, .lower, .{ .width = 4, .fill = '0' });
}
}
fn outputSpecialEscape(c: u8, writer: *Writer) Error!void {
switch (c) {
'\\' => try writer.writeAll("\\\\"),
'\"' => try writer.writeAll("\\\""),
0x08 => try writer.writeAll("\\b"),
0x0C => try writer.writeAll("\\f"),
'\n' => try writer.writeAll("\\n"),
'\r' => try writer.writeAll("\\r"),
'\t' => try writer.writeAll("\\t"),
else => try outputUnicodeEscape(c, writer),
}
}
/// 将 `string` 作为 JSON 编码字符串写入 `writer`。
pub fn encodeJsonString(string: []const u8, options: Options, writer: *Writer) Error!void {
try writer.writeByte('\"');
try encodeJsonStringChars(string, options, writer);
try writer.writeByte('\"');
}
/// 将 `chars` 作为经 JSON 编码的字符串字符写入 `writer`。
pub fn encodeJsonStringChars(chars: []const u8, options: Options, writer: *Writer) Error!void {
var write_cursor: usize = 0;
var i: usize = 0;
if (options.escape_unicode) {
while (i < chars.len) : (i += 1) {
switch (chars[i]) {
// 普通 ASCII 字符
0x20...0x21, 0x23...0x5B, 0x5D...0x7E => {},
0x00...0x1F, '\\', '\"' => {
// 这些字符始终必须转义。
try writer.writeAll(chars[write_cursor..i]);
try outputSpecialEscape(chars[i], writer);
write_cursor = i + 1;
},
0x7F...0xFF => {
try writer.writeAll(chars[write_cursor..i]);
const ulen = std.unicode.utf8ByteSequenceLength(chars[i]) catch unreachable;
const codepoint = std.unicode.utf8Decode(chars[i..][0..ulen]) catch unreachable;
try outputUnicodeEscape(codepoint, writer);
i += ulen - 1;
write_cursor = i + 1;
},
}
}
} else {
while (i < chars.len) : (i += 1) {
switch (chars[i]) {
// 普通字节
0x20...0x21, 0x23...0x5B, 0x5D...0xFF => {},
0x00...0x1F, '\\', '\"' => {
// 这些字符始终必须转义。
try writer.writeAll(chars[write_cursor..i]);
try outputSpecialEscape(chars[i], writer);
write_cursor = i + 1;
},
}
}
}
try writer.writeAll(chars[write_cursor..chars.len]);
}
test "json write stream" {
var out_buf: [1024]u8 = undefined;
var out: Writer = .fixed(&out_buf);
var w: Stringify = .{ .writer = &out, .options = .{ .whitespace = .indent_2 } };
try testBasicWriteStream(&w);
}
fn testBasicWriteStream(w: *Stringify) !void {
w.writer.end = 0;
try w.beginObject();
try w.objectField("object");
var arena_allocator = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena_allocator.deinit();
try w.write(try getJsonObject(arena_allocator.allocator()));
try w.objectFieldRaw("\"string\"");
try w.write("This is a string");
try w.objectField("array");
try w.beginArray();
try w.write("Another string");
try w.write(@as(i32, 1));
try w.write(@as(f32, 3.5));
try w.endArray();
try w.objectField("int");
try w.write(@as(i32, 10));
try w.objectField("float");
try w.write(@as(f32, 3.5));
try w.endObject();
const expected =
\\{
\\ "object": {
\\ "one": 1,
\\ "two": 2
\\ },
\\ "string": "This is a string",
\\ "array": [
\\ "Another string",
\\ 1,
\\ 3.5
\\ ],
\\ "int": 10,
\\ "float": 3.5
\\}
;
try std.testing.expectEqualStrings(expected, w.writer.buffered());
}
fn getJsonObject(allocator: std.mem.Allocator) !std.json.Value {
var v: std.json.Value = .{ .object = .empty };
try v.object.put(allocator, "one", std.json.Value{ .integer = @as(i64, @intCast(1)) });
try v.object.put(allocator, "two", std.json.Value{ .float = 2.0 });
return v;
}
test "stringify null optional fields" {
const MyStruct = struct {
optional: ?[]const u8 = null,
required: []const u8 = "something",
another_optional: ?[]const u8 = null,
another_required: []const u8 = "something else",
};
try testStringify(
\\{"optional":null,"required":"something","another_optional":null,"another_required":"something else"}
,
MyStruct{},
.{},
);
try testStringify(
\\{"required":"something","another_required":"something else"}
,
MyStruct{},
.{ .emit_null_optional_fields = false },
);
}
test "stringify basic types" {
try testStringify("false", false, .{});
try testStringify("true", true, .{});
try testStringify("null", @as(?u8, null), .{});
try testStringify("null", @as(?*u32, null), .{});
try testStringify("42", 42, .{});
try testStringify("42", 42.0, .{});
try testStringify("42", @as(u8, 42), .{});
try testStringify("42", @as(u128, 42), .{});
try testStringify("9999999999999999", 9999999999999999, .{});
try testStringify("42", @as(f32, 42), .{});
try testStringify("42", @as(f64, 42), .{});
try testStringify("\"ItBroke\"", @as(anyerror, error.ItBroke), .{});
try testStringify("\"ItBroke\"", error.ItBroke, .{});
}
test "stringify string" {
try testStringify("\"hello\"", "hello", .{});
try testStringify("\"with\\nescapes\\r\"", "with\nescapes\r", .{});
try testStringify("\"with\\nescapes\\r\"", "with\nescapes\r", .{ .escape_unicode = true });
try testStringify("\"with unicode\\u0001\"", "with unicode\u{1}", .{});
try testStringify("\"with unicode\\u0001\"", "with unicode\u{1}", .{ .escape_unicode = true });
try testStringify("\"with unicode\u{80}\"", "with unicode\u{80}", .{});
try testStringify("\"with unicode\\u0080\"", "with unicode\u{80}", .{ .escape_unicode = true });
try testStringify("\"with unicode\u{FF}\"", "with unicode\u{FF}", .{});
try testStringify("\"with unicode\\u00ff\"", "with unicode\u{FF}", .{ .escape_unicode = true });
try testStringify("\"with unicode\u{100}\"", "with unicode\u{100}", .{});
try testStringify("\"with unicode\\u0100\"", "with unicode\u{100}", .{ .escape_unicode = true });
try testStringify("\"with unicode\u{800}\"", "with unicode\u{800}", .{});
try testStringify("\"with unicode\\u0800\"", "with unicode\u{800}", .{ .escape_unicode = true });
try testStringify("\"with unicode\u{8000}\"", "with unicode\u{8000}", .{});
try testStringify("\"with unicode\\u8000\"", "with unicode\u{8000}", .{ .escape_unicode = true });
try testStringify("\"with unicode\u{D799}\"", "with unicode\u{D799}", .{});
try testStringify("\"with unicode\\ud799\"", "with unicode\u{D799}", .{ .escape_unicode = true });
try testStringify("\"with unicode\u{10000}\"", "with unicode\u{10000}", .{});
try testStringify("\"with unicode\\ud800\\udc00\"", "with unicode\u{10000}", .{ .escape_unicode = true });
try testStringify("\"with unicode\u{10FFFF}\"", "with unicode\u{10FFFF}", .{});
try testStringify("\"with unicode\\udbff\\udfff\"", "with unicode\u{10FFFF}", .{ .escape_unicode = true });
}
test "stringify many-item sentinel-terminated string" {
try testStringify("\"hello\"", @as([*:0]const u8, "hello"), .{});
try testStringify("\"with\\nescapes\\r\"", @as([*:0]const u8, "with\nescapes\r"), .{ .escape_unicode = true });
try testStringify("\"with unicode\\u0001\"", @as([*:0]const u8, "with unicode\u{1}"), .{ .escape_unicode = true });
}
test "stringify enums" {
const E = enum {
foo,
bar,
};
try testStringify("\"foo\"", E.foo, .{});
try testStringify("\"bar\"", E.bar, .{});
}
test "stringify non-exhaustive enum" {
const E = enum(u8) {
foo = 0,
_,
};
try testStringify("\"foo\"", E.foo, .{});
try testStringify("1", @as(E, @fromBackingInt(@intCast(1))), .{});
}
test "stringify enum literals" {
try testStringify("\"foo\"", .foo, .{});
try testStringify("\"bar\"", .bar, .{});
}
test "stringify tagged unions" {
const T = union(enum) {
nothing,
foo: u32,
bar: bool,
};
try testStringify("{\"nothing\":{}}", T{ .nothing = {} }, .{});
try testStringify("{\"foo\":42}", T{ .foo = 42 }, .{});
try testStringify("{\"bar\":true}", T{ .bar = true }, .{});
}
test "stringify struct" {
try testStringify("{\"foo\":42}", struct {
foo: u32,
}{ .foo = 42 }, .{});
}
test "emit_strings_as_arrays" {
// 应仅影响字符串值,不影响对象键。
try testStringify("{\"foo\":\"bar\"}", .{ .foo = "bar" }, .{});
try testStringify("{\"foo\":[98,97,114]}", .{ .foo = "bar" }, .{ .emit_strings_as_arrays = true });
// *不应*影响这些类型:
try testStringify("\"foo\"", @as(enum { foo, bar }, .foo), .{ .emit_strings_as_arrays = true });
try testStringify("\"ItBroke\"", error.ItBroke, .{ .emit_strings_as_arrays = true });
// 应适用于以下情况:
try testStringify("\"bar\"", @Vector(3, u8){ 'b', 'a', 'r' }, .{});
try testStringify("[98,97,114]", @Vector(3, u8){ 'b', 'a', 'r' }, .{ .emit_strings_as_arrays = true });
try testStringify("\"bar\"", [3]u8{ 'b', 'a', 'r' }, .{});
try testStringify("[98,97,114]", [3]u8{ 'b', 'a', 'r' }, .{ .emit_strings_as_arrays = true });
}
test "stringify struct with indentation" {
try testStringify(
\\{
\\ "foo": 42,
\\ "bar": [
\\ 1,
\\ 2,
\\ 3
\\ ]
\\}
,
struct {
foo: u32,
bar: [3]u32,
}{
.foo = 42,
.bar = .{ 1, 2, 3 },
},
.{ .whitespace = .indent_4 },
);
try testStringify(
"{\n\t\"foo\": 42,\n\t\"bar\": [\n\t\t1,\n\t\t2,\n\t\t3\n\t]\n}",
struct {
foo: u32,
bar: [3]u32,
}{
.foo = 42,
.bar = .{ 1, 2, 3 },
},
.{ .whitespace = .indent_tab },
);
try testStringify(
\\{"foo":42,"bar":[1,2,3]}
,
struct {
foo: u32,
bar: [3]u32,
}{
.foo = 42,
.bar = .{ 1, 2, 3 },
},
.{ .whitespace = .minified },
);
}
test "stringify array of structs" {
const MyStruct = struct {
foo: u32,
};
try testStringify("[{\"foo\":42},{\"foo\":100},{\"foo\":1000}]", [_]MyStruct{
MyStruct{ .foo = 42 },
MyStruct{ .foo = 100 },
MyStruct{ .foo = 1000 },
}, .{});
}
test "stringify struct with custom stringifier" {
try testStringify("[\"something special\",42]", struct {
foo: u32,
const Self = @This();
pub fn jsonStringify(v: @This(), jws: anytype) !void {
_ = v;
try jws.beginArray();
try jws.write("something special");
try jws.write(42);
try jws.endArray();
}
}{ .foo = 42 }, .{});
}
fn testStringify(expected: []const u8, v: anytype, options: Options) !void {
var buffer: [4096]u8 = undefined;
var w: Writer = .fixed(&buffer);
try value(v, options, &w);
try std.testing.expectEqualStrings(expected, w.buffered());
}
test "raw streaming" {
var out_buf: [1024]u8 = undefined;
var out: Writer = .fixed(&out_buf);
var w: Stringify = .{ .writer = &out, .options = .{ .whitespace = .indent_2 } };
try w.beginObject();
try w.beginObjectFieldRaw();
try w.writer.writeAll("\"long");
try w.writer.writeAll(" key\"");
w.endObjectFieldRaw();
try w.beginWriteRaw();
try w.writer.writeAll("\"long");
try w.writer.writeAll(" value\"");
w.endWriteRaw();
try w.endObject();
const expected =
\\{
\\ "long key": "long value"
\\}
;
try std.testing.expectEqualStrings(expected, w.writer.buffered());
}