From ebdbfccd989b07a8aef75af5fbe7448f035ee239 Mon Sep 17 00:00:00 2001 From: Joe Tsai Date: Tue, 24 Jun 2025 18:56:26 -0700 Subject: encoding/json/jsontext: preserve buffer capacity in Encoder.Reset This does the equivalent of CL 681177 for the Encoder. It preserves the internal buffer between resets. Change-Id: I5e9353b6d7755e067d4f9a4d1ea3d8f056253027 Reviewed-on: https://go-review.googlesource.com/c/go/+/690375 Reviewed-by: Johan Brandhorst-Satzkorn Auto-Submit: Joseph Tsai LUCI-TryBot-Result: Go LUCI Reviewed-by: Damien Neil Reviewed-by: Michael Knyszek --- src/encoding/json/jsontext/encode.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'src/encoding/json/jsontext/encode.go') diff --git a/src/encoding/json/jsontext/encode.go b/src/encoding/json/jsontext/encode.go index 562d217fef..e3b9c04ca6 100644 --- a/src/encoding/json/jsontext/encode.go +++ b/src/encoding/json/jsontext/encode.go @@ -107,12 +107,17 @@ func (e *Encoder) Reset(w io.Writer, opts ...Options) { case e.s.Flags.Get(jsonflags.WithinArshalCall): panic("jsontext: cannot reset Encoder passed to json.MarshalerTo") } - e.s.reset(nil, w, opts...) + // Reuse the buffer if it does not alias a previous [bytes.Buffer]. + b := e.s.Buf[:0] + if _, ok := e.s.wr.(*bytes.Buffer); ok { + b = nil + } + e.s.reset(b, w, opts...) } func (e *encoderState) reset(b []byte, w io.Writer, opts ...Options) { e.state.reset() - e.encodeBuffer = encodeBuffer{Buf: b, wr: w, bufStats: e.bufStats} + e.encodeBuffer = encodeBuffer{Buf: b, wr: w, availBuffer: e.availBuffer, bufStats: e.bufStats} if bb, ok := w.(*bytes.Buffer); ok && bb != nil { e.Buf = bb.AvailableBuffer() // alias the unused buffer of bb } -- cgit v1.3