From 5d364ed5b994a50318d4350670451eeb09d40324 Mon Sep 17 00:00:00 2001 From: Meghan Denny Date: Thu, 8 Apr 2021 16:57:46 -0700 Subject: [PATCH] util/yaml: add custom formatters --- src/util/yaml.zig | 52 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/src/util/yaml.zig b/src/util/yaml.zig index f1f7e077ccb456b8658cdc9174252a14444ca5c2..91a27041ba6f983c2e50dfeb193e69f8ea452e40 100644 --- a/src/util/yaml.zig +++ b/src/util/yaml.zig @@ -21,6 +21,29 @@ pub const Item = union(enum) { sequence: []Item, document: Document, string: []const u8, + + pub fn format(self: Item, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) @TypeOf(writer).Error!void { + try writer.writeAll("Item{"); + switch (self) { + .event, .kv, .document => { + unreachable; + }, + .mapping => { + try std.fmt.format(writer, "{}", .{self.mapping}); + }, + .sequence => { + try writer.writeAll("[ "); + for (self.sequence) |it| { + try std.fmt.format(writer, "{}, ", .{it}); + } + try writer.writeAll("]"); + }, + .string => { + try std.fmt.format(writer, "{s}", .{self.string}); + }, + } + try writer.writeAll("}"); + } }; pub const Key = struct { @@ -32,6 +55,26 @@ pub const Value = union(enum) { string: []const u8, mapping: Mapping, sequence: []Item, + + pub fn format(self: Value, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) @TypeOf(writer).Error!void { + try writer.writeAll("Value{"); + switch (self) { + .string => { + try std.fmt.format(writer, "{s}", .{self.string}); + }, + .mapping => { + try std.fmt.format(writer, "{}", .{self.mapping}); + }, + .sequence => { + try writer.writeAll("[ "); + for (self.sequence) |it| { + try std.fmt.format(writer, "{}, ", .{it}); + } + try writer.writeAll("]"); + }, + } + try writer.writeAll("}"); + } }; pub const Mapping = struct { @@ -64,6 +107,15 @@ pub const Mapping = struct { } return list.items; } + + pub fn format(self: Mapping, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) @TypeOf(writer).Error!void { + try writer.writeAll("{ "); + for (self.items) |it| { + try std.fmt.format(writer, "{s}: ", .{it.key}); + try std.fmt.format(writer, "{}, ", .{it.value}); + } + try writer.writeAll("}"); + } }; // -- 2.54.0