nps/lib/common/pool.go

96 lines
1.7 KiB
Go
Raw Permalink Normal View History

package common
2019-02-09 09:07:47 +00:00
import (
"sync"
)
const PoolSize = 64 * 1024
const PoolSizeSmall = 100
2019-12-02 16:46:30 +00:00
const PoolSizeUdp = 1472 + 200
2019-03-02 14:57:05 +00:00
const PoolSizeCopy = 32 << 10
2019-02-09 09:07:47 +00:00
var BufPool = sync.Pool{
New: func() interface{} {
return make([]byte, PoolSize)
},
}
var BufPoolUdp = sync.Pool{
New: func() interface{} {
return make([]byte, PoolSizeUdp)
},
}
var BufPoolMax = sync.Pool{
New: func() interface{} {
return make([]byte, PoolSize)
},
}
var BufPoolSmall = sync.Pool{
New: func() interface{} {
return make([]byte, PoolSizeSmall)
},
}
var BufPoolCopy = sync.Pool{
New: func() interface{} {
2019-08-26 13:42:20 +00:00
return make([]byte, PoolSizeCopy)
2019-02-09 09:07:47 +00:00
},
}
2019-08-23 10:53:36 +00:00
2019-02-17 11:36:48 +00:00
func PutBufPoolUdp(buf []byte) {
if cap(buf) == PoolSizeUdp {
BufPoolUdp.Put(buf[:PoolSizeUdp])
}
}
2019-02-09 09:07:47 +00:00
func PutBufPoolCopy(buf []byte) {
if cap(buf) == PoolSizeCopy {
2019-08-26 13:42:20 +00:00
BufPoolCopy.Put(buf[:PoolSizeCopy])
2019-02-09 09:07:47 +00:00
}
}
2019-08-23 10:53:36 +00:00
func GetBufPoolCopy() []byte {
2019-08-26 13:42:20 +00:00
return (BufPoolCopy.Get().([]byte))[:PoolSizeCopy]
2019-03-15 06:03:49 +00:00
}
2019-02-17 11:36:48 +00:00
func PutBufPoolMax(buf []byte) {
if cap(buf) == PoolSize {
BufPoolMax.Put(buf[:PoolSize])
2019-02-09 09:07:47 +00:00
}
}
2019-08-23 10:53:36 +00:00
2019-09-08 15:49:16 +00:00
type copyBufferPool struct {
2019-08-26 15:29:22 +00:00
pool sync.Pool
}
2019-09-08 15:49:16 +00:00
func (Self *copyBufferPool) New() {
2019-08-26 15:29:22 +00:00
Self.pool = sync.Pool{
New: func() interface{} {
2019-08-27 12:07:37 +00:00
return make([]byte, PoolSizeCopy, PoolSizeCopy)
2019-08-26 15:29:22 +00:00
},
}
}
2019-09-08 15:49:16 +00:00
func (Self *copyBufferPool) Get() []byte {
2019-08-27 12:07:37 +00:00
buf := Self.pool.Get().([]byte)
return buf[:PoolSizeCopy] // just like make a new slice, but data may not be 0
2019-08-26 15:29:22 +00:00
}
2019-09-08 15:49:16 +00:00
func (Self *copyBufferPool) Put(x []byte) {
if len(x) == PoolSizeCopy {
Self.pool.Put(x)
} else {
2019-09-08 15:49:16 +00:00
x = nil // buf is not full, not allowed, New method returns a full buf
}
2019-08-26 15:29:22 +00:00
}
2019-08-23 10:53:36 +00:00
var once = sync.Once{}
2019-09-08 15:49:16 +00:00
var CopyBuff = copyBufferPool{}
2019-08-26 15:29:22 +00:00
func newPool() {
CopyBuff.New()
}
2019-08-23 10:53:36 +00:00
func init() {
2019-08-26 15:29:22 +00:00
once.Do(newPool)
2019-08-23 10:53:36 +00:00
}