Files
EdgeNode/internal/utils/byte_pool.go

53 lines
917 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
2024-03-28 17:17:34 +08:00
var BytePool1k = NewBytePool(1 << 10)
var BytePool4k = NewBytePool(4 << 10)
var BytePool16k = NewBytePool(16 << 10)
var BytePool32k = NewBytePool(32 << 10)
2020-09-26 08:07:07 +08:00
2024-04-15 09:26:00 +08:00
type BytesBuf struct {
Bytes []byte
}
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 {
2024-04-15 09:26:00 +08:00
return &BytesBuf{
Bytes: make([]byte, length),
}
2022-08-07 11:12:29 +08:00
},
},
2020-09-26 08:07:07 +08:00
}
2021-12-19 11:32:26 +08:00
}
// Get 获取一个新的byte slice
2024-04-15 09:26:00 +08:00
func (this *BytePool) Get() *BytesBuf {
return this.rawPool.Get().(*BytesBuf)
2020-09-26 08:07:07 +08:00
}
2021-12-19 11:32:26 +08:00
// Put 放回一个使用过的byte slice
2024-04-15 09:26:00 +08:00
func (this *BytePool) Put(ptr *BytesBuf) {
this.rawPool.Put(ptr)
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
}