authorgravatar for quae@daurnimator.comdaurnimator <quae@daurnimator.com> 2020-05-18 02:51:02+10:00
committergravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-07-24 20:35:47+00:00
log978a38ee40e13c3eed625f2df7b36be49fd049e0
tree60596022f326a9f62e07618863ae6f3b668739aa
parentd3ebd428650748e60db70dd2171cc044855814b1

std: fix json parsing into unions


1 files changed, 12 insertions(+), 1 deletions(-)

lib/std/json.zig+12-1
......@@ -1418,7 +1418,10 @@ fn parseInternal(comptime T: type, token: Token, tokens: *TokenStream, options:
14181418 if (unionInfo.tag_type) |_| {
14191419 // try each of the union fields until we find one that matches
14201420 inline for (unionInfo.fields) |u_field| {
1421 if (parseInternal(u_field.field_type, token, tokens, options)) |value| {
1421 // take a copy of tokens so we can withhold mutations until success
1422 var tokens_copy = tokens.*;
1423 if (parseInternal(u_field.field_type, token, &tokens_copy, options)) |value| {
1424 tokens.* = tokens_copy;
14221425 return @unionInit(T, u_field.name, value);
14231426 } else |err| {
14241427 // Bubble up error.OutOfMemory
......@@ -1733,6 +1736,14 @@ test "parse into tagged union" {
17331736 };
17341737 testing.expectEqual(T{ .x = 42 }, try parse(T, &TokenStream.init("42"), ParseOptions{}));
17351738 }
1739
1740 { // needs to back out when first union member doesn't match
1741 const T = union(enum) {
1742 A: struct { x: u32 },
1743 B: struct { y: u32 },
1744 };
1745 testing.expectEqual(T{ .B = .{.y = 42} }, try parse(T, &TokenStream.init("{\"y\":42}"), ParseOptions{}));
1746 }
17361747}
17371748
17381749test "parseFree descends into tagged union" {