-
Notifications
You must be signed in to change notification settings - Fork 20
/
byte_stream.go
55 lines (49 loc) · 884 Bytes
/
byte_stream.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
package main
import (
"errors"
"github.com/DQNEO/minigo/stdlib/io/ioutil"
)
type ByteStream struct {
filename string
source []byte
nextIndex int
line int
column int
}
func NewByteStreamFromFile(path string) *ByteStream {
s := readFile(path)
return &ByteStream{
filename: path,
source: s,
nextIndex: 0,
line: 1,
column: 0,
}
}
func readFile(filename string) []byte {
bytes, err := ioutil.ReadFile(filename)
if err != nil {
panic("Unable to read file:" + filename)
}
return bytes
}
func (bs *ByteStream) get() (byte, error) {
if bs.nextIndex >= len(bs.source) {
return 0, errors.New("EOF")
}
r := bs.source[bs.nextIndex]
if r == '\n' {
bs.line++
bs.column = 1
}
bs.nextIndex++
bs.column++
return r, nil
}
func (bs *ByteStream) unget() {
bs.nextIndex--
r := bs.source[bs.nextIndex]
if r == '\n' {
bs.line--
}
}