]> 127.0.0.1 Git - part/.git/commitdiff
Improve v0.23.10
authorqydysky <32743305+qydysky@users.noreply.github.com>
Sat, 4 Mar 2023 11:29:53 +0000 (19:29 +0800)
committerqydysky <32743305+qydysky@users.noreply.github.com>
Sat, 4 Mar 2023 11:29:53 +0000 (19:29 +0800)
slice/Slice.go
slice/Slice_test.go

index 57feeff4e43acdbb3ba8157a9fc8b5ca50ccdcf8..1577443e65c221b7ff14df3f5de73f501e72bc5d 100644 (file)
@@ -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])
 }
index be386e4e90b047aac9674e7d38dcf1b222b00505..c610c685680ab6d75805e814e071c7ecb93b7c6b 100644 (file)
@@ -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()
        }
 }