Skip to content

Commit f65047b

Browse files
committed
Avoid buffering when reader supports ReadString
1 parent 1c950ee commit f65047b

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

Diff for: gitdiff/parser.go

+14-2
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ import (
1313
// the first file is returned as the second value. If an error occurs while
1414
// parsing, it returns all files parsed before the error.
1515
func Parse(r io.Reader) ([]*File, string, error) {
16-
p := &parser{r: bufio.NewReader(r)}
16+
p := newParser(r)
17+
1718
if err := p.Next(); err != nil {
1819
if err == io.EOF {
1920
return nil, "", nil
@@ -66,14 +67,25 @@ func Parse(r io.Reader) ([]*File, string, error) {
6667
// - if returning an object, advance to the first line after the object
6768
// - any exported parsing methods must initialize the parser by calling Next()
6869

70+
type stringReader interface {
71+
ReadString(delim byte) (string, error)
72+
}
73+
6974
type parser struct {
70-
r *bufio.Reader
75+
r stringReader
7176

7277
eof bool
7378
lineno int64
7479
lines [3]string
7580
}
7681

82+
func newParser(r io.Reader) *parser {
83+
if r, ok := r.(stringReader); ok {
84+
return &parser{r: r}
85+
}
86+
return &parser{r: bufio.NewReader(r)}
87+
}
88+
7789
// Next advances the parser by one line. It returns any error encountered while
7890
// reading the line, including io.EOF when the end of stream is reached.
7991
func (p *parser) Next() error {

Diff for: gitdiff/parser_test.go

+2-3
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
package gitdiff
22

33
import (
4-
"bufio"
4+
"bytes"
55
"encoding/binary"
66
"encoding/json"
77
"io"
88
"os"
99
"reflect"
10-
"strings"
1110
"testing"
1211
)
1312

@@ -490,7 +489,7 @@ Date: Tue Apr 2 22:55:40 2019 -0700
490489
}
491490

492491
func newTestParser(input string, init bool) *parser {
493-
p := &parser{r: bufio.NewReader(strings.NewReader(input))}
492+
p := newParser(bytes.NewBufferString(input))
494493
if init {
495494
_ = p.Next()
496495
}

0 commit comments

Comments
 (0)