]> 127.0.0.1 Git - part/.git/commitdiff
slices.Buf[T any].GetPureBufRLock v0.28.20240316094927
authorqydysky <qydysky@foxmail.com>
Sat, 16 Mar 2024 09:43:55 +0000 (17:43 +0800)
committerqydysky <qydysky@foxmail.com>
Sat, 16 Mar 2024 09:43:55 +0000 (17:43 +0800)
slice/Slice.go
slice/Slice_test.go

index 046b726a382530a000dd12a470a872c70cb7c2b6..8f028b007bf33b0cc3ed1673ae883137cfcb8715 100644 (file)
@@ -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()
index 61db09f5a67aa4edffa2d4d978fdf92131cbc711..2da7059a98b757a2d328f34a6a455987cc171fed 100644 (file)
@@ -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)
+       }
+}