Skip to content

Commit

Permalink
encoding/json: don't panic on incorrect map argument
Browse files Browse the repository at this point in the history
Fixes golang#8305.

LGTM=rsc
R=rsc
CC=golang-codereviews
https://golang.org/cl/145680044
  • Loading branch information
griesemer authored and wheatman committed Jun 26, 2018
1 parent dbfd7b1 commit 29efaa3
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
6 changes: 4 additions & 2 deletions src/encoding/json/decode.go
Expand Up @@ -445,7 +445,7 @@ func (d *decodeState) array(v reflect.Value) {
}

// object consumes an object from d.data[d.off-1:], decoding into the value v.
// the first byte of the object ('{') has been read already.
// the first byte ('{') of the object has been read already.
func (d *decodeState) object(v reflect.Value) {
// Check for unmarshaler.
u, ut, pv := d.indirect(v, false)
Expand Down Expand Up @@ -478,7 +478,9 @@ func (d *decodeState) object(v reflect.Value) {
t := v.Type()
if t.Key().Kind() != reflect.String {
d.saveError(&UnmarshalTypeError{"object", v.Type()})
break
d.off--
d.next() // skip over { } in input
return
}
if v.IsNil() {
v.Set(reflect.MakeMap(t))
Expand Down
12 changes: 11 additions & 1 deletion src/encoding/json/decode_test.go
Expand Up @@ -406,6 +406,13 @@ var unmarshalTests = []unmarshalTest{
ptr: new(string),
out: "hello\ufffd\ufffd\ufffd\ufffd\ufffd\ufffdworld",
},

// issue 8305
{
in: `{"2009-11-10T23:00:00Z": "hello world"}`,
ptr: &map[time.Time]string{},
err: &UnmarshalTypeError{"object", reflect.TypeOf(map[time.Time]string{})},
},
}

func TestMarshal(t *testing.T) {
Expand Down Expand Up @@ -514,14 +521,17 @@ func TestUnmarshal(t *testing.T) {
if tt.ptr == nil {
continue
}

// v = new(right-type)
v := reflect.New(reflect.TypeOf(tt.ptr).Elem())
dec := NewDecoder(bytes.NewReader(in))
if tt.useNumber {
dec.UseNumber()
}
if err := dec.Decode(v.Interface()); !reflect.DeepEqual(err, tt.err) {
t.Errorf("#%d: %v want %v", i, err, tt.err)
t.Errorf("#%d: %v, want %v", i, err, tt.err)
continue
} else if err != nil {
continue
}
if !reflect.DeepEqual(v.Elem().Interface(), tt.out) {
Expand Down

0 comments on commit 29efaa3

Please sign in to comment.