diff --git a/bench_test.go b/bench_test.go index f2592e3..f92d39f 100644 --- a/bench_test.go +++ b/bench_test.go @@ -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}]}`) diff --git a/encode.go b/encode.go index 2e1f56f..0758b2f 100644 --- a/encode.go +++ b/encode.go @@ -600,11 +600,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) } diff --git a/stream_test.go b/stream_test.go index e3317dd..ebb4f23 100644 --- a/stream_test.go +++ b/stream_test.go @@ -118,6 +118,11 @@ func TestEncoderSetEscapeHTML(t *testing.T) { Ptr strPtrMarshaler }{`""`, `""`} + // https://golang.org/issue/34154 + stringOption := struct { + Bar string `json:"bar,string"` + }{`foobar`} + for _, tt := range []struct { name string v interface{} @@ -137,6 +142,11 @@ func TestEncoderSetEscapeHTML(t *testing.T) { `{"NonPtr":"\u003cstr\u003e","Ptr":"\u003cstr\u003e"}`, `{"NonPtr":"","Ptr":""}`, }, + { + "stringOption", stringOption, + `{"bar":"\"\u003chtml\u003efoobar\u003c/html\u003e\""}`, + `{"bar":"\"foobar\""}`, + }, } { var buf bytes.Buffer enc := NewEncoder(&buf)