github.com/TeaOSLab/EdgeNode@v1.3.8/internal/utils/byte_pool.go (about) 1 package utils 2 3 import ( 4 "sync" 5 ) 6 7 var BytePool1k = NewBytePool(1 << 10) 8 var BytePool4k = NewBytePool(4 << 10) 9 var BytePool16k = NewBytePool(16 << 10) 10 var BytePool32k = NewBytePool(32 << 10) 11 12 type BytesBuf struct { 13 Bytes []byte 14 } 15 16 // BytePool pool for get byte slice 17 type BytePool struct { 18 length int 19 rawPool *sync.Pool 20 } 21 22 // NewBytePool 创建新对象 23 func NewBytePool(length int) *BytePool { 24 if length < 0 { 25 length = 1024 26 } 27 return &BytePool{ 28 length: length, 29 rawPool: &sync.Pool{ 30 New: func() any { 31 return &BytesBuf{ 32 Bytes: make([]byte, length), 33 } 34 }, 35 }, 36 } 37 } 38 39 // Get 获取一个新的byte slice 40 func (this *BytePool) Get() *BytesBuf { 41 return this.rawPool.Get().(*BytesBuf) 42 } 43 44 // Put 放回一个使用过的byte slice 45 func (this *BytePool) Put(ptr *BytesBuf) { 46 this.rawPool.Put(ptr) 47 } 48 49 // Length 单个字节slice长度 50 func (this *BytePool) Length() int { 51 return this.length 52 }