From bbedbbc41b66a3803c3e675adfaa1ff38accfb37 Mon Sep 17 00:00:00 2001 From: qydysky <32743305+qydysky@users.noreply.github.com> Date: Sat, 4 Mar 2023 19:10:08 +0800 Subject: [PATCH] Add --- slice/Slice.go | 15 +++++++++++++++ slice/Slice_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) 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() + } +} -- 2.39.2