-
Notifications
You must be signed in to change notification settings - Fork 0
/
type.go
48 lines (42 loc) · 880 Bytes
/
type.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
package syrup
import (
"reflect"
"sync"
)
type structMetadata struct {
fields []field
fieldNamesIndex map[string]int
}
type field struct {
name string
fieldIdx int
t reflect.Type
}
func buildMetadata(t reflect.Type) (m structMetadata) {
m.fieldNamesIndex = make(map[string]int, 0)
for i := 0; i < t.NumField(); i++ {
f := t.Field(i)
public := f.PkgPath == ""
if !public {
continue
}
m.fieldNamesIndex[f.Name] = len(m.fields)
m.fields = append(m.fields, field{
name: f.Name,
fieldIdx: i,
t: f.Type,
})
}
return m
}
// map[reflect.Type]structMetadata
var metadataCache sync.Map
func buildCachedMetadata(t reflect.Type) (m structMetadata) {
if i, ok := metadataCache.Load(t); ok {
m = i.(structMetadata)
return
}
i, _ := metadataCache.LoadOrStore(t, buildMetadata(t))
m = i.(structMetadata)
return
}