From 57b9100cb44aa565337b33ce674404dc04cc5ea7 Mon Sep 17 00:00:00 2001 From: Dv2Corn <320380254+Dv2Corn@users.noreply.github.com> Date: Sun, 8 Nov 2026 22:00:24 +0000 Subject: [PATCH] Fix: buf.Compact dropping data when the buffer has no room after its end Compact decided whether to merge the next buffer by comparing the total length with Size, but the bytes are copied after the end of the previous buffer. When that buffer had been advanced (SplitSize, partial Read, header stripping) or wraps a byte slice (FromBytes), the room after its end is smaller than Size - Len(), so ReadFrom copied only part of the next buffer and the rest was released and lost. Check the room after the end instead. --- common/buf/multi_buffer.go | 2 +- common/buf/multi_buffer_test.go | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/common/buf/multi_buffer.go b/common/buf/multi_buffer.go index 7a62ec48eed..6ca26e366c9 100644 --- a/common/buf/multi_buffer.go +++ b/common/buf/multi_buffer.go @@ -144,7 +144,7 @@ func Compact(mb MultiBuffer) MultiBuffer { for i := 1; i < len(mb); i++ { curr := mb[i] - if last.Len()+curr.Len() > Size { + if last.end+curr.Len() > last.Cap() { mb2 = append(mb2, last) last = curr } else { diff --git a/common/buf/multi_buffer_test.go b/common/buf/multi_buffer_test.go index b8d242da13d..d9f1725e8cf 100644 --- a/common/buf/multi_buffer_test.go +++ b/common/buf/multi_buffer_test.go @@ -176,6 +176,25 @@ func TestCompact(t *testing.T) { } } +func TestCompactBufferWithoutRoom(t *testing.T) { + a := New() + common.Must2(a.Write(bytes.Repeat([]byte{'a'}, 1500))) + a.Advance(1000) + b := New() + common.Must2(b.Write(bytes.Repeat([]byte{'b'}, 1000))) + + c := FromBytes([]byte("cd")) + d := New() + common.Must2(d.WriteString("ef")) + + for _, mb := range []MultiBuffer{{a, b}, {c, d}} { + want := mb.String() + if got := Compact(mb).String(); got != want { + t.Error("unexpected Compact result length ", len(got), ", want ", len(want)) + } + } +} + func BenchmarkSplitBytes(b *testing.B) { var mb MultiBuffer raw := make([]byte, Size)