Skip to content

Commit

Permalink
Boundary reader - long lines processing fixed (#200)
Browse files Browse the repository at this point in the history
* Boundary reader - long lines processing fixed
* boundaryReader.Next - buffer allocation only for lines longer than buffer

Co-authored-by: Pavel Bazika <pavel.bazika@icewarp.com>
  • Loading branch information
pavelbazika and Pavel Bazika committed Jul 5, 2021
1 parent 8fd0e3c commit 6817b15
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 3 deletions.
21 changes: 18 additions & 3 deletions boundary.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,10 +181,25 @@ func (b *boundaryReader) Next() (bool, error) {
_, _ = io.Copy(ioutil.Discard, b)
}
for {
line, err := b.r.ReadSlice('\n')
if err != nil && err != io.EOF {
return false, errors.WithStack(err)
var line []byte = nil
var err error
for {
// Read whole line, handle extra long lines in cycle
var segment []byte
segment, err = b.r.ReadSlice('\n')
if line == nil {
line = segment
} else {
line = append(line, segment...)
}

if err == nil || err == io.EOF {
break
} else if err != bufio.ErrBufferFull || len(segment) == 0 {
return false, errors.WithStack(err)
}
}

if len(line) > 0 && (line[0] == '\r' || line[0] == '\n') {
// Blank line
continue
Expand Down
18 changes: 18 additions & 0 deletions boundary_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -477,6 +477,24 @@ func TestBoundaryReaderReadErrors(t *testing.T) {
}
}

// TestBoundaryReaderLongLine checks that boundaryReader can read lines longer than the `peekBufferSize`.
func TestBoundaryReaderLongLine(t *testing.T) {
data := bytes.Repeat([]byte{1}, 7*1024)
data[6*1024] = '\n'

br := &boundaryReader{
r: bufio.NewReader(bytes.NewReader(data)),
}

next, err := br.Next()
if next {
t.Fatal("Next() should have returned false, failed")
}
if err != nil {
t.Fatal("Next() should have returned no error, failed")
}
}

// TestReadLenNotCap checks that the `boundaryReader` `io.Reader` implementation fills the provided
// slice based on its length (as per the `io.Reader` documentation), and not its capacity.
func TestReadLenNotCap(t *testing.T) {
Expand Down

0 comments on commit 6817b15

Please sign in to comment.