-
Notifications
You must be signed in to change notification settings - Fork 2
/
copy_struct.go
291 lines (259 loc) · 6.76 KB
/
copy_struct.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
package mapper
import (
"context"
"fmt"
"reflect"
"sync"
"unsafe"
)
/*
**************************
@author: tiansheng.ren
@date: 2022/10/25
@desc:
**************************
*/
var (
tagName = "json"
excludeTagValue = "-"
copyValueTagPrefix = "copy"
)
type fieldDescription struct {
fieldName string
name string
idx int
inline bool
omitEmpty bool
private bool
typ reflect.Type
}
type structDescription struct {
fm map[string]*fieldDescription
}
type structCache struct {
cache map[reflect.Type]*structDescription
sync.RWMutex
copyPrivate bool
validateStruct bool
}
func newStructCache() *structCache {
return &structCache{
cache: make(map[reflect.Type]*structDescription, 0),
copyPrivate: false,
}
}
func (dcv *defaultCopyValue) StructCopyValue(ctx context.Context, src, dst reflect.Value) error {
if !dst.CanSet() {
return CanSetError{Name: "StructCopyValue"}
}
if dst.Kind() != reflect.Struct {
return LookupCopyValueError{Name: "StructCopyValue", Kinds: []reflect.Kind{reflect.Struct}, Received: dst}
}
src = skipElem(src)
switch src.Kind() {
case reflect.Struct:
case reflect.Map:
// copy map to struct
return dcv.MapToStructCopyValue(ctx, src, dst)
default:
return CopyValueError{
Name: "StructCopyValue",
Types: nil,
Kinds: []reflect.Kind{reflect.Map, reflect.Struct},
Received: src,
}
}
if dst.IsZero() {
dst.Set(reflect.New(dst.Type()).Elem())
}
srcSD, err := dcv.describeStruct(ctx, src.Type())
if err != nil {
return err
}
dstSD, err := dcv.describeStruct(ctx, dst.Type())
if err != nil {
return err
}
for name, descField := range dstSD.fm {
srcDescField, ok := srcSD.fm[name]
if !ok {
// not found, continue
continue
}
srcItem, dstItem := src.FieldByName(srcDescField.fieldName), dst.FieldByName(descField.fieldName)
if descField.private {
if !dcv.structCache.copyPrivate {
continue
}
dstItem = reflect.NewAt(dstItem.Type(), unsafe.Pointer(dstItem.UnsafeAddr())).Elem()
}
if dstItem.Kind() == reflect.Interface && dstItem.IsNil() {
dstItem.Set(reflect.New(descField.typ).Elem())
}
fn, err := dcv.lookupCopyValue(dstItem)
if err != nil {
return err
}
if err := fn(ctx, srcItem, dstItem); err != nil {
return err
}
}
if dcv.validate != nil {
if err := dcv.validate.Struct(dst.Interface()); err != nil {
return err
}
}
return nil
}
func (dcv *defaultCopyValue) MapToStructCopyValue(ctx context.Context, src, dst reflect.Value) error {
if !dst.CanSet() {
return CanSetError{Name: "MapToStructCopyValue"}
}
if dst.Kind() != reflect.Struct {
return LookupCopyValueError{Name: "MapToStructCopyValue", Kinds: []reflect.Kind{reflect.Struct}, Received: dst}
}
if src.Kind() != reflect.Map {
return CopyValueError{Name: "MapToStructCopyValue", Kinds: []reflect.Kind{reflect.Map}, Received: src}
}
if src.IsNil() {
return nil
}
if src.Type().Key().Kind() != reflect.String {
// notice: this error is not accurate, need to be improved
return CopyValueError{Name: "MapToStructCopyValue", Kinds: []reflect.Kind{reflect.Map}, Received: src}
}
src = skipElem(src)
if dst.IsZero() {
dst.Set(reflect.New(dst.Type()).Elem())
}
dstSD, err := dcv.describeStruct(ctx, dst.Type())
if err != nil {
return err
}
iter := src.MapRange()
for iter.Next() {
key := iter.Key().String()
value := iter.Value()
descField, ok := dstSD.fm[key]
if !ok {
continue
}
dstVal := dst.FieldByName(descField.fieldName)
if descField.private {
if !dcv.structCache.copyPrivate {
continue
}
dstVal = reflect.NewAt(dstVal.Type(), unsafe.Pointer(dstVal.UnsafeAddr())).Elem()
}
fn, err := dcv.lookupCopyValue(dstVal)
if err != nil {
return err
}
if err := fn(ctx, value, dstVal); err != nil {
return err
}
}
return nil
}
func (dcv *defaultCopyValue) StructToMapCopyValue(ctx context.Context, src, dst reflect.Value) error {
if !dst.CanSet() {
return CanSetError{Name: "StructToMapCopyValue"}
}
if dst.Kind() != reflect.Map || dst.Type().Key().Kind() != reflect.String {
return LookupCopyValueError{Name: "StructToMapCopyValue", Kinds: []reflect.Kind{reflect.Struct}, Received: dst}
}
src = skipElem(src)
if src.Kind() != reflect.Struct {
return CopyValueError{Name: "StructToMapCopyValue", Kinds: []reflect.Kind{reflect.Struct}, Received: src}
}
if dst.IsZero() {
dst.Set(reflect.MakeMap(dst.Type()))
}
srcSD, err := dcv.describeStruct(ctx, src.Type())
if err != nil {
return err
}
myIsNil := func(v reflect.Value) bool {
k := v.Kind()
switch k {
case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice:
return v.IsNil()
}
return false
}
for name, descField := range srcSD.fm {
if descField.private && !dcv.structCache.copyPrivate {
//fix map to struct 拷贝私有对象
continue
}
fieldSrc := src.FieldByName(descField.fieldName)
// copy struct to map, if the field is empty and tag has omitempty, we skip it.
if descField.omitEmpty && myIsNil(fieldSrc) {
continue
}
dstVal := reflect.New(dst.Type().Elem()).Elem()
fn, err := dcv.lookupCopyValue(dstVal)
if err != nil {
return err
}
if err := fn(ctx, fieldSrc, dstVal); err != nil {
return err
}
dst.SetMapIndex(reflect.ValueOf(name), dstVal)
}
return nil
}
func (dcv *defaultCopyValue) describeStruct(ctx context.Context, t reflect.Type) (*structDescription, error) {
// We need to analyze the struct, including getting the tags, collecting
// information about inlining, and create a map of the field name to the field.
dcv.structCache.RLock()
ds, exists := dcv.structCache.cache[t]
dcv.structCache.RUnlock()
if exists {
return ds, nil
}
numFields := t.NumField()
sd := &structDescription{
fm: make(map[string]*fieldDescription, numFields),
}
for i := 0; i < numFields; i++ {
sf := t.Field(i)
desc := &fieldDescription{
fieldName: sf.Name,
name: sf.Name,
idx: i,
typ: sf.Type,
}
if !sf.IsExported() {
desc.private = true
}
if sf.Anonymous {
inlineSF, err := dcv.describeStruct(ctx, sf.Type)
if err != nil {
return nil, err
}
for _, fd := range inlineSF.fm {
if _, exists := sd.fm[fd.name]; exists {
return nil, fmt.Errorf("(struct %s) duplicated key %s", t.String(), fd.name)
}
sd.fm[fd.name] = fd
}
continue
}
for _, fn := range tagHandleFnList {
if tag := fn.newFn(sf.Tag.Get(fn.tagName)); tag.Name() != "" {
desc.name = tag.Name()
desc.omitEmpty = tag.OmitEmpty()
break
}
}
if _, exists := sd.fm[desc.name]; exists {
return nil, fmt.Errorf("(struct %s) duplicated key %s", t.String(), desc.name)
}
sd.fm[desc.name] = desc
}
dcv.structCache.Lock()
dcv.structCache.cache[t] = sd
dcv.structCache.Unlock()
return sd, nil
}