mirror of
https://codeberg.org/ziglang/zig.git
synced 2025-12-06 13:54:21 +00:00
Introduces `std.fmt.alt` which is a helper for calling alternate format methods besides one named "format".
40 lines
1.2 KiB
Zig
40 lines
1.2 KiB
Zig
const std = @import("../std.zig");
|
|
const assert = std.debug.assert;
|
|
|
|
const stringify = @import("stringify.zig").stringify;
|
|
const StringifyOptions = @import("stringify.zig").StringifyOptions;
|
|
|
|
/// Returns a formatter that formats the given value using stringify.
|
|
pub fn fmt(value: anytype, options: StringifyOptions) Formatter(@TypeOf(value)) {
|
|
return Formatter(@TypeOf(value)){ .value = value, .options = options };
|
|
}
|
|
|
|
/// Formats the given value using stringify.
|
|
pub fn Formatter(comptime T: type) type {
|
|
return struct {
|
|
value: T,
|
|
options: StringifyOptions,
|
|
|
|
pub fn format(self: @This(), writer: *std.io.Writer) std.io.Writer.Error!void {
|
|
try stringify(self.value, self.options, writer);
|
|
}
|
|
};
|
|
}
|
|
|
|
test fmt {
|
|
const expectFmt = std.testing.expectFmt;
|
|
try expectFmt("123", "{}", .{fmt(@as(u32, 123), .{})});
|
|
try expectFmt(
|
|
\\{"num":927,"msg":"hello","sub":{"mybool":true}}
|
|
, "{}", .{fmt(struct {
|
|
num: u32,
|
|
msg: []const u8,
|
|
sub: struct {
|
|
mybool: bool,
|
|
},
|
|
}{
|
|
.num = 927,
|
|
.msg = "hello",
|
|
.sub = .{ .mybool = true },
|
|
}, .{})});
|
|
}
|