go-socks5/bufferpool/pool.go

41 lines
789 B
Go
Raw Permalink Normal View History

package bufferpool
2020-04-20 01:41:06 +00:00
import (
"sync"
)
// BufPool is an interface for getting and returning temporary
2020-08-06 02:12:46 +00:00
// byte slices for use by io.CopyBuffer.
type BufPool interface {
2020-08-06 02:12:46 +00:00
Get() []byte
Put([]byte)
}
2020-04-20 01:41:06 +00:00
type pool struct {
size int
pool *sync.Pool
}
2020-08-06 02:12:46 +00:00
// NewPool new buffer pool for getting and returning temporary
// byte slices for use by io.CopyBuffer.
func NewPool(size int) BufPool {
2020-04-20 01:41:06 +00:00
return &pool{
size,
&sync.Pool{
2020-08-05 06:40:07 +00:00
New: func() interface{} { return make([]byte, 0, size) }},
2020-04-20 01:41:06 +00:00
}
}
2020-08-06 02:12:46 +00:00
// Get implement interface BufPool
2020-04-20 01:41:06 +00:00
func (sf *pool) Get() []byte {
return sf.pool.Get().([]byte)
}
// Put implement interface BufPool
2020-04-20 01:41:06 +00:00
func (sf *pool) Put(b []byte) {
if cap(b) != sf.size {
panic("invalid buffer size that's put into leaky buffer")
}
2020-08-05 05:17:05 +00:00
sf.pool.Put(b[:0]) // nolint: staticcheck
2020-04-20 01:41:06 +00:00
}