From: qydysky Date: Sat, 16 Mar 2024 09:43:55 +0000 (+0800) Subject: slices.Buf[T any].GetPureBufRLock X-Git-Tag: v0.28.20240316094927 X-Git-Url: http://127.0.0.1:8081/?a=commitdiff_plain;h=f1b82e5bfd98aa6d8e6229363f0ca0ecbcabd426;p=part%2F.git slices.Buf[T any].GetPureBufRLock --- diff --git a/slice/Slice.go b/slice/Slice.go index 046b726..8f028b0 100644 --- a/slice/Slice.go +++ b/slice/Slice.go @@ -151,6 +151,18 @@ func (t *Buf[T]) GetPureBuf() (buf []T) { return t.buf[:t.bufsize] } +// must call unlock +// +// buf will no modify before unlock +// +// modify func(eg Reset) with block until unlock +// +// unsafe +func (t *Buf[T]) GetPureBufRLock() (buf []T, unlock func()) { + t.l.RLock() + return t.buf[:t.bufsize], t.l.RUnlock +} + func (t *Buf[T]) GetCopyBuf() (buf []T) { t.l.RLock() defer t.l.RUnlock() diff --git a/slice/Slice_test.go b/slice/Slice_test.go index 61db09f..2da7059 100644 --- a/slice/Slice_test.go +++ b/slice/Slice_test.go @@ -106,3 +106,34 @@ func Test3(t *testing.T) { t.Fatal() } } + +func Test4(t *testing.T) { + var c = New[byte]() + var w = make(chan struct{}) + + c.Append([]byte("12345")) + + buf, unlock := c.GetPureBufRLock() + + go func() { + w <- struct{}{} + c.Reset() + t.Log(c.Append([]byte("22345"))) + t.Log(c.buf) + w <- struct{}{} + }() + + <-w + + if !bytes.Equal(buf, []byte("12345")) { + t.Fatal() + } + + unlock() + + <-w + + if !bytes.Equal(buf, []byte("22345")) { + t.Fatal(buf) + } +}