GetPool() API

pull/1331/head
Darien Raymond 2018-09-03 20:57:40 +02:00
parent 1cf5225c0a
commit ff0b0b1640
No known key found for this signature in database
GPG Key ID: 7251FFA14BB18169
2 changed files with 16 additions and 4 deletions

View File

@ -172,9 +172,11 @@ func (b *Buffer) String() string {
return string(b.Bytes()) return string(b.Bytes())
} }
var pool = bytespool.GetPool(Size)
// New creates a Buffer with 0 length and 2K capacity. // New creates a Buffer with 0 length and 2K capacity.
func New() *Buffer { func New() *Buffer {
return &Buffer{ return &Buffer{
v: bytespool.Alloc(Size), v: pool.Get().([]byte),
} }
} }

View File

@ -33,13 +33,23 @@ func init() {
} }
} }
// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 2048. // GetPool returns a sync.Pool that generates bytes array with at least the given size.
func Alloc(size int32) []byte { // It may return nil if no such pool exists.
func GetPool(size int32) *sync.Pool {
for idx, ps := range poolSize { for idx, ps := range poolSize {
if size <= ps { 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) return make([]byte, size)
} }