Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions mem/buffer_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,11 @@ type sizedBufferPool struct {
}

func (p *sizedBufferPool) Get(size int) *[]byte {
buf := p.pool.Get().(*[]byte)
buf, ok := p.pool.Get().(*[]byte)
if !ok {
buf := make([]byte, size, p.defaultSize)
return &buf
}
b := *buf
clear(b[:cap(b)])
*buf = b[:size]
Expand All @@ -137,12 +141,6 @@ func (p *sizedBufferPool) Put(buf *[]byte) {

func newSizedBufferPool(size int) *sizedBufferPool {
return &sizedBufferPool{
pool: sync.Pool{
New: func() any {
buf := make([]byte, size)
return &buf
},
},
defaultSize: size,
}
}
Expand All @@ -160,6 +158,7 @@ type simpleBufferPool struct {
func (p *simpleBufferPool) Get(size int) *[]byte {
bs, ok := p.pool.Get().(*[]byte)
if ok && cap(*bs) >= size {
clear((*bs)[:cap(*bs)])
*bs = (*bs)[:size]
return bs
}
Expand Down
52 changes: 35 additions & 17 deletions mem/buffer_pool_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,26 +49,44 @@ func (s) TestBufferPool(t *testing.T) {
}

func (s) TestBufferPoolClears(t *testing.T) {
pool := mem.NewTieredBufferPool(4)
const poolSize = 4
pool := mem.NewTieredBufferPool(poolSize)
tests := []struct {
name string
bufferSize int
}{
{
name: "sized_buffer_pool",
bufferSize: poolSize,
},
{
name: "simple_buffer_pool",
bufferSize: poolSize + 1,
},
}

for {
buf1 := pool.Get(4)
copy(*buf1, "1234")
pool.Put(buf1)
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
for {
buf1 := pool.Get(tc.bufferSize)
copy(*buf1, "1234")
pool.Put(buf1)

buf2 := pool.Get(4)
if unsafe.SliceData(*buf1) != unsafe.SliceData(*buf2) {
pool.Put(buf2)
// This test is only relevant if a buffer is reused, otherwise try again. This
// can happen if a GC pause happens between putting the buffer back in the pool
// and getting a new one.
continue
}
buf2 := pool.Get(tc.bufferSize)
if unsafe.SliceData(*buf1) != unsafe.SliceData(*buf2) {
pool.Put(buf2)
// This test is only relevant if a buffer is reused, otherwise try again. This
// can happen if a GC pause happens between putting the buffer back in the pool
// and getting a new one.
continue
}

if !bytes.Equal(*buf1, make([]byte, 4)) {
t.Fatalf("buffer not cleared")
}
break
if !bytes.Equal(*buf1, make([]byte, tc.bufferSize)) {
t.Fatalf("buffer not cleared")
}
break
}
})
}
}

Expand Down
Loading