2016-08-05 07:47:04 +02:00
|
|
|
package bytepool
|
|
|
|
|
|
|
|
import "sync"
|
|
|
|
|
|
|
|
// BytePool is a cached pool of reusable byte slices.
|
|
|
|
type BytePool struct {
|
|
|
|
sync.Pool
|
|
|
|
}
|
|
|
|
|
2016-09-05 18:30:03 +02:00
|
|
|
// New allocates a new BytePool with slices of equal length and capacity.
|
|
|
|
func New(length int) *BytePool {
|
2016-08-05 07:47:04 +02:00
|
|
|
var bp BytePool
|
|
|
|
bp.Pool.New = func() interface{} {
|
2022-01-15 19:31:14 +01:00
|
|
|
return make([]byte, length)
|
2016-08-05 07:47:04 +02:00
|
|
|
}
|
|
|
|
return &bp
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get returns a byte slice from the pool.
|
|
|
|
func (bp *BytePool) Get() []byte {
|
|
|
|
return bp.Pool.Get().([]byte)
|
|
|
|
}
|
|
|
|
|
|
|
|
// Put returns a byte slice to the pool.
|
|
|
|
func (bp *BytePool) Put(b []byte) {
|
2016-08-07 04:43:33 +02:00
|
|
|
b = b[:cap(b)]
|
2016-08-05 07:47:04 +02:00
|
|
|
// Zero out the bytes.
|
2016-08-07 04:43:33 +02:00
|
|
|
// Apparently this specific expression is optimized by the compiler, see
|
|
|
|
// github.com/golang/go/issues/5373.
|
|
|
|
for i := range b {
|
|
|
|
b[i] = 0
|
2016-08-05 07:47:04 +02:00
|
|
|
}
|
|
|
|
bp.Pool.Put(b)
|
|
|
|
}
|