-
Notifications
You must be signed in to change notification settings - Fork 16
/
numberedreader.go
52 lines (45 loc) · 935 Bytes
/
numberedreader.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
package main
import (
"bufio"
"io"
)
// 用于逐字符读取的辅助 Reader,提供行号支持
type NumberdReader struct {
reader *bufio.Reader
line int
lastRune rune
}
func NewNumberdReader(reader io.Reader) *NumberdReader {
return &NumberdReader{
reader: bufio.NewReader(reader),
line: 1,
lastRune: -1,
}
}
func (reader *NumberdReader) ReadRune() (r rune, size int, err error) {
r, size, err = reader.reader.ReadRune()
reader.lastRune = r
if r == '\n' {
reader.line++
}
return r, size, err
}
func (reader *NumberdReader) UnreadRune() error {
err := reader.reader.UnreadRune()
if err == nil {
if reader.lastRune == '\n' {
reader.line--
}
reader.lastRune = -1
}
return err
}
func (reader *NumberdReader) SkipLine() error {
reader.line++
reader.lastRune = -1
_, err := reader.reader.ReadBytes('\n')
return err
}
func (reader *NumberdReader) Line() int {
return reader.line
}