-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranslate.go
66 lines (58 loc) · 1.41 KB
/
translate.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
package djson
import "io"
// Translator a translator for translating djson to a json or other result format
// depending the Encoder,
type Translator interface {
Translate(r io.Reader, w io.Writer) (int, error)
}
// Encoder encode the Value that interpeter constructed from djson to a result format
type Encoder interface {
// Encode the Value to a result format
Encode(val Value, w io.Writer) (int, error)
}
type translator struct {
encoder Encoder
bufSize uint
ctx Context
}
// BufSize set a buffer size for translator
func BuffSize(bufSize uint) func(*translator) {
return func(opt *translator) {
opt.bufSize = bufSize
}
}
// Ctx set a Context for translator
func Ctx(ctx Context) func(*translator) {
return func(opt *translator) {
opt.ctx = ctx
}
}
// NewTranslator new a translator
func NewTranslator(e Encoder, opts ...func(*translator)) *translator {
t := &translator{encoder: e}
for _, opt := range opts {
opt(t)
}
return t
}
// Translate implements ths Translator
func (t *translator) Translate(r io.Reader, w io.Writer) (int, error) {
scanner := NewTokenScanner(NewLexer(r, t.bufSize))
if t.ctx == nil {
t.ctx = NewContext()
}
stmt := NewStmtExecutor(scanner, t.ctx)
var val Value
for {
if err := stmt.Execute(); err != nil {
return 0, err
}
if stmt.value.Type != ValueNull {
val = stmt.value
}
if scanner.EndAt() == TokenEOF {
break
}
}
return t.encoder.Encode(val, w)
}