-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresult.go
70 lines (60 loc) · 1.86 KB
/
result.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
package pars
// Void is a global Result for storing unused parsing results.
var Void = &Result{}
// Result is the output of a parser.
// One of three fields will be set:
// Token: a byte sequence matching for a primitive parser.
// Value: any value, useful for constructing complex objects.
// Children: results for individual child parsers.
// Use one of the Set* methods to mutually set fields.
type Result struct {
Token []byte
Value interface{}
Children []Result
}
// SetToken sets the token and clears other fields.
func (r *Result) SetToken(p []byte) {
r.Token = p
r.Value = nil
r.Children = nil
}
// SetValue sets the value and clears other fields.
func (r *Result) SetValue(v interface{}) {
r.Token = nil
r.Value = v
r.Children = nil
}
// SetChildren sets the children and clears other fields.
func (r *Result) SetChildren(c []Result) {
r.Token = nil
r.Value = nil
r.Children = c
}
// NewTokenResult creates a new result with the given token.
func NewTokenResult(p []byte) *Result { return &Result{Token: p} }
// NewValueResult creates a new result with the given value.
func NewValueResult(v interface{}) *Result { return &Result{Value: v} }
// NewChildrenResult creates a new result with the given children.
func NewChildrenResult(c []Result) *Result { return &Result{Children: c} }
// AsResult creates a new result based on the given argument type.
func AsResult(arg interface{}) *Result {
switch v := arg.(type) {
case byte:
return NewTokenResult([]byte{v})
case []byte:
return NewTokenResult(v)
case []Result:
return NewChildrenResult(v)
default:
return NewValueResult(v)
}
}
// AsResults transforms a given list of arguments into a result with Children
// with each argument as is result.
func AsResults(args ...interface{}) *Result {
r := make([]Result, len(args))
for i, arg := range args {
r[i] = *AsResult(arg)
}
return AsResult(r)
}