-
Notifications
You must be signed in to change notification settings - Fork 2
/
structcache.go
104 lines (86 loc) · 1.83 KB
/
structcache.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
package bson
import (
"errors"
"reflect"
"sort"
"strings"
"sync"
)
var structInfoCache sync.Map // map[reflect.Type]*structInfo
type structInfo struct {
Fields []fieldInfo
}
type fieldInfo struct {
Key string
Num int
OmitEmpty bool
}
func (si *structInfo) asDoc(val reflect.Value) docRefl {
doc := make(docRefl, 0, len(si.Fields))
for _, info := range si.Fields {
value := val.Field(info.Num)
if info.OmitEmpty && isZero(value) {
continue
}
doc = append(doc, pairRefl{
Key: info.Key,
Val: value.Interface(),
})
}
sort.Sort(doc)
return doc
}
func getStruct(val reflect.Value) *structInfo {
typ := val.Type()
if info, ok := structInfoCache.Load(typ); ok {
return info.(*structInfo)
}
info, _ := getStructInfo(typ)
structInfoCache.Store(typ, info)
return info
}
func getStructInfo(typ reflect.Type) (*structInfo, error) {
n := typ.NumField()
fields := make([]fieldInfo, 0, n)
fieldsMap := make(map[string]fieldInfo, n)
for i := 0; i < n; i++ {
field := typ.Field(i)
if field.PkgPath != "" && !field.Anonymous {
continue
}
info := fieldInfo{Num: i}
tag := field.Tag.Get("bson")
if tag == "" && strings.Index(string(field.Tag), ":") == -1 {
tag = string(field.Tag)
}
if tag == "-" {
continue
}
tagsParts := strings.Split(tag, ",")
if len(tagsParts) > 1 {
for _, flag := range tagsParts[1:] {
switch flag {
case "omitempty":
info.OmitEmpty = true
default:
panic("Unsupported flag: " + flag)
}
}
tag = tagsParts[0]
}
if tag != "" {
info.Key = tag
} else {
info.Key = strings.ToLower(field.Name)
}
if _, ok := fieldsMap[info.Key]; ok {
return nil, errors.New("Duplicated key: " + info.Key)
}
fields = append(fields, info)
fieldsMap[info.Key] = info
}
info := &structInfo{
Fields: fields,
}
return info, nil
}