tracker/frontend/udp/bytepool/bytepool.go

38 lines
742 B
Go
Raw Normal View History

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{} {
b := make([]byte, length)
return &b
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)
2016-08-05 07:47:04 +02:00
}
// Put returns a byte slice to the pool.
func (bp *BytePool) Put(b *[]byte) {
*b = (*b)[:cap(*b)]
2016-08-05 07:47:04 +02:00
// Zero out the bytes.
// This specific expression is optimized by the compiler:
// https://github.com/golang/go/issues/5373.
for i := range *b {
(*b)[i] = 0
2016-08-05 07:47:04 +02:00
}
2016-08-05 07:47:04 +02:00
bp.Pool.Put(b)
}