From ff0b0b16401bf9965078bd55db9baf701456096b Mon Sep 17 00:00:00 2001 From: Darien Raymond Date: Mon, 3 Sep 2018 20:57:40 +0200 Subject: [PATCH] GetPool() API --- common/buf/buffer.go | 4 +++- common/bytespool/pool.go | 16 +++++++++++++--- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/common/buf/buffer.go b/common/buf/buffer.go index 4f85792e..e8ab7755 100644 --- a/common/buf/buffer.go +++ b/common/buf/buffer.go @@ -172,9 +172,11 @@ func (b *Buffer) String() string { return string(b.Bytes()) } +var pool = bytespool.GetPool(Size) + // New creates a Buffer with 0 length and 2K capacity. func New() *Buffer { return &Buffer{ - v: bytespool.Alloc(Size), + v: pool.Get().([]byte), } } diff --git a/common/bytespool/pool.go b/common/bytespool/pool.go index 11668a55..b8ab3d7d 100644 --- a/common/bytespool/pool.go +++ b/common/bytespool/pool.go @@ -33,13 +33,23 @@ func init() { } } -// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 2048. -func Alloc(size int32) []byte { +// GetPool returns a sync.Pool that generates bytes array with at least the given size. +// It may return nil if no such pool exists. +func GetPool(size int32) *sync.Pool { for idx, ps := range poolSize { if size <= ps { - return pool[idx].Get().([]byte) + return &pool[idx] } } + return nil +} + +// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 2048. +func Alloc(size int32) []byte { + pool := GetPool(size) + if pool != nil { + return pool.Get().([]byte) + } return make([]byte, size) }