forked from blockwatch-cc/tzstats-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
typeinfo.go
239 lines (213 loc) · 5.56 KB
/
typeinfo.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// Copyright (c) 2018-2022 Blockwatch Data Inc.
// Author: alex@blockwatch.cc
package tzstats
import (
"encoding"
"fmt"
"reflect"
"strings"
"sync"
)
const (
tagName = "json"
)
// TypeInfo holds details for the representation of a type.
type TypeInfo struct {
Name string
Fields []FieldInfo
IsGoType bool
TagName string
}
// FieldInfo holds details for the representation of a single field.
type FieldInfo struct {
Idx []int
Name string
Alias string
Flags []string
TypeName string
}
func (f FieldInfo) ContainsFlag(flag string) bool {
for _, v := range f.Flags {
if v == flag {
return true
}
}
return false
}
func (t TypeInfo) FilteredAliases(f string) []string {
s := make([]string, 0, len(t.Fields))
for _, v := range t.Fields {
if v.ContainsFlag(f) {
continue
}
s = append(s, v.Alias)
}
return s
}
func (t TypeInfo) Aliases() []string {
s := make([]string, len(t.Fields))
for i, v := range t.Fields {
s[i] = v.Alias
}
return s
}
func (t TypeInfo) FieldNames() []string {
s := make([]string, len(t.Fields))
for i, v := range t.Fields {
s[i] = v.Name
}
return s
}
func (f FieldInfo) String() string {
return fmt.Sprintf("FieldInfo: %s typ=%s idx=%d", f.Name, f.TypeName, f.Idx)
}
var tinfoMap = make(map[reflect.Type]*TypeInfo)
var tinfoLock sync.RWMutex
var (
textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem()
textMarshalerType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem()
binaryUnmarshalerType = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem()
binaryMarshalerType = reflect.TypeOf((*encoding.BinaryMarshaler)(nil)).Elem()
byteSliceType = reflect.TypeOf([]byte(nil))
)
// GetTypeInfo returns the typeInfo structure with details necessary
// for marshaling and unmarshaling typ.
func GetTypeInfo(v interface{}, tagname string) (*TypeInfo, error) {
// Load value from interface
val := reflect.Indirect(reflect.ValueOf(v))
if !val.IsValid() {
return nil, fmt.Errorf("invalid value of type %T", v)
}
if tagname == "" {
tagname = tagName
}
return getReflectTypeInfo(val.Type(), tagname)
}
func getReflectTypeInfo(typ reflect.Type, tagname string) (*TypeInfo, error) {
tinfoLock.RLock()
tinfo, ok := tinfoMap[typ]
tinfoLock.RUnlock()
if ok {
return tinfo, nil
}
if typ.Kind() != reflect.Struct {
return nil, fmt.Errorf("type %s (%s) is not a struct", typ.String(), typ.Kind())
}
tinfo = &TypeInfo{
Name: typ.String(),
IsGoType: true,
TagName: tagname,
}
n := typ.NumField()
for i := 0; i < n; i++ {
f := typ.Field(i)
if (f.PkgPath != "" && !f.Anonymous) || f.Tag.Get(tinfo.TagName) == "-" {
continue // Private field
}
// For embedded structs, embed its fields.
if f.Anonymous {
t := f.Type
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() == reflect.Struct {
inner, err := getReflectTypeInfo(t, tinfo.TagName)
if err != nil {
return nil, err
}
for _, finfo := range inner.Fields {
finfo.Idx = append([]int{i}, finfo.Idx...)
if err := addFieldInfo(typ, tinfo, &finfo); err != nil {
return nil, err
}
}
continue
}
}
finfo, err := structFieldInfo(typ, &f, tinfo.TagName)
if err != nil {
return nil, err
}
// Add the field if it doesn't conflict with other fields.
if err := addFieldInfo(typ, tinfo, finfo); err != nil {
return nil, err
}
}
tinfoLock.Lock()
tinfoMap[typ] = tinfo
tinfoLock.Unlock()
return tinfo, nil
}
// structFieldInfo builds and returns a fieldInfo for f.
func structFieldInfo(typ reflect.Type, f *reflect.StructField, tagname string) (*FieldInfo, error) {
finfo := &FieldInfo{Idx: f.Index, Name: f.Name, TypeName: f.Type.String()}
switch tags := strings.Split(f.Tag.Get(tagname), ","); len(tags) {
case 0:
finfo.Alias = finfo.Name
case 1:
finfo.Alias = tags[0]
default:
finfo.Alias = tags[0]
finfo.Flags = tags[1:]
}
return finfo, nil
}
func addFieldInfo(typ reflect.Type, tinfo *TypeInfo, newf *FieldInfo) error {
var conflicts []int
// Find all conflicts.
for i := range tinfo.Fields {
oldf := &tinfo.Fields[i]
if newf.Name == oldf.Name {
conflicts = append(conflicts, i)
}
}
// Return the first error.
for _, i := range conflicts {
oldf := &tinfo.Fields[i]
f1 := typ.FieldByIndex(oldf.Idx)
f2 := typ.FieldByIndex(newf.Idx)
return fmt.Errorf("%s: %s field %q with tag %q conflicts with field %q with tag %q",
tinfo.TagName, typ, f1.Name, f1.Tag.Get(tinfo.TagName), f2.Name, f2.Tag.Get(tinfo.TagName))
}
// Without conflicts, add the new field and return.
tinfo.Fields = append(tinfo.Fields, *newf)
return nil
}
// value returns v's field value corresponding to finfo.
// It's equivalent to v.FieldByIndex(finfo.idx), but initializes
// and dereferences pointers as necessary.
func (finfo *FieldInfo) Value(v reflect.Value) reflect.Value {
for i, x := range finfo.Idx {
if i > 0 {
t := v.Type()
if t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Struct {
if v.IsNil() {
v.Set(reflect.New(v.Type().Elem()))
}
v = v.Elem()
}
}
v = v.Field(x)
}
return v
}
// Load value from interface, but only if the result will be
// usefully addressable.
func (finfo *FieldInfo) DerefIndirect(v interface{}) reflect.Value {
return derefValue(reflect.ValueOf(v))
}
func derefValue(val reflect.Value) reflect.Value {
if val.Kind() == reflect.Interface && !val.IsNil() {
e := val.Elem()
if e.Kind() == reflect.Ptr && !e.IsNil() {
val = e
}
}
if val.Kind() == reflect.Ptr {
if val.IsNil() {
val.Set(reflect.New(val.Type().Elem()))
}
val = val.Elem()
}
return val
}