-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
encoding/json: reuse values when decoding map elements
When we decode into a struct, each input key-value may be decoded into one of the struct's fields. Particularly, existing data isn't dropped, so that some sub-fields can be decoded into without zeroing all other data. However, decoding into a map behaved in the opposite way. Whenever a key-value was decoded, it completely replaced the previous map element. If the map contained any non-zero data in that key, it's dropped. Instead, try to reuse the existing element value if possible. If the map element type is a pointer, and the value is non-nil, we can decode directly into it. If it's not a pointer, make a copy and decode into that copy, as map element values aren't addressable. This means we have to parse and convert the map element key before the value, to be able to obtain the existing element value. This is fine, though. Moreover, reporting errors on the key before the value follows the input order more closely. Finally, add a test to explore the four combinations, involving pointer and non-pointer, and non-zero and zero values. A table-driven test wasn't used, as each case required different checks, such as checking that the non-nil pointer case doesn't end up with a different pointer. Fixes #31924. Change-Id: I5ca40c9963a98aaf92f26f0b35843c021028dfca Reviewed-on: https://go-review.googlesource.com/c/go/+/179337 Run-TryBot: Daniel Martí <mvdan@mvdan.cc> TryBot-Result: Gobot Gobot <gobot@golang.org> Reviewed-by: Ian Lance Taylor <iant@golang.org>
- Loading branch information
Showing
2 changed files
with
112 additions
and
45 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters