From 59ea343843643f8d7e67a614a5dafd42b928e6c2 Mon Sep 17 00:00:00 2001 From: charlie <3140647@qq.com> Date: Sun, 27 Mar 2022 10:18:50 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AD=97=E8=8A=82=E6=95=B0=E7=BB=84=E6=B1=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- bytePool/byte_pool.go | 36 ++++++++++++++++++++++++++++++++++++ bytePool/byte_pool_test.go | 11 +++++++++++ 2 files changed, 47 insertions(+) create mode 100644 bytePool/byte_pool.go create mode 100644 bytePool/byte_pool_test.go diff --git a/bytePool/byte_pool.go b/bytePool/byte_pool.go new file mode 100644 index 0000000..44954d6 --- /dev/null +++ b/bytePool/byte_pool.go @@ -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: + } +} diff --git a/bytePool/byte_pool_test.go b/bytePool/byte_pool_test.go new file mode 100644 index 0000000..85fe757 --- /dev/null +++ b/bytePool/byte_pool_test.go @@ -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)) +}