authorgravatar for ben@benburkert.comBen Burkert <ben@benburkert.com> 2025-09-22 06:30:23-04:00
committergravatar for masonremaley@noreply.codeberg.orgMason Remaley <masonremaley@noreply.codeberg.org> 2026-08-02 21:40:32+02:00
log32ed280a9b7f16a48d970d06a27a26ee38c24ca1
tree2eec4426a265cbb2de9f709469c7a35fc39ca4b5
parent539bdfc46ff75a4a4febb97a7700ade393c1cb22

zon: add fmt function

Add std.zon.fmt Formatter that formats any value via std.zon.stringify.

1 files changed, 41 insertions(+), 0 deletions(-)

lib/std/zon.zig+41
...@@ -37,10 +37,51 @@...@@ -37,10 +37,51 @@
37//! ZON does not have syntax for pointers, but the parsers will allocate as needed to match the37//! ZON does not have syntax for pointers, but the parsers will allocate as needed to match the
38//! given Zig types. Similarly, the serializer will traverse pointers.38//! given Zig types. Similarly, the serializer will traverse pointers.
3939
40const std = @import("std");
41
40pub const parse = @import("zon/parse.zig");42pub const parse = @import("zon/parse.zig");
41pub const stringify = @import("zon/stringify.zig");43pub const stringify = @import("zon/stringify.zig");
42pub const Serializer = @import("zon/Serializer.zig");44pub const Serializer = @import("zon/Serializer.zig");
4345
46/// Returns a formatter that formats the given value using stringify.
47pub fn fmt(value: anytype, options: stringify.SerializeOptions) Formatter(@TypeOf(value)) {
48 return Formatter(@TypeOf(value)){ .value = value, .options = options };
49}
50
51test fmt {
52 const expectFmt = std.testing.expectFmt;
53 try expectFmt("123", "{f}", .{fmt(@as(u32, 123), .{})});
54 try expectFmt(
55 \\.{
56 \\ .num = 927,
57 \\ .msg = "hello",
58 \\ .sub = .{ .mybool = true },
59 \\}
60 , "{f}", .{fmt(struct {
61 num: u32,
62 msg: []const u8,
63 sub: struct {
64 mybool: bool,
65 },
66 }{
67 .num = 927,
68 .msg = "hello",
69 .sub = .{ .mybool = true },
70 }, .{})});
71}
72
73/// Formats the given value using stringify.
74pub fn Formatter(comptime T: type) type {
75 return struct {
76 value: T,
77 options: stringify.SerializeOptions,
78
79 pub fn format(self: @This(), writer: *std.Io.Writer) std.Io.Writer.Error!void {
80 try stringify.serialize(self.value, self.options, writer);
81 }
82 };
83}
84
44test {85test {
45 _ = parse;86 _ = parse;
46 _ = stringify;87 _ = stringify;