Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

encoding/json: fix and optimize marshal for quoted string #34127

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/encoding/json/bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,22 @@ func BenchmarkIssue10335(b *testing.B) {
})
}

func BenchmarkIssue34127(b *testing.B) {
b.ReportAllocs()
j := struct {
Bar string `json:"bar,string"`
}{
Bar: `foobar`,
}
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
if _, err := Marshal(&j); err != nil {
b.Fatal(err)
}
}
})
}

func BenchmarkUnmapped(b *testing.B) {
b.ReportAllocs()
j := []byte(`{"s": "hello", "y": 2, "o": {"x": 0}, "a": [1, 99, {"x": 1}]}`)
Expand Down
10 changes: 5 additions & 5 deletions src/encoding/json/encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -601,11 +601,11 @@ func stringEncoder(e *encodeState, v reflect.Value, opts encOpts) {
return
}
if opts.quoted {
sb, err := Marshal(v.String())
if err != nil {
e.error(err)
}
e.string(string(sb), opts.escapeHTML)
b := make([]byte, 0, v.Len()+2)
b = append(b, '"')
b = append(b, []byte(v.String())...)
b = append(b, '"')
e.stringBytes(b, opts.escapeHTML)
} else {
e.string(v.String(), opts.escapeHTML)
}
Expand Down
10 changes: 10 additions & 0 deletions src/encoding/json/stream_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,11 @@ func TestEncoderSetEscapeHTML(t *testing.T) {
Ptr strPtrMarshaler
}{`"<str>"`, `"<str>"`}

// https://golang.org/issue/34154
stringOption := struct {
Bar string `json:"bar,string"`
}{`<html>foobar</html>`}

for _, tt := range []struct {
name string
v interface{}
Expand All @@ -137,6 +142,11 @@ func TestEncoderSetEscapeHTML(t *testing.T) {
`{"NonPtr":"\u003cstr\u003e","Ptr":"\u003cstr\u003e"}`,
`{"NonPtr":"<str>","Ptr":"<str>"}`,
},
{
"stringOption", stringOption,
`{"bar":"\"\u003chtml\u003efoobar\u003c/html\u003e\""}`,
`{"bar":"\"<html>foobar</html>\""}`,
},
} {
var buf bytes.Buffer
enc := NewEncoder(&buf)
Expand Down