// Package iobufpool implements a global segregated-fit pool of buffers for IO. // // It uses *[]byte instead of []byte to avoid the sync.Pool allocation with Put. Unfortunately, using a pointer to avoid // an allocation is purposely not documented. https://github.com/golang/go/issues/16323
package iobufpool import const minPoolExpOf2 = 8 var pools [18]*sync.Pool func init() { for := range pools { := 1 << (minPoolExpOf2 + ) pools[] = &sync.Pool{ New: func() any { := make([]byte, ) return & }, } } } // Get gets a []byte of len size with cap <= size*2. func ( int) *[]byte { := getPoolIdx() if >= len(pools) { := make([]byte, ) return & } := (pools[].Get().(*[]byte)) * = (*)[:] return } func getPoolIdx( int) int { -- >>= minPoolExpOf2 := 0 for > 0 { >>= 1 ++ } return } // Put returns buf to the pool. func ( *[]byte) { := putPoolIdx(cap(*)) if < 0 { return } pools[].Put() } func putPoolIdx( int) int { := 1 << minPoolExpOf2 for := range pools { if == << { return } } return -1 }