JSON: Optionally write union variant tags and names #4293
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Introduces an option to make JSON marshaller write out union variant name and tag. These names and tags are automatically looked for when unmarshalling happens, in a backwards compatible way.
For a union looking like this
It would write this:
When unmarshalling into a union, it will look for these
$name
and$tag
fields etc. If found it will use them and try to find a matching union variant.It writes both name and tag so that it can first try with name, because that is makes it possible to move things in the union. However, if you renamed a type, then the name wont match and it will instead try with the tag.
Without this the above would unmarshal into a union of variant
A
instead, which is not what the user expects.Test program that shows how it works and how to enable the marshalling option:
when run it prints this:
The above is similar to the repro in this issue: #3474, but with the desired outcome.
Things to consider:
$name
for variants that have type infoType_Info_Named
. For basic types likef32
it would only write the$tag
. I can usereflect.write_typeid
in the marshaller to write the "correct" type for something like an f32, but no good way to compare against it in the unmarshaller without doing something similar there, which starts feeling a bit hacky.