authorgravatar for philipp@luehmann.devPhilipp Lühmann <philipp@luehmann.dev> 2023-08-09 01:26:46+02:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2023-08-08 23:26:46+00:00
logd34201c8491007c5a24b4175a5170a5b6cc3d55e
treeb1c5f230c9b143902acc17627b6e60a940cecc2e
parent36c57c3ba17c45a4c9b902041db9bb993dbc67b9
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

std.json: stringify enum literals (#16742)


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

lib/std/json/stringify.zig+2-1
......@@ -181,6 +181,7 @@ pub fn writeStreamArbitraryDepth(
181181/// * If the union declares a method `pub fn jsonStringify(self: *@This(), jw: anytype) !void`, it is called to do the serialization instead of the default behavior. The given `jw` is a pointer to this `WriteStream`.
182182/// * Zig `enum` -> JSON string naming the active tag.
183183/// * If the enum declares a method `pub fn jsonStringify(self: *@This(), jw: anytype) !void`, it is called to do the serialization instead of the default behavior. The given `jw` is a pointer to this `WriteStream`.
184/// * Zig untyped enum literal -> JSON string naming the active tag.
184185/// * Zig error -> JSON string naming the error.
185186/// * Zig `*T` -> the rendering of `T`. Note there is no guard against circular-reference infinite recursion.
186187///
......@@ -449,7 +450,7 @@ pub fn WriteStream(
449450 return try self.write(null);
450451 }
451452 },
452 .Enum => {
453 .Enum, .EnumLiteral => {
453454 if (comptime std.meta.trait.hasFn("jsonStringify")(T)) {
454455 return value.jsonStringify(self);
455456 }
lib/std/json/stringify_test.zig+5
......@@ -172,6 +172,11 @@ test "stringify enums" {
172172 try testStringify("\"bar\"", E.bar, .{});
173173}
174174
175test "stringify enum literals" {
176 try testStringify("\"foo\"", .foo, .{});
177 try testStringify("\"bar\"", .bar, .{});
178}
179
175180test "stringify tagged unions" {
176181 const T = union(enum) {
177182 nothing,