Skip to content

Commit

Permalink
feat: allow GetBytes to get all bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
ppzqh committed Feb 23, 2024
1 parent 7ba622b commit 0c594e3
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
9 changes: 9 additions & 0 deletions nocopy_linkbuffer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
25 changes: 25 additions & 0 deletions nocopy_linkbuffer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 0c594e3

Please sign in to comment.