-
Notifications
You must be signed in to change notification settings - Fork 16
/
slice.go
71 lines (62 loc) · 1.57 KB
/
slice.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
71
package dynaml
import (
"fmt"
//"github.com/mandelsoft/spiff/debug"
"github.com/mandelsoft/spiff/yaml"
)
type SliceExpr struct {
Expression Expression
Range RangeExpr
}
func (e SliceExpr) Evaluate(binding Binding, locally bool) (interface{}, EvaluationInfo, bool) {
root, info, ok := e.Expression.Evaluate(binding, locally)
if !ok {
return nil, info, false
}
if !isLocallyResolvedValue(root, binding) {
return e, info, true
}
if !locally && !isResolvedValue(root, binding) {
return e, info, true
}
array, ok := root.([]yaml.Node)
if !ok {
return info.Error("slice requires array expression")
}
start, end, infoe, ok, resolved := e.Range.getRange(binding, len(array))
info.Join(infoe)
if !ok {
return nil, info, ok
}
if !resolved {
return e, info, ok
}
if start > end {
return []yaml.Node{}, info, ok
}
if start < 0 {
if end >= 0 {
return info.Error("mixed negative and non-negative range not possible for slice")
}
if start < -int64(len(array)) {
return info.Error("slice out of range (%d < -length %d)", start, len(array))
}
result := make([]yaml.Node, end-start+1)
for i := start; i <= end; i++ {
result[i-start] = array[i+int64(len(array))]
}
return result, info, true
} else {
if end >= int64(len(array)) {
return info.Error("slice out of range (%d >= length %d)", end, len(array))
}
result := make([]yaml.Node, end-start+1)
for i := start; i <= end; i++ {
result[i-start] = array[i]
}
return result, info, true
}
}
func (e SliceExpr) String() string {
return fmt.Sprintf("%s.[%s]", e.Expression, e.Range)
}