2016-12-09 11:35:27 +01:00
|
|
|
package buf
|
2016-04-12 16:52:57 +02:00
|
|
|
|
|
|
|
import (
|
|
|
|
"sync"
|
|
|
|
)
|
|
|
|
|
2016-12-06 17:26:51 +01:00
|
|
|
// Pool provides functionality to generate and recycle buffers on demand.
|
2018-03-08 22:30:52 +01:00
|
|
|
type Pool struct {
|
2016-11-21 22:08:34 +01:00
|
|
|
allocator *sync.Pool
|
|
|
|
}
|
|
|
|
|
2018-03-08 22:30:52 +01:00
|
|
|
// NewPool creates a SyncPool with given buffer size.
|
|
|
|
func NewPool(bufferSize uint32) *Pool {
|
|
|
|
pool := &Pool{
|
2016-11-21 22:08:34 +01:00
|
|
|
allocator: &sync.Pool{
|
|
|
|
New: func() interface{} { return make([]byte, bufferSize) },
|
|
|
|
},
|
|
|
|
}
|
|
|
|
return pool
|
|
|
|
}
|
|
|
|
|
2018-03-08 22:30:52 +01:00
|
|
|
// Allocate either returns a unused buffer from the pool, or generates a new one from system.
|
|
|
|
func (p *Pool) Allocate() *Buffer {
|
2016-12-11 09:43:20 +01:00
|
|
|
return &Buffer{
|
|
|
|
v: p.allocator.Get().([]byte),
|
|
|
|
pool: p,
|
|
|
|
}
|
2016-11-21 22:08:34 +01:00
|
|
|
}
|
|
|
|
|
2018-03-08 22:30:52 +01:00
|
|
|
// // Free recycles the given buffer.
|
|
|
|
func (p *Pool) Free(buffer *Buffer) {
|
2017-05-16 16:47:07 +02:00
|
|
|
if buffer.v != nil {
|
|
|
|
p.allocator.Put(buffer.v)
|
2016-11-21 22:08:34 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-05-11 10:54:20 -07:00
|
|
|
const (
|
2016-12-11 09:43:20 +01:00
|
|
|
// Size of a regular buffer.
|
2017-04-15 21:19:21 +02:00
|
|
|
Size = 2 * 1024
|
2016-05-11 10:54:20 -07:00
|
|
|
)
|
|
|
|
|
2018-03-08 22:30:52 +01:00
|
|
|
var mediumPool = NewPool(Size)
|