From 2d8732a29d41869bd46c2c48a4e92f9781b71449 Mon Sep 17 00:00:00 2001 From: qydysky Date: Thu, 14 Dec 2023 23:03:52 +0800 Subject: [PATCH] 1 --- .github/workflows/test.yml | 1 + slice/Blocks.go | 32 +++++++++++++++++++++----------- slice/Blocks_test.go | 19 +++++++++++++++++-- 3 files changed, 39 insertions(+), 13 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index a9f0cd6..431d9d8 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -40,6 +40,7 @@ jobs: go test -count 1 -timeout 10s -v -race github.com/qydysky/part/rpc go test -count 1 -timeout 5s -v -race github.com/qydysky/part/component go test -count 1 -timeout 15s -v -race github.com/qydysky/part/ctx + go test -count 1 -timeout 5s -v -race github.com/qydysky/part/slice - name: Set Release Name run: | diff --git a/slice/Blocks.go b/slice/Blocks.go index b3a6752..39c907b 100644 --- a/slice/Blocks.go +++ b/slice/Blocks.go @@ -4,16 +4,33 @@ import ( "errors" ) -type Blocks[T any] struct { +type BlocksI[T any] interface { + // // eg + // + // if tmpbuf, putBack, e := buf.Get(); e == nil { + // clear(tmpbuf) + // // do something with tmpbuf + // putBack() + // } + Get() ([]T, func(), error) +} + +type blocks[T any] struct { + _ noCopy free chan int size int buf []T } +type noCopy struct{} + +func (*noCopy) Lock() {} +func (*noCopy) Unlock() {} + var ErrOverflow = errors.New("ErrOverflow") -func NewBlocks[T any](blockSize int, blockNum int) *Blocks[T] { - p := &Blocks[T]{ +func NewBlocks[T any](blockSize int, blockNum int) BlocksI[T] { + p := &blocks[T]{ size: blockSize, free: make(chan int, blockNum+1), buf: make([]T, blockSize*blockNum), @@ -24,14 +41,7 @@ func NewBlocks[T any](blockSize int, blockNum int) *Blocks[T] { return p } -// // eg -// -// if tmpbuf, putBack, e := buf.Get(); e == nil { -// clear(tmpbuf) -// // do something with tmpbuf -// putBack() -// } -func (t *Blocks[T]) Get() ([]T, func(), error) { +func (t *blocks[T]) Get() ([]T, func(), error) { select { case offset := <-t.free: offset *= t.size diff --git a/slice/Blocks_test.go b/slice/Blocks_test.go index b6eae39..303e159 100644 --- a/slice/Blocks_test.go +++ b/slice/Blocks_test.go @@ -1,12 +1,27 @@ package part -import "testing" +import ( + "testing" +) func TestMain(t *testing.T) { - buf := NewBlocks[byte](1024, 10) + buf := NewBlocks[byte](1024, 1) if tmpbuf, putBack, e := buf.Get(); e == nil { clear(tmpbuf) // do something with tmpbuf putBack() + } else { + t.Fail() + } + if tmpbuf, putBack, e := buf.Get(); e == nil { + clear(tmpbuf) + if tmpbuf, putBack, e := buf.Get(); e != ErrOverflow { + clear(tmpbuf) + t.Fail() + // do something with tmpbuf + putBack() + } + // do something with tmpbuf + putBack() } } -- 2.39.2