mirror of
https://codeberg.org/ziglang/zig.git
synced 2025-12-06 13:54:21 +00:00
zon: add Formatter
This commit is contained in:
parent
26825e9506
commit
90ec1ae6a2
1 changed files with 41 additions and 0 deletions
|
|
@ -37,10 +37,51 @@
|
||||||
//! ZON does not have syntax for pointers, but the parsers will allocate as needed to match the
|
//! ZON does not have syntax for pointers, but the parsers will allocate as needed to match the
|
||||||
//! given Zig types. Similarly, the serializer will traverse pointers.
|
//! given Zig types. Similarly, the serializer will traverse pointers.
|
||||||
|
|
||||||
|
const std = @import("std");
|
||||||
|
|
||||||
pub const parse = @import("zon/parse.zig");
|
pub const parse = @import("zon/parse.zig");
|
||||||
pub const stringify = @import("zon/stringify.zig");
|
pub const stringify = @import("zon/stringify.zig");
|
||||||
pub const Serializer = @import("zon/Serializer.zig");
|
pub const Serializer = @import("zon/Serializer.zig");
|
||||||
|
|
||||||
|
/// Returns a formatter that formats the given value using stringify.
|
||||||
|
pub fn fmt(value: anytype, options: stringify.SerializeOptions) Formatter(@TypeOf(value)) {
|
||||||
|
return Formatter(@TypeOf(value)){ .value = value, .options = options };
|
||||||
|
}
|
||||||
|
|
||||||
|
test fmt {
|
||||||
|
const expectFmt = std.testing.expectFmt;
|
||||||
|
try expectFmt("123", "{f}", .{fmt(@as(u32, 123), .{})});
|
||||||
|
try expectFmt(
|
||||||
|
\\.{
|
||||||
|
\\ .num = 927,
|
||||||
|
\\ .msg = "hello",
|
||||||
|
\\ .sub = .{ .mybool = true },
|
||||||
|
\\}
|
||||||
|
, "{f}", .{fmt(struct {
|
||||||
|
num: u32,
|
||||||
|
msg: []const u8,
|
||||||
|
sub: struct {
|
||||||
|
mybool: bool,
|
||||||
|
},
|
||||||
|
}{
|
||||||
|
.num = 927,
|
||||||
|
.msg = "hello",
|
||||||
|
.sub = .{ .mybool = true },
|
||||||
|
}, .{})});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Formats the given value using stringify.
|
||||||
|
pub fn Formatter(comptime T: type) type {
|
||||||
|
return struct {
|
||||||
|
value: T,
|
||||||
|
options: stringify.SerializeOptions,
|
||||||
|
|
||||||
|
pub fn format(self: @This(), writer: *std.Io.Writer) std.Io.Writer.Error!void {
|
||||||
|
try stringify.serialize(self.value, self.options, writer);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
test {
|
test {
|
||||||
_ = parse;
|
_ = parse;
|
||||||
_ = stringify;
|
_ = stringify;
|
||||||
|
|
|
||||||
Loading…
Add table
Reference in a new issue