forked from mitchellh/mapstructure
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfield_path.go
More file actions
122 lines (95 loc) · 2.27 KB
/
field_path.go
File metadata and controls
122 lines (95 loc) · 2.27 KB
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
package mapstructure
import (
"strconv"
)
//PathPart is interface for different kinds of FieldPath elements.
type PathPart interface {
getDelimiter() string
String() string
}
//InStructPathPart is FieldPath element that represents field name in structure.
type InStructPathPart struct {
val string
}
func (p InStructPathPart) getDelimiter() string {
return "."
}
func (p InStructPathPart) String() string {
return p.val
}
func (p InStructPathPart) Value() string {
return p.val
}
//InMapPathPart is FieldPath element that represents key in map.
type InMapPathPart struct {
val string
}
func (p InMapPathPart) getDelimiter() string {
return ""
}
func (p InMapPathPart) String() string {
return "[" + p.val + "]"
}
func (p InMapPathPart) Value() string {
return p.val
}
//InSlicePathPart is FieldPath element that represents index in slice or array.
type InSlicePathPart struct {
val int
}
func (p InSlicePathPart) getDelimiter() string {
return ""
}
func (p InSlicePathPart) String() string {
return "[" + strconv.Itoa(p.val) + "]"
}
func (p InSlicePathPart) Value() int {
return p.val
}
//FieldPath represents path to a field in nested structure.
type FieldPath struct {
parts []PathPart
}
func (f FieldPath) addStruct(part string) FieldPath {
return FieldPath{
parts: appendPart(f.parts, InStructPathPart{val: part}),
}
}
func (f FieldPath) addMap(part string) FieldPath {
return FieldPath{
parts: appendPart(f.parts, InMapPathPart{val: part}),
}
}
func (f FieldPath) addSlice(part int) FieldPath {
return FieldPath{
parts: appendPart(f.parts, InSlicePathPart{val: part}),
}
}
func (f FieldPath) notEmpty() bool {
return len(f.parts) > 0
}
func newFieldPath() FieldPath {
return FieldPath{
parts: make([]PathPart, 0),
}
}
func (f FieldPath) Parts() []PathPart {
return f.parts
}
func (f FieldPath) String() string {
result := ""
for i, part := range f.parts {
delimiter := ""
if i > 0 { //there is no delimiter before first element
delimiter = part.getDelimiter()
}
result += delimiter + part.String()
}
return result
}
//appendPart appends PathPart to a PathPart slice with guarantee of slice immutability.
func appendPart(parts []PathPart, part PathPart) []PathPart {
p := make([]PathPart, len(parts))
copy(p, parts)
return append(p, part)
}