authorgravatar for yujiri@disroot.orgEvin Yulo <yujiri@disroot.org> 2023-06-27 14:28:17-04:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2023-07-03 20:33:36-07:00
logba6e5e65a0f84b803fffe4dd26b6e71417cab616
treeffea8c44cab15c64452a7c41a532632b1cdaad60
parentb26fa4ec4baff7af8023f64230cbc0bdf1c99433

json: give enums a default stringify implementation


2 files changed, 10 insertions(+), 1 deletions(-)

lib/std/json/stringify.zig+1-1
...@@ -167,7 +167,7 @@ pub fn stringify(...@@ -167,7 +167,7 @@ pub fn stringify(
167 return value.jsonStringify(options, out_stream);167 return value.jsonStringify(options, out_stream);
168 }168 }
169169
170 @compileError("Unable to stringify enum '" ++ @typeName(T) ++ "'");170 return try encodeJsonString(@tagName(value), options, out_stream);
171 },171 },
172 .Union => {172 .Union => {
173 if (comptime std.meta.trait.hasFn("jsonStringify")(T)) {173 if (comptime std.meta.trait.hasFn("jsonStringify")(T)) {
lib/std/json/stringify_test.zig+9
...@@ -73,6 +73,15 @@ test "stringify many-item sentinel-terminated string" {...@@ -73,6 +73,15 @@ test "stringify many-item sentinel-terminated string" {
73 try teststringify("\"with unicode\\u0001\"", @as([*:0]const u8, "with unicode\u{1}"), StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } });73 try teststringify("\"with unicode\\u0001\"", @as([*:0]const u8, "with unicode\u{1}"), StringifyOptions{ .string = .{ .String = .{ .escape_unicode = true } } });
74}74}
7575
76test "stringify enums" {
77 const E = enum {
78 foo,
79 bar,
80 };
81 try teststringify("\"foo\"", E.foo, .{});
82 try teststringify("\"bar\"", E.bar, .{});
83}
84
76test "stringify tagged unions" {85test "stringify tagged unions" {
77 const T = union(enum) {86 const T = union(enum) {
78 nothing,87 nothing,