-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathlinescanner.go
57 lines (48 loc) · 1.06 KB
/
linescanner.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
package ledger
import (
"bufio"
"io"
"os"
"unsafe"
)
type linescanner struct {
scanner *bufio.Scanner
unsafe bool
filename string
lineCount int
}
// NewLineScanner creates a wrapper around bufio.Scanner with pre-allocated
// buffer. Significantly reduces memory allocations and reduces runtime.
func newLineScanner(filename string, r io.Reader) *linescanner {
lp := &linescanner{}
lp.scanner = bufio.NewScanner(r)
if fs, fserr := os.Stat(filename); fserr == nil {
lp.scanner.Buffer(make([]byte, int(fs.Size())), int(fs.Size()))
lp.unsafe = true
}
lp.filename = filename
return lp
}
func (lp *linescanner) Scan() bool {
return lp.scanner.Scan()
}
func (lp *linescanner) Text() string {
var line string
if lp.unsafe {
if lbytes := lp.scanner.Bytes(); len(lbytes) > 0 {
line = unsafe.String(unsafe.SliceData(lbytes), len(lbytes))
} else {
line = ""
}
} else {
line = lp.scanner.Text()
}
lp.lineCount++
return line
}
func (lp *linescanner) LineNumber() int {
return lp.lineCount
}
func (lp *linescanner) Name() string {
return lp.filename
}