make sure the tmp is not be covered

This commit is contained in:
maskpp 2025-09-07 23:00:06 +08:00
parent 8ce2047348
commit 0d362be009
3 changed files with 15 additions and 8 deletions

View file

@ -359,11 +359,16 @@ func (w *EncoderBuffer) ToBytes() []byte {
} }
// AppendToBytes appends the encoded bytes to dst. // AppendToBytes appends the encoded bytes to dst.
func (w *EncoderBuffer) AppendToBytes(dst []byte) []byte { func (w *EncoderBuffer) AppendToBytes(dst *[]byte) {
size := w.buf.size() size := w.buf.size()
out := append(dst, make([]byte, size)...) tmp, length := *dst, len(*dst)
w.buf.copyTo(out[len(dst):]) if cap(tmp) >= size+length {
return out tmp = tmp[:size+length]
} else {
tmp = append(tmp, make([]byte, size)...)
}
*dst = tmp
w.buf.copyTo(tmp[length:])
} }
// Write appends b directly to the encoder output. // Write appends b directly to the encoder output.

View file

@ -435,7 +435,7 @@ func TestEncodeToBytes(t *testing.T) {
} }
func TestEncodeAppendToBytes(t *testing.T) { func TestEncodeAppendToBytes(t *testing.T) {
buffer := make([]byte, 20) buffer := make([]byte, 3)
runEncTests(t, func(val interface{}) ([]byte, error) { runEncTests(t, func(val interface{}) ([]byte, error) {
w := NewEncoderBuffer(nil) w := NewEncoderBuffer(nil)
defer w.Flush() defer w.Flush()
@ -444,8 +444,9 @@ func TestEncodeAppendToBytes(t *testing.T) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
output := w.AppendToBytes(buffer[:0]) buffer = buffer[:0]
return output, nil w.AppendToBytes(&buffer)
return buffer, nil
}) })
} }

View file

@ -181,7 +181,8 @@ func (h *hasher) encodeFullNode(n *fullNode) []byte {
// This convention exists because node.encode can only be inlined/escape-analyzed when // This convention exists because node.encode can only be inlined/escape-analyzed when
// called on a concrete receiver type. // called on a concrete receiver type.
func (h *hasher) encodedBytes() []byte { func (h *hasher) encodedBytes() []byte {
h.tmp = h.encbuf.AppendToBytes(h.tmp[:0]) h.tmp = h.tmp[:0]
h.encbuf.AppendToBytes(&h.tmp)
h.encbuf.Reset(nil) h.encbuf.Reset(nil)
return h.tmp return h.tmp
} }