Skip to content

Commit

Permalink
encoding/json: fix panic for nil instances of TextMarshaler in map keys
Browse files Browse the repository at this point in the history
This change adds a a check in the encodeWithString.resolve method
to ensure that a reflect.Value with kind Ptr is not nil before
the type assertion to TextMarshaler.

If the value is nil, the method returns a nil error, and the map key
encodes to an empty string.

Fixes #33675
  • Loading branch information
wI2L committed Aug 17, 2019
1 parent c485506 commit 0ace442
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/encoding/json/encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -872,6 +872,9 @@ func (w *reflectWithString) resolve() error {
return nil
}
if tm, ok := w.v.Interface().(encoding.TextMarshaler); ok {
if w.v.Kind() == reflect.Ptr && w.v.IsNil() {
return nil
}
buf, err := tm.MarshalText()
w.s = string(buf)
return err
Expand Down
14 changes: 14 additions & 0 deletions src/encoding/json/encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -793,6 +793,20 @@ func TestTextMarshalerMapKeysAreSorted(t *testing.T) {
}
}

func TestIssue33675(t *testing.T) {
b, err := Marshal(map[*unmarshalerText]int{
(*unmarshalerText)(nil): 1,
&unmarshalerText{"A", "B"}: 2,
})
if err != nil {
t.Fatalf("Failed to Marshal *text.Marshaler: %v", err)
}
const want = `{"":1,"A:B":2}`
if string(b) != want {
t.Errorf("Marshal map with *text.Marshaler keys: got %#q, want %#q", b, want)
}
}

var re = regexp.MustCompile

// syntactic checks on form of marshaled floating point numbers.
Expand Down

0 comments on commit 0ace442

Please sign in to comment.