-
Notifications
You must be signed in to change notification settings - Fork 0
/
scanner.go
97 lines (79 loc) · 1.86 KB
/
scanner.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package ioline
import (
"bufio"
"io"
"strings"
)
// Scanner provides methods to read the entire file line-by-line, omitting newline character
type Scanner interface {
Next() bool
Get() string
Error() error
HasError() bool
}
type linesIterator struct {
rd io.Reader
reader *bufio.Reader
err error
line string
isFinished bool
}
// Next moves the iteration to the next line
func (iterator *linesIterator) Next() bool {
if iterator.ended() {
return false
}
iterator.line = ""
line, err := iterator.ReadEntireLine()
switch err {
case io.EOF:
iterator.isFinished = true
case nil:
iterator.line = line
default:
iterator.err = err
}
return iterator.needsIteration()
}
// Error gets the last error
func (iterator *linesIterator) Error() error {
return iterator.err
}
// HasError is true when an error is triggered
func (iterator *linesIterator) HasError() bool {
return iterator.err != nil
}
// Get the current line the iterator is positioned at
func (iterator *linesIterator) Get() string {
return iterator.line
}
// NewScanner starts a new `Scanner` for the provided `io.Reader`
func NewScanner(rd io.Reader) Scanner {
iterator := &linesIterator{}
iterator.rd = rd
iterator.reader = bufio.NewReader(iterator.rd)
return iterator
}
func (iterator *linesIterator) ReadEntireLine() (string, error) {
reader := iterator.reader
var entireLine strings.Builder
for {
line, isPrefix, err := reader.ReadLine()
if err != nil && err != io.EOF {
return "", err
}
_, bufErr := entireLine.Write(line)
if bufErr != nil {
return "", bufErr
}
if isPrefix == false && (err == nil || err == io.EOF) {
return entireLine.String(), err
}
}
}
func (iterator *linesIterator) ended() bool {
return iterator.isFinished || iterator.err != nil
}
func (iterator *linesIterator) needsIteration() bool {
return !iterator.ended()
}