authorgravatar for johnnymarler@gmail.comJonathan Marler <johnnymarler@gmail.com> 2023-09-13 16:24:59-06:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2023-09-13 18:24:59-04:00
log223f62acbd32c04db3169906f33869f43e5258f7
tree21e51a6ec49519505da94bb8164d1806b44931f1
parent0e2f002a7b45acb5ed62365b9290b09912e5c709
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

std.json: add fmt function (#17055)

Adds std.json.fmt which returns a std.fmt Formatter that formats any given value using std.json.stringify.

2 files changed, 49 insertions(+), 0 deletions(-)

lib/std/json.zig+3
......@@ -110,6 +110,9 @@ pub const WriteStream = @import("json/stringify.zig").WriteStream;
110110pub const encodeJsonString = @import("json/stringify.zig").encodeJsonString;
111111pub const encodeJsonStringChars = @import("json/stringify.zig").encodeJsonStringChars;
112112
113pub const Formatter = @import("json/fmt.zig").Formatter;
114pub const fmt = @import("json/fmt.zig").fmt;
115
113116// Deprecations
114117pub const parse = @compileError("Deprecated; use parseFromSlice() or parseFromTokenSource() instead.");
115118pub const parseFree = @compileError("Deprecated; call Parsed(T).deinit() instead.");
lib/std/json/fmt.zig created+46
......@@ -0,0 +1,46 @@
1const std = @import("std");
2
3const stringify = @import("stringify.zig").stringify;
4const StringifyOptions = @import("stringify.zig").StringifyOptions;
5
6/// Returns a formatter that formats the given value using stringify.
7pub fn fmt(value: anytype, options: StringifyOptions) Formatter(@TypeOf(value)) {
8 return Formatter(@TypeOf(value)){ .value = value, .options = options };
9}
10
11/// Formats the given value using stringify.
12pub fn Formatter(comptime T: type) type {
13 return struct {
14 value: T,
15 options: StringifyOptions,
16
17 pub fn format(
18 self: @This(),
19 comptime fmt_spec: []const u8,
20 options: std.fmt.FormatOptions,
21 writer: anytype,
22 ) !void {
23 _ = fmt_spec;
24 _ = options;
25 try stringify(self.value, self.options, writer);
26 }
27 };
28}
29
30test fmt {
31 const expectFmt = std.testing.expectFmt;
32 try expectFmt("123", "{}", .{fmt(@as(u32, 123), .{})});
33 try expectFmt(
34 \\{"num":927,"msg":"hello","sub":{"mybool":true}}
35 , "{}", .{fmt(struct {
36 num: u32,
37 msg: []const u8,
38 sub: struct {
39 mybool: bool,
40 },
41 }{
42 .num = 927,
43 .msg = "hello",
44 .sub = .{ .mybool = true },
45 }, .{})});
46}