Skip to content

Commit

Permalink
pkgs/bytes: init bytes pool
Browse files Browse the repository at this point in the history
  • Loading branch information
5aaee9 committed Jun 27, 2023
1 parent 71bb3c4 commit 2a1b90a
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
31 changes: 31 additions & 0 deletions pkgs/bytes/pool.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package bytes

import "sync"

type BytesPool struct {
size uint
pool sync.Pool
}

func NewBytesPool(size uint) *BytesPool {
return &BytesPool{
size: size,
pool: sync.Pool{
New: func() any {
return make([]byte, size)
},
},
}
}

func (p *BytesPool) Get() []byte {
return p.pool.Get().([]byte)
}

func (p *BytesPool) Put(data []byte) {
if uint(len(data)) != p.size {
panic("buf size not match pool size")
}

p.pool.Put(data)
}
33 changes: 33 additions & 0 deletions pkgs/bytes/pool_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package bytes

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestPoolGet(t *testing.T) {
pool := NewBytesPool(200)
assert.Equal(t, 200, len(pool.Get()))

pool = NewBytesPool(1025)
assert.Equal(t, 1025, len(pool.Get()))

pool = NewBytesPool(2 * 1024)
assert.Equal(t, 2*1024, len(pool.Get()))

pool = NewBytesPool(5 * 2000)
assert.Equal(t, 5*2000, len(pool.Get()))
}

func TestPoolPut(t *testing.T) {
pool := NewBytesPool(200)

assert.Panics(t, func() {
pool.Put(make([]byte, 2000))
})

assert.NotPanics(t, func() {
pool.Put(make([]byte, 200))
})
}

0 comments on commit 2a1b90a

Please sign in to comment.