-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstruct.go
More file actions
118 lines (94 loc) · 1.99 KB
/
struct.go
File metadata and controls
118 lines (94 loc) · 1.99 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
package jsonpointer
import (
"reflect"
"strings"
"sync"
"unicode"
)
func structField(field string, value *reflect.Value) bool {
fields := getStructFields(value.Type())
i, ok := fields[field]
if !ok {
return false
}
*value = value.FieldByIndex(i)
return true
}
type structFields map[string][]int
var structFieldsCache sync.Map
func getStructFields(t reflect.Type) structFields {
if fields, ok := structFieldsCache.Load(t); ok {
return fields.(structFields)
}
type field struct {
t reflect.Type
i []int
}
fields := make(structFields, t.NumField())
current := []field{}
next := []field{{
t: t,
}}
visited := make(map[reflect.Type]struct{})
for len(next) > 0 {
current, next = next, current[:0]
for _, f := range current {
if _, ok := visited[f.t]; ok {
continue
}
visited[f.t] = struct{}{}
n := f.t.NumField()
for i := range n {
sf := f.t.Field(i)
if sf.Anonymous {
ft := sf.Type
if ft.Kind() == reflect.Pointer {
ft = ft.Elem()
}
if !sf.IsExported() && ft.Kind() != reflect.Struct {
continue
}
} else if !sf.IsExported() {
continue
}
name := sf.Name
tag := sf.Tag.Get("json")
if tag != "" {
if tag == "-" {
continue
}
tag, _, _ = strings.Cut(tag, ",")
for _, r := range tag {
if strings.ContainsRune("!#$%&()*+-./:;<=>?@[]^_{|}~ ", r) {
continue
}
if !unicode.IsLetter(r) && !unicode.IsDigit(r) {
tag = ""
break
}
}
if tag != "" {
name = tag
}
}
index := make([]int, len(f.i)+1)
copy(index, f.i)
index[len(f.i)] = i
ft := sf.Type
if ft.Name() == "" && ft.Kind() == reflect.Pointer {
ft = ft.Elem()
}
if !sf.Anonymous || ft.Kind() != reflect.Struct {
fields[name] = index
continue
}
next = append(next, field{
t: ft,
i: index,
})
}
}
}
fieldsVal, _ := structFieldsCache.LoadOrStore(t, fields)
return fieldsVal.(structFields)
}