From 6536a9354728523f7ac3627f558ba3f51163e72c Mon Sep 17 00:00:00 2001 From: Filip Petkovski Date: Mon, 23 Jun 2025 11:47:21 +0000 Subject: encoding/json/jsontext: preserve buffer capacity in Decoder.Reset The Decoder.Reset method is not preserving the internal buffer between resets, causing buffer capacity to be lost and resulting in unnecessary allocations when reusing decoders. This is particularly problematic when decoding many small messages. This commit fixes the Reset method to preserve the internal buffer. It makes sure aliasing is removed if the buffer currently points to an internal byte slice of a bytes.Buffer. It adds a TestDecoderReset test structured into subtests to better validate the different scenarios. Change-Id: Ia685bff47034598224489173bb7f2ffd48e89da5 GitHub-Last-Rev: 462ddc936409ee3da6d75def7d9de59eb3c65f8d GitHub-Pull-Request: golang/go#74120 Reviewed-on: https://go-review.googlesource.com/c/go/+/681177 Reviewed-by: Sean Liao Reviewed-by: Joseph Tsai LUCI-TryBot-Result: Go LUCI Reviewed-by: Dmitri Shuralyov Reviewed-by: Damien Neil Auto-Submit: Joseph Tsai --- src/encoding/json/jsontext/decode.go | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) (limited to 'src/encoding/json/jsontext/decode.go') diff --git a/src/encoding/json/jsontext/decode.go b/src/encoding/json/jsontext/decode.go index 784ae4709a..44b436686f 100644 --- a/src/encoding/json/jsontext/decode.go +++ b/src/encoding/json/jsontext/decode.go @@ -138,7 +138,14 @@ func (d *Decoder) Reset(r io.Reader, opts ...Options) { case d.s.Flags.Get(jsonflags.WithinArshalCall): panic("jsontext: cannot reset Decoder passed to json.UnmarshalerFrom") } - d.s.reset(nil, r, opts...) + // If the decoder was previously aliasing a bytes.Buffer, + // invalidate the alias to avoid writing into the bytes.Buffer's + // internal buffer. + b := d.s.buf[:0] + if _, ok := d.s.rd.(*bytes.Buffer); ok { + b = nil // avoid reusing b since it aliases the previous bytes.Buffer. + } + d.s.reset(b, r, opts...) } func (d *decoderState) reset(b []byte, r io.Reader, opts ...Options) { -- cgit v1.3-5-g9baa