forked from binhonglee/kdlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreader.go
137 lines (109 loc) · 1.99 KB
/
reader.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package kdl
import (
"bytes"
"io"
)
type innerReader interface {
io.ByteScanner
io.RuneScanner
Discard(n int) (discarded int, err error)
Peek(n int) (view []byte, err error)
}
type reader struct {
reader innerReader
line int
pos int
depth int
}
func wrapReader(r innerReader) reader {
return reader{reader: r, line: 1, pos: 0}
}
func (r *reader) readRune() (ch rune, err error) {
ch, _, err = r.reader.ReadRune()
if err != nil {
return
}
if isNewLine(ch) {
if ch == '\r' {
next, _, errNext := r.reader.ReadRune()
if errNext != nil {
return
}
if next == '\n' {
_ = r.reader.UnreadRune()
return
}
}
r.line++
r.pos = 0
return
}
r.pos++
return
}
func (r *reader) discardRunes(count int) {
for i := 0; i < count; i++ {
_, _ = r.readRune()
}
}
func (r *reader) readByte() (b byte, err error) {
b, err = r.reader.ReadByte()
if b == '\n' || b == '\r' {
r.line++
r.pos = 0
} else {
r.pos++
}
return
}
func (r *reader) peekByte() (b byte, err error) {
b, err = r.reader.ReadByte()
if err != nil {
return
}
err = r.reader.UnreadByte()
return
}
func (r *reader) discardByte() {
_, _ = r.readByte()
}
func (r *reader) discardBytes(count int) {
wasCR := false
bytes, _ := r.peekBytes(count)
for _, b := range bytes {
if b == '\n' && !wasCR {
r.line++
r.pos = 0
wasCR = false
continue
}
if b == '\r' {
wasCR = true
r.line++
r.pos = 0
continue
}
wasCR = false
r.pos++
}
r.reader.Discard(count)
}
// peekBytes tries to return next N bytes without advancing the reader.
func (r *reader) peekBytes(count int) ([]byte, error) {
return r.reader.Peek(count)
}
func (r *reader) peekRune() (rune, error) {
ch, _, err := r.reader.ReadRune()
if err != nil {
return ch, err
}
err = r.reader.UnreadRune()
return ch, err
}
func (r *reader) isNext(expected []byte) (bool, error) {
next, err := r.peekBytes(len(expected))
if err != nil {
return false, err
}
return bytes.Equal(next, expected), nil
}