From cb784005a33554c75b44315776d71feb829e9d76 Mon Sep 17 00:00:00 2001 From: qydysky <32743305+qydysky@users.noreply.github.com> Date: Sat, 4 Mar 2023 19:29:53 +0800 Subject: [PATCH] Improve --- slice/Slice.go | 15 ++++++++------- slice/Slice_test.go | 16 ++++++++++------ 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/slice/Slice.go b/slice/Slice.go index 57feeff..1577443 100644 --- a/slice/Slice.go +++ b/slice/Slice.go @@ -160,17 +160,18 @@ func (t *Buf[T]) GetCopyBuf() (buf []T) { return } -// Need to lock when processing buf or Make sure buf only processing by GetBufCopy -func (t *Buf[T]) GetBufCopy(buf *[]T) { +// *Need to lock when processing buf or Make sure buf only processing by AppendBufCopy +// +// *Not use b = make() to avoid pointer change +func (t *Buf[T]) AppendBufCopy(buf *[]T) { t.RLock() defer t.RUnlock() - if len(*buf) == 0 { + origin := len(*buf) + if origin == 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] + *buf = append(*buf, make([]T, t.bufsize)...) } - copy(*buf, t.buf[:t.bufsize]) + copy((*buf)[origin:], t.buf[:t.bufsize]) } diff --git a/slice/Slice_test.go b/slice/Slice_test.go index be386e4..c610c68 100644 --- a/slice/Slice_test.go +++ b/slice/Slice_test.go @@ -3,6 +3,7 @@ package part import ( "bytes" "testing" + "unsafe" ) func TestXxx(t *testing.T) { @@ -82,26 +83,29 @@ func TestXxx2(t *testing.T) { func TestXxx3(t *testing.T) { var c = New[byte]() - var b = []byte{} + var b []byte + var bp = unsafe.Pointer(&b) c.Append([]byte("12345")) c.Append([]byte("67890")) - c.GetBufCopy(&b) + c.AppendBufCopy(&b) c.Reset() if !bytes.Equal(b, []byte("1234567890")) { t.Fatal(string(b)) } + b = []byte{} c.Append([]byte("abc")) c.Append([]byte("defg")) - c.GetBufCopy(&b) + c.AppendBufCopy(&b) c.Reset() - if !bytes.Equal(b, []byte("abcdefg")) { + if !bytes.Equal(b, []byte("abcdefg")) || unsafe.Pointer(&b) != bp { t.Fatal() } + b = b[:0] c.Append([]byte("akjsdhfaksdjhf")) c.Append([]byte("9834719203857")) - c.GetBufCopy(&b) + c.AppendBufCopy(&b) c.Reset() - if !bytes.Equal(b, []byte("akjsdhfaksdjhf9834719203857")) { + if !bytes.Equal(b, []byte("akjsdhfaksdjhf9834719203857")) || unsafe.Pointer(&b) != bp { t.Fatal() } } -- 2.39.2