From: qydysky <32743305+qydysky@users.noreply.github.com> Date: Sat, 4 Mar 2023 11:10:08 +0000 (+0800) Subject: Add X-Git-Tag: v0.23.9 X-Git-Url: http://127.0.0.1:8081/?a=commitdiff_plain;h=bbedbbc41b66a3803c3e675adfaa1ff38accfb37;p=part%2F.git Add --- diff --git a/slice/Slice.go b/slice/Slice.go index 2a07109..57feeff 100644 --- a/slice/Slice.go +++ b/slice/Slice.go @@ -159,3 +159,18 @@ func (t *Buf[T]) GetCopyBuf() (buf []T) { copy(buf, t.buf[:t.bufsize]) return } + +// Need to lock when processing buf or Make sure buf only processing by GetBufCopy +func (t *Buf[T]) GetBufCopy(buf *[]T) { + t.RLock() + defer t.RUnlock() + + if len(*buf) == 0 { + *buf = make([]T, t.bufsize) + } else if len(*buf) < t.bufsize { + *buf = append(*buf, make([]T, t.bufsize-len(*buf))...) + } else { + *buf = (*buf)[:t.bufsize] + } + copy(*buf, t.buf[:t.bufsize]) +} diff --git a/slice/Slice_test.go b/slice/Slice_test.go index a093095..be386e4 100644 --- a/slice/Slice_test.go +++ b/slice/Slice_test.go @@ -79,3 +79,29 @@ func TestXxx2(t *testing.T) { t.Fatal() } } + +func TestXxx3(t *testing.T) { + var c = New[byte]() + var b = []byte{} + c.Append([]byte("12345")) + c.Append([]byte("67890")) + c.GetBufCopy(&b) + c.Reset() + if !bytes.Equal(b, []byte("1234567890")) { + t.Fatal(string(b)) + } + c.Append([]byte("abc")) + c.Append([]byte("defg")) + c.GetBufCopy(&b) + c.Reset() + if !bytes.Equal(b, []byte("abcdefg")) { + t.Fatal() + } + c.Append([]byte("akjsdhfaksdjhf")) + c.Append([]byte("9834719203857")) + c.GetBufCopy(&b) + c.Reset() + if !bytes.Equal(b, []byte("akjsdhfaksdjhf9834719203857")) { + t.Fatal() + } +}