-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbytereader.go
78 lines (62 loc) · 1.34 KB
/
bytereader.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
package ventil
import (
"bufio"
"io"
)
// reader wraps a bufio.Reader and counts bytes.
type reader struct {
r *bufio.Reader
lastByteWasNewline bool
readBytes int64
readLines int64
oldReadBytesInLine int64
readBytesInLine int64
}
func newByteReader(r io.Reader) *reader {
return &reader{
r: bufio.NewReader(r),
readLines: 1,
}
}
// ReadByte reads a single byte from the input.
func (r *reader) ReadByte() (byte, error) {
b, err := r.r.ReadByte()
if err != nil {
return b, err
}
r.readBytes++
if b == '\n' {
r.readLines++
r.oldReadBytesInLine = r.readBytesInLine
r.readBytesInLine = 0
r.lastByteWasNewline = true
}
return b, err
}
// UnreadByte returns a byte to the buffer.
func (r *reader) UnreadByte() error {
err := r.r.UnreadByte()
if err != nil {
return err
}
r.readBytes--
if r.lastByteWasNewline {
r.readLines--
r.readBytesInLine = r.oldReadBytesInLine
r.lastByteWasNewline = false
}
return err
}
func (r *reader) ReadLine() ([]byte, error) {
line, err := r.r.ReadBytes('\n')
r.readBytes += int64(len(line))
r.lastByteWasNewline = false
if len(line) > 0 && line[len(line)-1] == '\n' {
r.readLines++
r.oldReadBytesInLine = r.readBytesInLine
r.readBytesInLine = 0
r.lastByteWasNewline = true
line = line[:len(line)-1]
}
return line, err
}