Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support stringifying non-exhaustive enum to json #21228

Merged
merged 3 commits into from
Sep 7, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion lib/std/json/stringify.zig
Original file line number Diff line number Diff line change
Expand Up @@ -540,11 +540,26 @@ pub fn WriteStream(
return try self.write(null);
}
},
.Enum, .EnumLiteral => {
.Enum => |enum_info| {
pfgithub marked this conversation as resolved.
Show resolved Hide resolved
if (std.meta.hasFn(T, "jsonStringify")) {
return value.jsonStringify(self);
}

if (!enum_info.is_exhaustive) {
inline for (enum_info.fields) |field| {
if (value == @field(T, field.name)) {
break;
}
} else {
try self.valueStart();
try self.stream.print("{d}", .{@intFromEnum(value)});
return self.valueDone();
pfgithub marked this conversation as resolved.
Show resolved Hide resolved
}
}

return self.stringValue(@tagName(value));
},
.EnumLiteral => {
return self.stringValue(@tagName(value));
},
.Union => {
Expand Down
9 changes: 9 additions & 0 deletions lib/std/json/stringify_test.zig
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,15 @@ test "stringify enums" {
try testStringify("\"bar\"", E.bar, .{});
}

test "stringify non-exhaustive enum" {
const E = enum(u8) {
foo = 0,
_,
};
try testStringify("\"foo\"", E.foo, .{});
try testStringify("1", @as(E, @enumFromInt(1)), .{});
}

test "stringify enum literals" {
try testStringify("\"foo\"", .foo, .{});
try testStringify("\"bar\"", .bar, .{});
Expand Down
Loading