Skip to content

Commit f3cdcad

Browse files
common/buf/multi_buffer.go: Fix Compact() (#5015)
Fixes #5012 Co-authored-by: patterniha <[email protected]>
1 parent 5a8e9c2 commit f3cdcad

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

common/buf/buffer.go

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,14 @@ func (b *Buffer) Cap() int32 {
244244
return int32(len(b.v))
245245
}
246246

247+
// Available returns the available capacity of the buffer content.
248+
func (b *Buffer) Available() int32 {
249+
if b == nil {
250+
return 0
251+
}
252+
return int32(len(b.v)) - b.end
253+
}
254+
247255
// IsEmpty returns true if the buffer is empty.
248256
func (b *Buffer) IsEmpty() bool {
249257
return b.Len() == 0

common/buf/multi_buffer.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ func Compact(mb MultiBuffer) MultiBuffer {
144144

145145
for i := 1; i < len(mb); i++ {
146146
curr := mb[i]
147-
if last.Len()+curr.Len() > Size {
147+
if curr.Len() > last.Available() {
148148
mb2 = append(mb2, last)
149149
last = curr
150150
} else {

common/buf/multi_buffer_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,29 @@ func TestCompact(t *testing.T) {
175175
}
176176
}
177177

178+
func TestCompactWithConsumed(t *testing.T) {
179+
// make a consumed buffer (a.Start != 0)
180+
a := New()
181+
for range 8192 {
182+
common.Must2(a.WriteString("a"))
183+
}
184+
a.Read(make([]byte, 2))
185+
186+
b := New()
187+
for range 2 {
188+
common.Must2(b.WriteString("b"))
189+
}
190+
191+
mb := MultiBuffer{a, b}
192+
cmb := Compact(mb)
193+
mbc := &MultiBufferContainer{mb}
194+
mbc.Read(make([]byte, 8190))
195+
196+
if w := cmb.String(); w != "bb" {
197+
t.Error("unexpected Compact result ", w)
198+
}
199+
}
200+
178201
func BenchmarkSplitBytes(b *testing.B) {
179202
var mb MultiBuffer
180203
raw := make([]byte, Size)

0 commit comments

Comments
 (0)