mirror of
https://github.com/charlienet/go-mixed.git
synced 2025-07-18 08:32:40 +08:00
字节数组池
This commit is contained in:
36
bytePool/byte_pool.go
Normal file
36
bytePool/byte_pool.go
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
package bytecache
|
||||||
|
|
||||||
|
type BytePool struct {
|
||||||
|
c chan []byte
|
||||||
|
w int
|
||||||
|
wcap int
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewBytePool(poolSize, size, cap int) *BytePool {
|
||||||
|
return &BytePool{
|
||||||
|
c: make(chan []byte, poolSize),
|
||||||
|
w: size,
|
||||||
|
wcap: cap,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bp *BytePool) Get() (b []byte) {
|
||||||
|
select {
|
||||||
|
case b = <-bp.c:
|
||||||
|
default:
|
||||||
|
if bp.wcap > 0 {
|
||||||
|
b = make([]byte, bp.w, bp.wcap)
|
||||||
|
} else {
|
||||||
|
b = make([]byte, bp.w)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
func (bp *BytePool) Put(b []byte) {
|
||||||
|
select {
|
||||||
|
case bp.c <- b:
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
11
bytePool/byte_pool_test.go
Normal file
11
bytePool/byte_pool_test.go
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
package bytecache
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestByteCache(t *testing.T) {
|
||||||
|
bp := NewBytePool(512, 1024, 1024)
|
||||||
|
buffer := bp.Get()
|
||||||
|
defer bp.Put(buffer)
|
||||||
|
|
||||||
|
t.Log(len(buffer))
|
||||||
|
}
|
Reference in New Issue
Block a user