-
Notifications
You must be signed in to change notification settings - Fork 0
/
gmap.go
135 lines (119 loc) · 2.43 KB
/
gmap.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
package gmap
import (
"strconv"
"strings"
)
// Get get value for the specified path
func Get(v interface{}, path string) Value {
return get(v, path, false)
}
// Get get value for the specified path, but case-insensitive
func GetIgnoreCase(v interface{}, path string) Value {
return get(v, path, true)
}
type Map map[string]interface{}
// Get get value for the specified path
func (m Map) Get(path string) Value {
return get(m, path, false)
}
// Get get value for the specified path, but case-insensitive
func (m Map) GetIgnoreCase(path string) Value {
return get(m, path, true)
}
type Slice []interface{}
// Get get value for the specified path
func (s Slice) Get(path string) Value {
return get(s, path, false)
}
// Get get value for the specified path, but case-insensitive
func (s Slice) GetIgnoreCase(path string) Value {
return get(s, path, true)
}
type nextResult struct {
Index string
Path string
More bool
}
func nextIndex(path string) (r nextResult) {
for i := 0; i < len(path); i++ {
if path[i] == '\\' {
epart := []byte(path[:i])
i++
if i < len(path) {
epart = append(epart, path[i])
i++
for ; i < len(path); i++ {
if path[i] == '\\' {
i++
if i < len(path) {
epart = append(epart, path[i])
}
continue
} else if path[i] == '.' {
r.Index = string(epart)
r.Path = path[i+1:]
r.More = true
return
}
epart = append(epart, path[i])
}
}
r.Index = string(epart)
return
}
if path[i] == '.' {
r.Index = path[:i]
r.Path = path[i+1:]
r.More = true
return
}
}
r.Index = path
return
}
func get(v interface{}, path string, ignoreCase bool) Value {
next := nextResult{Path: path}
for {
next = nextIndex(next.Path)
var m map[string]interface{}
var s []interface{}
var smode bool
switch t := v.(type) {
case Map:
m = t
case map[string]interface{}:
m = t
case Slice:
s = t
smode = true
case []interface{}:
s = t
smode = true
default:
return Value{}
}
var fnd bool
if smode {
if idx, err := strconv.Atoi(next.Index); err != nil || idx < 0 || idx >= len(s) {
return Value{}
} else {
v = s[idx]
fnd = true
}
} else {
v, fnd = m[next.Index]
if !fnd && ignoreCase {
for k, vv := range m {
if strings.EqualFold(k, next.Index) {
v = vv
fnd = true
break
}
}
}
}
if !next.More {
return Value{Has: fnd, Raw: v}
}
}
}