-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgxjpath.go
294 lines (265 loc) · 6.31 KB
/
gxjpath.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package gxjpath
import (
"errors"
"fmt"
"strconv"
"strings"
"sync"
)
type GXJValueType int8
type GXJContainerType int8
var ErrNotFound = errors.New("Path not found")
var ErrWrongPath = errors.New("Wrong path")
var ErrInvalidIndex = errors.New("Invalid array index")
var ErrUnexpectedType = errors.New("Invalid array index")
var ErrTruncateCast = errors.New("Type has been truncated")
const (
GXJMapContainer GXJContainerType = iota
GXJSliceContainer
)
type GXJPathItem struct {
key string
index int
containerType GXJContainerType
}
func (s *GXJPathItem) String() string {
var t string
var c string
switch s.containerType {
case GXJMapContainer:
c = "map[string]" + t
case GXJSliceContainer:
c = "[]" + t
}
return fmt.Sprintf("Key: %s, Index: %d, Type: %s, container: %s", s.key, s.index, t, c)
}
type GXJPath []GXJPathItem
var cacheLock sync.Mutex
var compiledCache map[string]GXJPath = make(map[string]GXJPath)
func (x GXJPath) String() string {
buf := make([]string, 0)
for _, v := range x {
buf = append(buf, v.String())
}
return strings.Join(buf, "\n")
}
func getIndex(path string) (int, error) {
if len(path) == 0 {
return 0, ErrInvalidIndex
}
switch path {
case "first":
return 0, nil
case "last":
return -1, nil
default:
idx, err := strconv.Atoi(path)
if err != nil {
return idx, ErrInvalidIndex
}
return idx, nil
}
}
// cutSegment cuts a path segment taking into account escaped "." characters.
func cutSegment(path string) (string, string) {
normChar := true
var idx int
for idx = 0; idx < len(path); idx++ {
if normChar {
if path[idx] == '\\' {
normChar = false
}
if path[idx] == '.' {
leftover := path[idx+1:]
if len(leftover) == 0 {
// Will cause an error later. Used on purpose.
leftover = "."
}
return path[:idx], leftover
}
} else {
normChar = true
}
}
return path, ""
}
// unescape removed escape characters.
func unescape(segment string) string {
buf := make([]byte, 0, len(segment))
escChar := false
for idx := 0; idx < len(segment); idx++ {
b := segment[idx]
if escChar {
escChar = false
buf = append(buf, b)
continue
}
if segment[idx] == '\\' {
escChar = true
continue
}
buf = append(buf, b)
}
if len(segment) == len(buf) {
return segment
}
return string(buf)
}
// compileSegment compiles a single segment.
func compileSegment(segment string) (GXJPathItem, error) {
var idx int
var err error
var containerType GXJContainerType = GXJMapContainer
if len(segment) == 0 {
return GXJPathItem{}, ErrWrongPath
}
if segment[0] == '@' {
containerType = GXJSliceContainer
segment = segment[1:]
idx, err = getIndex(segment)
if err != nil {
return GXJPathItem{}, err
}
}
return GXJPathItem{
index: idx,
key: unescape(segment),
containerType: containerType,
}, nil
}
// CompileXJPath creates a slice of parsed path segments
func CompilePath(path string) (GXJPath, error) {
output := make(GXJPath, 0, 4)
var segment string
for len(path) > 0 {
segment, path = cutSegment(path)
if len(segment) == 0 {
return nil, ErrWrongPath
}
compiled, err := compileSegment(segment)
if err != nil {
return nil, err
}
output = append(output, compiled)
}
return output, nil
}
func lookupSegment(pathItem *GXJPathItem, data interface{}) (interface{}, error) {
if pathItem.containerType == GXJSliceContainer {
v, ok := data.([]interface{})
if !ok {
return nil, ErrNotFound
}
idx := pathItem.index
if idx < 0 {
idx = len(v) + idx
}
if idx < 0 && idx >= len(v) {
return nil, ErrNotFound
}
return v[idx], nil
}
if pathItem.containerType == GXJMapContainer {
v, ok := data.(map[string]interface{})
if !ok {
return nil, ErrNotFound
}
mapValue, ok := v[pathItem.key]
if !ok {
return nil, ErrNotFound
}
return mapValue, nil
}
panic("Unknown container type!")
return nil, nil
}
// LookupCompiledPath looks up a value using pre-compiled path that works much faster.
func LookupCompiledPath(path GXJPath, data interface{}) (interface{}, error) {
var err error
for _, x := range path {
data, err = lookupSegment(&x, data)
if err != nil {
return nil, err
}
}
return data, err
}
// LookupRawPath looks up a value using raw string path.
// Before actual lookup value is compiled, so if path used frequently,
// it would be a good idea to compiled it first.
func LookupRawPath(path string, data interface{}) (interface{}, error) {
cp, err := CompilePath(path)
if err != nil {
return nil, err
}
return LookupCompiledPath(cp, data)
}
// LookUpInt64Value looks up a value of the int64 type.
func LookUpInt64Value(path string, data interface{}) (int64, error) {
v, err := CachedLookup(path, data)
if err != nil {
return 0, err
}
switch vv := v.(type) {
case int:
return int64(vv), nil
case int64:
return vv, nil
case float64:
return int64(vv), ErrTruncateCast
case float32:
return int64(vv), nil
}
return 0, ErrUnexpectedType
}
// LookUpStringValue looks up a value of the string type.
func LookUpStringValue(path string, data interface{}) (string, error) {
v, err := CachedLookup(path, data)
if err != nil {
return "", err
}
if s, ok := v.(string); ok {
return s, nil
}
return "", ErrUnexpectedType
}
// LookUpBoolValue looks up a value of the boolean type.
func LookUpBoolValue(path string, data interface{}) (bool, error) {
v, err := CachedLookup(path, data)
if err != nil {
return false, err
}
if b, ok := v.(bool); ok {
return b, nil
}
return false, ErrUnexpectedType
}
// LookUpMapToInterface looks up a value of the map[string]interface{} type.
func LookUpMapToInterface(path string, data interface{}) (map[string]interface{}, error) {
v, err := CachedLookup(path, data)
if err != nil {
return nil, err
}
if m, ok := v.(map[string]interface{}); ok {
return m, nil
}
return nil, ErrUnexpectedType
}
// CachedLookup compiles and caches compiled path in the module level dictionary.
// Lookup result is equal to the previous functions.
func CachedLookup(path string, data interface{}) (interface{}, error) {
cacheLock.Lock()
compiled, ok := compiledCache[path]
cacheLock.Unlock()
if !ok {
cacheLock.Lock()
defer cacheLock.Unlock()
c, err := CompilePath(path)
if err != nil {
return nil, err
}
compiledCache[path] = c
compiled = c
}
return LookupCompiledPath(compiled, data)
}