Files
EdgeNode/internal/utils/byte_pool.go

47 lines
834 B
Go
Raw Normal View History

2020-09-26 08:07:07 +08:00
package utils
2021-12-19 11:32:26 +08:00
import (
2022-08-07 11:12:29 +08:00
"sync"
2021-12-19 11:32:26 +08:00
)
2020-09-26 08:07:07 +08:00
2022-08-07 11:12:29 +08:00
var BytePool1k = NewBytePool(1024)
var BytePool4k = NewBytePool(4 * 1024)
var BytePool16k = NewBytePool(16 * 1024)
var BytePool32k = NewBytePool(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 {
length int
2022-08-07 11:12:29 +08:00
rawPool *sync.Pool
2020-09-26 08:07:07 +08:00
}
2021-12-19 11:32:26 +08:00
// NewBytePool 创建新对象
2022-08-07 11:12:29 +08:00
func NewBytePool(length int) *BytePool {
if length < 0 {
length = 1024
2020-09-26 08:07:07 +08:00
}
2022-08-07 11:12:29 +08:00
return &BytePool{
length: length,
rawPool: &sync.Pool{
New: func() any {
return make([]byte, length)
},
},
2020-09-26 08:07:07 +08:00
}
2021-12-19 11:32:26 +08:00
}
// Get 获取一个新的byte slice
2022-08-07 11:12:29 +08:00
func (this *BytePool) Get() []byte {
return this.rawPool.Get().([]byte)
2020-09-26 08:07:07 +08:00
}
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) {
2022-08-07 11:12:29 +08:00
this.rawPool.Put(b)
2020-09-26 08:07:07 +08:00
}
2021-12-19 11:32:26 +08:00
// Length 单个字节slice长度
func (this *BytePool) Length() int {
return this.length
}