From f1b82e5bfd98aa6d8e6229363f0ca0ecbcabd426 Mon Sep 17 00:00:00 2001 From: qydysky Date: Sat, 16 Mar 2024 17:43:55 +0800 Subject: [PATCH] slices.Buf[T any].GetPureBufRLock --- slice/Slice.go | 12 ++++++++++++ slice/Slice_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) 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) + } +} -- 2.39.2