From 0c594e3c81632323f71a51d7f3a1411a9ecb0020 Mon Sep 17 00:00:00 2001 From: "qiheng.zhou" Date: Fri, 23 Feb 2024 18:22:27 +0800 Subject: [PATCH] feat: allow GetBytes to get all bytes --- nocopy_linkbuffer.go | 9 +++++++++ nocopy_linkbuffer_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/nocopy_linkbuffer.go b/nocopy_linkbuffer.go index 555ba5ce..c888c3c8 100644 --- a/nocopy_linkbuffer.go +++ b/nocopy_linkbuffer.go @@ -557,8 +557,17 @@ func (b *LinkBuffer) Bytes() []byte { } // GetBytes will read and fill the slice p as much as possible. +// If p is not passed, return all readable bytes. func (b *LinkBuffer) GetBytes(p [][]byte) (vs [][]byte) { node, flush := b.read, b.flush + if len(p) == 0 { + n := 0 + for ; node != flush; node = node.next { + n++ + } + node = b.read + p = make([][]byte, n) + } var i int for i = 0; node != flush && i < len(p); node = node.next { if node.Len() > 0 { diff --git a/nocopy_linkbuffer_test.go b/nocopy_linkbuffer_test.go index c3f9b9d8..a376b7bf 100644 --- a/nocopy_linkbuffer_test.go +++ b/nocopy_linkbuffer_test.go @@ -84,6 +84,31 @@ func TestLinkBuffer(t *testing.T) { Equal(t, buf.Len(), 100) } +func TestGetBytes(t *testing.T) { + buf := NewLinkBuffer() + var ( + num = 10 + b = 1 + expectedLen = 0 + ) + for i := 0; i < num; i++ { + expectedLen += b + n, err := buf.WriteBinary(make([]byte, b)) + MustNil(t, err) + Equal(t, n, b) + b *= 10 + } + buf.Flush() + Equal(t, int(buf.length), expectedLen) + bs := buf.GetBytes(nil) + actualLen := 0 + for i := 0; i < len(bs); i++ { + actualLen += len(bs[i]) + } + Equal(t, actualLen, expectedLen) + +} + // TestLinkBufferWithZero test more case with n is invalid. func TestLinkBufferWithInvalid(t *testing.T) { // clean & new