-
Notifications
You must be signed in to change notification settings - Fork 1
/
convertor.go
493 lines (460 loc) · 12.6 KB
/
convertor.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
package convertor
import (
"errors"
"fmt"
"reflect"
"sort"
"sync"
)
const (
convertorTag = "convertor"
)
type convertFuncsType map[[2]reflect.Type]reflect.Value
var (
cacheFields sync.Map
convertFuncs = convertFuncsType{} // global convert func
errType = reflect.TypeOf((*error)(nil)).Elem()
)
// RegisterConvertFunc register convert function like func (src SrcType, dest DestType) error
// SrcType must not be pointer, DestType must be pointer
// concurrent unsafe, just register in main func, and it will panic if it's a bad convert func
func RegisterConvertFunc(f interface{}) {
if err := registerConvertFunc(convertFuncs, f); err != nil {
panic(err)
}
}
var (
BadConvertFuncNotFunc = errors.New("convert func is not function")
BadConvertFuncInCount = errors.New("bad convertor func in count")
BadConvertFuncSrcTypeIsPointer = errors.New("convertor func src type should not be pointer")
BadConvertFuncDestTypeNotPointer = errors.New("convertor func dest type should be pointer")
BadConvertFuncOut = errors.New("bad convertor func out")
)
func registerConvertFunc(convertFuncs convertFuncsType, f interface{}) error {
val := reflect.ValueOf(f)
if val.Type().Kind() != reflect.Func {
return BadConvertFuncNotFunc
}
if val.Type().NumIn() != 2 {
return BadConvertFuncInCount
}
if val.Type().In(0).Kind() == reflect.Ptr {
return BadConvertFuncSrcTypeIsPointer
}
if val.Type().In(1).Kind() != reflect.Ptr {
return BadConvertFuncDestTypeNotPointer
}
if val.Type().NumOut() != 1 || !isErrorType(val.Type().Out(0)) {
return BadConvertFuncOut
}
convertFuncs[[2]reflect.Type{val.Type().In(0), val.Type().In(1)}] = val
return nil
}
func isErrorType(typ reflect.Type) bool {
return typ.Implements(errType)
}
/*
TO consider:
interface assign
*/
type typeStruct struct {
err error
fields []typeField
elemStruct *typeStruct // slice element struct
}
type typeField struct {
Type reflect.Type
Name string
Idx int
NextIdx int
NextStruct *typeStruct
FinalStruct *typeStruct // current field endpoint struct
}
var (
ErrDestinationNotPointer = errors.New("destination value is not pointer")
ErrNilDestination = errors.New("nil destination")
notStructType = &typeStruct{}
)
func getCacheStruct(typ reflect.Type, typePath map[reflect.Type]bool) (finalTypeStruct *typeStruct) {
if val, ok := cacheFields.Load(typ); ok {
return val.(*typeStruct)
}
if typePath == nil {
typePath = map[reflect.Type]bool{}
}
if typePath[typ] { // prevent cirle struct rely
return &typeStruct{
err: fmt.Errorf("circle struct rely: %s", typ),
}
}
typePath[typ] = true
originType := typ
defer func() {
sort.Slice(finalTypeStruct.fields, func(i, j int) bool {
return finalTypeStruct.fields[i].Name < finalTypeStruct.fields[j].Name
})
cacheFields.Store(originType, finalTypeStruct)
typePath[typ] = false
if finalTypeStruct.err != nil {
return
}
if typ.Kind() == reflect.Slice {
finalTypeStruct = &typeStruct{
fields: finalTypeStruct.fields,
elemStruct: getCacheStruct(typ.Elem(), nil),
}
}
for i, field := range finalTypeStruct.fields {
if field.FinalStruct == nil {
finalTypeStruct.fields[i].FinalStruct = getCacheStruct(field.Type, nil)
}
}
}()
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
if typ.Kind() != reflect.Struct {
return notStructType
}
finalFields := make([]typeField, 0, typ.NumField())
nameMap := map[string]bool{}
var anonymousStructField []reflect.StructField
var anonymousStructFieldIndex []int
tmpVal := reflect.New(typ).Elem()
for i := 0; i < typ.NumField(); i++ {
if !tmpVal.Field(i).CanSet() { // unexport
continue
}
field := typ.Field(i)
tf := typeField{
Type: field.Type,
Name: field.Name,
Idx: i,
NextIdx: -1,
}
// use convertor tag to cover field name
tag, ok := field.Tag.Lookup(convertorTag)
if ok {
if tag == "-" { // ignore field
continue
}
tf.Name = tag
}
if (field.Anonymous && !ok) || (ok && tag == "+") { // anonymous field has not tag, flatten later
anonymousStructField = append(anonymousStructField, field)
anonymousStructFieldIndex = append(anonymousStructFieldIndex, i)
continue
}
finalFields = append(finalFields, tf)
if nameMap[tf.Name] {
return &typeStruct{
err: fmt.Errorf("conflict field name and tag: %s", tf.Name),
}
}
nameMap[tf.Name] = true
}
var allAnonFields []typeField
for i, field := range anonymousStructField {
ftStruct := getCacheStruct(field.Type, typePath)
if ftStruct.err != nil {
return ftStruct
}
if fieldName := inFields(ftStruct.fields, allAnonFields); len(fieldName) > 0 { // two anonymous field has same sub field
return &typeStruct{
err: fmt.Errorf("ambiguous field %s", fieldName),
}
}
allAnonFields = append(allAnonFields, ftStruct.fields...)
for _, subField := range ftStruct.fields {
if !nameMap[subField.Name] {
nameMap[subField.Name] = true
finalFields = append(finalFields, typeField{
Type: subField.Type,
Name: subField.Name,
Idx: anonymousStructFieldIndex[i],
NextStruct: ftStruct,
NextIdx: subField.Idx,
})
}
}
}
return &typeStruct{
fields: finalFields,
}
}
func inFields(sub, full []typeField) string {
for _, subField := range sub {
for _, fullField := range full {
if subField.Name == fullField.Name {
return subField.Name
}
}
}
return ""
}
type Options struct {
convertFuncs convertFuncsType
srcNotExistFieldIgnore bool
destNotExistFieldIgnore bool
}
type Option func(*Options) error
type convertor struct {
opts Options
}
type Convertor interface {
Convert(src, dest interface{}) error
}
// concurrent unsafe
func OptionConvertFunc(f interface{}) Option {
return func(opts *Options) error {
if opts.convertFuncs == nil {
opts.convertFuncs = convertFuncsType{}
}
return registerConvertFunc(opts.convertFuncs, f)
}
}
func OptionSrcNotExistFieldIgnore() Option {
return func(opts *Options) error {
opts.srcNotExistFieldIgnore = true
return nil
}
}
func OptionDestNotExistFieldIgnore() Option {
return func(opts *Options) error {
opts.destNotExistFieldIgnore = true
return nil
}
}
func NewConvertor(opts ...Option) (Convertor, error) {
c := &convertor{}
for _, o := range opts {
if err := o(&c.opts); err != nil {
return nil, err
}
}
return c, nil
}
/*
Convert convert struct src to dest
Example:
type D struct {
DD int64
}
type B struct {
BB string
DD int
}
type C struct {
BB string
D
}
var a = B{}
var b = C{}
Convert(a, &b)
Convert(&a, &b)
*/
func Convert(src, dest interface{}, opts ...Option) error {
if len(opts) > 0 {
c, err := NewConvertor(opts...)
if err != nil {
return err
}
return c.Convert(src, dest)
}
return DefaultConvertor.Convert(src, dest)
}
var DefaultConvertor, _ = NewConvertor()
var SrcNotExistFieldIgnoreConvertor, _ = NewConvertor(OptionSrcNotExistFieldIgnore())
var DestNotExistFieldIgnoreConvertor, _ = NewConvertor(OptionDestNotExistFieldIgnore())
func (c *convertor) Convert(src, dest interface{}) (err error) {
destVal := reflect.ValueOf(dest)
if destVal.Kind() != reflect.Ptr {
return ErrDestinationNotPointer
}
if destVal.IsNil() {
return ErrNilDestination
}
srcVal := reflect.ValueOf(src)
return c.convert(srcVal, destVal, nil, nil)
}
func (c *convertor) getConvertFunc(src, dest reflect.Value) (convertFunc reflect.Value, ok bool) {
convertFuncKey := [2]reflect.Type{src.Type(), dest.Type()}
if len(c.opts.convertFuncs) > 0 {
convertFunc, ok = c.opts.convertFuncs[convertFuncKey]
}
if !ok && len(convertFuncs) > 0 {
convertFunc, ok = convertFuncs[convertFuncKey]
}
return
}
func (c *convertor) convert(src, dest reflect.Value, srcStruct, destStruct *typeStruct) error {
indirectSrc := reflect.Indirect(src)
convertFunc, ok := c.getConvertFunc(indirectSrc, dest)
if ok {
out := convertFunc.Call([]reflect.Value{indirectSrc, dest})
if err, ok := out[0].Interface().(error); ok {
return err
}
return nil
}
indirectDest := reflect.Indirect(dest)
if indirectSrc.Type().AssignableTo(indirectDest.Type()) {
indirectDest.Set(indirectSrc)
return nil
}
if c.convertTo(indirectSrc, indirectDest) {
return nil
}
if srcStruct == nil {
srcStruct = getCacheStruct(src.Type(), nil)
}
if destStruct == nil {
destStruct = getCacheStruct(dest.Type(), nil)
}
if srcStruct.err != nil {
return srcStruct.err
}
if destStruct.err != nil {
return destStruct.err
}
if indirectSrc.Kind() == reflect.Slice && indirectDest.Kind() == reflect.Slice {
if src.IsNil() {
return nil
}
src = indirectSrc
dest = indirectDest
dest.Set(reflect.MakeSlice(dest.Type(), src.Len(), src.Cap()))
srcElemStruct := srcStruct.elemStruct
destElemStruct := destStruct.elemStruct
for i := 0; i < src.Len(); i++ {
srcElem := src.Index(i)
if srcElem.Kind() == reflect.Ptr && srcElem.IsNil() {
continue
}
destElem := dest.Index(i)
if destElem.Kind() == reflect.Ptr && destElem.IsNil() {
destElem.Set(reflect.New(destElem.Type().Elem()))
}
if destElem.Kind() != reflect.Ptr && destElem.CanAddr() {
destElem = destElem.Addr()
}
if err := c.convert(srcElem, destElem, srcElemStruct, destElemStruct); err != nil {
return err
}
}
return nil
}
if indirectSrc.Kind() != reflect.Struct || indirectDest.Kind() != reflect.Struct {
return fmt.Errorf("type %s is not convertiable to type %s", src.Type(), dest.Type())
}
srcFields := srcStruct.fields
destFields := destStruct.fields
var i, j int
for i < len(srcFields) && j < len(destFields) {
if srcFields[i].Name != destFields[j].Name {
var err error
if srcFields[i].Name < destFields[j].Name {
if c.opts.destNotExistFieldIgnore {
i++
continue
}
err = fmt.Errorf("dest has no field to receive src field %s(%v)", srcFields[i].Name, srcFields[i].Type)
} else {
if c.opts.srcNotExistFieldIgnore {
j++
continue
}
err = fmt.Errorf("src has no field %s(%v) convert to dest", destFields[j].Name, destFields[j].Type)
}
return err
}
val, srcFinalStruct := getValueByPath(src, srcFields[i])
if val == zeroValue || (val.Kind() == reflect.Ptr && val.IsNil()) {
i++
j++
continue
}
if err := c.setValueByPath(dest, val, destFields[j], srcFinalStruct); err != nil {
return err
}
i++
j++
}
if i < len(srcFields) && !c.opts.destNotExistFieldIgnore {
return fmt.Errorf("dest has no field to receive src field %s(%v)", srcFields[i].Name, srcFields[i].Type)
}
if j < len(destFields) && !c.opts.srcNotExistFieldIgnore {
return fmt.Errorf("src has no field %s(%v) convert to dest", destFields[j].Name, destFields[j].Type)
}
return nil
}
func (c *convertor) convertTo(src, dest reflect.Value) bool {
switch src.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
switch dest.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
dest.SetInt(src.Int())
return true
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
dest.SetUint(uint64(src.Int()))
return true
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
switch dest.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
dest.SetInt(int64(src.Uint()))
return true
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
dest.SetUint(src.Uint())
return true
}
case reflect.Float32, reflect.Float64:
switch dest.Kind() {
case reflect.Float32, reflect.Float64:
dest.SetFloat(src.Float())
return true
}
}
return false
}
var zeroValue = reflect.Value{}
func getValueByPath(val reflect.Value, field typeField) (reflect.Value, *typeStruct) {
for {
if val.Kind() == reflect.Ptr {
if val.IsNil() {
return zeroValue, notStructType
}
val = val.Elem()
}
val = val.Field(field.Idx)
if field.NextStruct == nil {
break
}
field = field.NextStruct.fields[field.NextIdx]
}
return val, field.FinalStruct
}
func (c *convertor) setValueByPath(dest, val reflect.Value, field typeField, srcFinalStruct *typeStruct) error {
for {
if dest.Kind() == reflect.Ptr {
if dest.IsNil() {
dest.Set(reflect.New(dest.Type().Elem()))
}
dest = dest.Elem()
}
dest = dest.Field(field.Idx)
if field.NextStruct == nil {
break
}
field = field.NextStruct.fields[field.NextIdx]
}
if dest.Kind() == reflect.Ptr {
if dest.IsNil() {
dest.Set(reflect.New(dest.Type().Elem()))
}
}
if dest.Kind() != reflect.Ptr && dest.CanAddr() {
dest = dest.Addr()
}
return c.convert(val, dest, srcFinalStruct, field.FinalStruct)
}