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])
}
import (
"bytes"
"testing"
+ "unsafe"
)
func TestXxx(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()
}
}