Skip to content

Commit

Permalink
Ensure uninitialized map is initialized when unmarshaling json
Browse files Browse the repository at this point in the history
Add tests for this scenario
  • Loading branch information
naemono authored and stanislas-m committed Dec 15, 2020
1 parent f36afb5 commit 4d0d826
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
3 changes: 3 additions & 0 deletions slices/map.go
Expand Up @@ -51,6 +51,9 @@ func (m Map) UnmarshalJSON(b []byte) error {
if err != nil {
return err
}
if m == nil {
m = Map{}
}
for key, value := range stuff {
m[key] = value
}
Expand Down
11 changes: 11 additions & 0 deletions slices/map_test.go
Expand Up @@ -24,3 +24,14 @@ func Test_Map_MarshalJSON(t *testing.T) {
r.NoError(err)
r.Equal([]byte(`{"a":"b"}`), b)
}

func Test_Map_UnMarshalJSON_uninitialized_map_does_not_panic(t *testing.T) {
r := require.New(t)

maps := make([]Map, 0)
r.NotPanics(func() {
err := json.Unmarshal([]byte(`[{"a": "b"}]`), &maps)
r.NoError(err)
r.Len(maps, 1)
})
}

0 comments on commit 4d0d826

Please sign in to comment.