Skip to content

Commit bb9c3f7

Browse files
authored
feat: allow GetBytes to get all bytes (#313)
1 parent 18c2c1f commit bb9c3f7

File tree

3 files changed

+43
-0
lines changed

3 files changed

+43
-0
lines changed

nocopy_linkbuffer.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -557,8 +557,17 @@ func (b *LinkBuffer) Bytes() []byte {
557557
}
558558

559559
// GetBytes will read and fill the slice p as much as possible.
560+
// If p is not passed, return all readable bytes.
560561
func (b *LinkBuffer) GetBytes(p [][]byte) (vs [][]byte) {
561562
node, flush := b.read, b.flush
563+
if len(p) == 0 {
564+
n := 0
565+
for ; node != flush; node = node.next {
566+
n++
567+
}
568+
node = b.read
569+
p = make([][]byte, n)
570+
}
562571
var i int
563572
for i = 0; node != flush && i < len(p); node = node.next {
564573
if node.Len() > 0 {

nocopy_linkbuffer_race.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -599,10 +599,19 @@ func (b *LinkBuffer) Bytes() []byte {
599599
}
600600

601601
// GetBytes will read and fill the slice p as much as possible.
602+
// If p is not passed, return all readable bytes.
602603
func (b *LinkBuffer) GetBytes(p [][]byte) (vs [][]byte) {
603604
b.Lock()
604605
defer b.Unlock()
605606
node, flush := b.read, b.flush
607+
if len(p) == 0 {
608+
n := 0
609+
for ; node != flush; node = node.next {
610+
n++
611+
}
612+
node = b.read
613+
p = make([][]byte, n)
614+
}
606615
var i int
607616
for i = 0; node != flush && i < len(p); node = node.next {
608617
if node.Len() > 0 {

nocopy_linkbuffer_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,31 @@ func TestLinkBuffer(t *testing.T) {
8484
Equal(t, buf.Len(), 100)
8585
}
8686

87+
func TestGetBytes(t *testing.T) {
88+
buf := NewLinkBuffer()
89+
var (
90+
num = 10
91+
b = 1
92+
expectedLen = 0
93+
)
94+
for i := 0; i < num; i++ {
95+
expectedLen += b
96+
n, err := buf.WriteBinary(make([]byte, b))
97+
MustNil(t, err)
98+
Equal(t, n, b)
99+
b *= 10
100+
}
101+
buf.Flush()
102+
Equal(t, int(buf.length), expectedLen)
103+
bs := buf.GetBytes(nil)
104+
actualLen := 0
105+
for i := 0; i < len(bs); i++ {
106+
actualLen += len(bs[i])
107+
}
108+
Equal(t, actualLen, expectedLen)
109+
110+
}
111+
87112
// TestLinkBufferWithZero test more case with n is invalid.
88113
func TestLinkBufferWithInvalid(t *testing.T) {
89114
// clean & new

0 commit comments

Comments
 (0)