Skip to content

Commit

Permalink
feat: allow GetBytes to get all bytes (#313)
Browse files Browse the repository at this point in the history
  • Loading branch information
ppzqh authored Mar 11, 2024
1 parent 18c2c1f commit bb9c3f7
Show file tree
Hide file tree
Showing 3 changed files with 43 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
9 changes: 9 additions & 0 deletions nocopy_linkbuffer_race.go
Original file line number Diff line number Diff line change
Expand Up @@ -599,10 +599,19 @@ 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) {
b.Lock()
defer b.Unlock()
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 bb9c3f7

Please sign in to comment.