| ... | ... | @@ -0,0 +1,46 @@ |
| 1 | const std = @import("std"); |
| 2 | |
| 3 | const stringify = @import("stringify.zig").stringify; |
| 4 | const StringifyOptions = @import("stringify.zig").StringifyOptions; |
| 5 | |
| 6 | /// Returns a formatter that formats the given value using stringify. |
| 7 | pub 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. |
| 12 | pub 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 | |
| 30 | test 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 | } |