-
-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
textlinescanner.go
47 lines (41 loc) · 967 Bytes
/
textlinescanner.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package iox
import (
"bufio"
"errors"
"io"
"strings"
)
// A TextLineScanner is a scanner that can scan lines from the given reader.
type TextLineScanner struct {
reader *bufio.Reader
hasNext bool
line string
err error
}
// NewTextLineScanner returns a TextLineScanner with the given reader.
func NewTextLineScanner(reader io.Reader) *TextLineScanner {
return &TextLineScanner{
reader: bufio.NewReader(reader),
hasNext: true,
}
}
// Scan checks if scanner has more lines to read.
func (scanner *TextLineScanner) Scan() bool {
if !scanner.hasNext {
return false
}
line, err := scanner.reader.ReadString('\n')
scanner.line = strings.TrimRight(line, "\n")
if errors.Is(err, io.EOF) {
scanner.hasNext = false
return true
} else if err != nil {
scanner.err = err
return false
}
return true
}
// Line returns the next available line.
func (scanner *TextLineScanner) Line() (string, error) {
return scanner.line, scanner.err
}