-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenizer.go
51 lines (45 loc) · 876 Bytes
/
tokenizer.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
package main
import (
"bufio"
"io"
"unicode/utf8"
)
const EOF rune = -1
// tokenizer is a buffered IO reader that implements peek functionality.
type tokenizer struct {
tok rune
tokpos int
*bufio.Reader
}
// newTokenizer creates a new Tokenizer.
func newTokenizer(r io.Reader) *tokenizer {
return &tokenizer{
Reader: bufio.NewReader(r),
}
}
// consume consumes one rune from the input and returns it.
func (t *tokenizer) consume() rune {
var err error
t.tok, _, err = t.ReadRune()
if err != nil {
t.tok = EOF
return t.tok
}
t.tokpos++
return t.tok
}
// peek peeks at the next token rune without consuming it.
func (t *tokenizer) peek() rune {
if t.Buffered() < 1 || t.tok == EOF {
return EOF
}
for n := utf8.UTFMax; n > 0; n-- {
b, err := t.Peek(n)
if err != nil {
continue
}
r, _ := utf8.DecodeRune(b)
return r
}
return EOF
}