Files
EdgeNode/internal/utils/byte_pool.go

109 lines
1.7 KiB
Go
Raw Normal View History

2020-09-26 08:07:07 +08:00
package utils
2021-12-19 11:32:26 +08:00
import (
"github.com/TeaOSLab/EdgeNode/internal/goman"
"github.com/iwind/TeaGo/Tea"
"time"
)
2020-09-26 08:07:07 +08:00
2021-12-19 11:32:26 +08:00
var BytePool1k = NewBytePool(20480, 1024)
var BytePool4k = NewBytePool(20480, 4*1024)
var BytePool16k = NewBytePool(40960, 16*1024)
var BytePool32k = NewBytePool(20480, 32*1024)
2020-09-26 08:07:07 +08:00
2021-12-19 11:32:26 +08:00
// BytePool pool for get byte slice
type BytePool struct {
c chan []byte
maxSize int
length int
hasNew bool
2020-09-26 08:07:07 +08:00
}
2021-12-19 11:32:26 +08:00
// NewBytePool 创建新对象
2020-09-26 08:07:07 +08:00
func NewBytePool(maxSize, length int) *BytePool {
if maxSize <= 0 {
maxSize = 1024
}
if length <= 0 {
length = 128
}
2021-12-19 11:32:26 +08:00
var pool = &BytePool{
c: make(chan []byte, maxSize),
maxSize: maxSize,
length: length,
2020-09-26 08:07:07 +08:00
}
2021-12-19 11:32:26 +08:00
pool.init()
2020-09-26 08:07:07 +08:00
return pool
}
2021-12-19 11:32:26 +08:00
// 初始化
func (this *BytePool) init() {
var ticker = time.NewTicker(2 * time.Minute)
if Tea.IsTesting() {
ticker = time.NewTicker(5 * time.Second)
}
goman.New(func() {
for range ticker.C {
if this.hasNew {
this.hasNew = false
continue
}
this.Purge()
}
})
}
// Get 获取一个新的byte slice
2020-09-26 08:07:07 +08:00
func (this *BytePool) Get() (b []byte) {
select {
case b = <-this.c:
default:
b = make([]byte, this.length)
2021-12-19 11:32:26 +08:00
this.hasNew = true
2020-09-26 08:07:07 +08:00
}
return
}
2021-12-19 11:32:26 +08:00
// Put 放回一个使用过的byte slice
2020-09-26 08:07:07 +08:00
func (this *BytePool) Put(b []byte) {
if cap(b) != this.length {
return
}
select {
case this.c <- b:
default:
// 已达最大容量,则抛弃
}
}
2021-12-19 11:32:26 +08:00
// Length 单个字节slice长度
func (this *BytePool) Length() int {
return this.length
}
// Size 当前的数量
2020-09-26 08:07:07 +08:00
func (this *BytePool) Size() int {
return len(this.c)
}
2021-12-19 11:32:26 +08:00
// Purge 清理
func (this *BytePool) Purge() {
// 1%
var count = len(this.c) / 100
if count == 0 {
return
}
Loop:
for i := 0; i < count; i++ {
select {
case <-this.c:
default:
break Loop
}
}
}