-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcopy_map.go
76 lines (67 loc) · 1.69 KB
/
copy_map.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
package mapper
import (
"context"
"fmt"
"reflect"
)
/***************************
@author: tiansheng.ren
@date: 2022/10/25
@desc:
***************************/
func (dcv *defaultCopyValue) MapCopyValue(ctx context.Context, src, dst reflect.Value) error {
if !dst.CanSet() {
return CanSetError{Name: "MapCopyValue"}
}
if dst.Kind() != reflect.Map {
return LookupCopyValueError{Name: "MapCopyValue", Kinds: []reflect.Kind{reflect.Map}, Received: dst}
}
src = skipElem(src)
switch src.Kind() {
case reflect.Map:
case reflect.Struct:
return dcv.StructToMapCopyValue(ctx, src, dst)
default:
if src.Kind() == reflect.Invalid || src.IsNil() {
// dst is map, src is nil, just return
return nil
}
return CopyValueError{
Name: "MapCopyValue",
Kinds: []reflect.Kind{reflect.Map},
Received: src,
}
}
if src.Type().Key() != dst.Type().Key() {
return fmt.Errorf("cannot copy map[%v]%v into an map[%v][%v] type",
src.Type().Key(), src.Type().Elem(), dst.Type().Key(), dst.Type().Elem())
}
if dst.IsNil() {
dst.Set(reflect.MakeMap(dst.Type()))
}
keyType := dst.Type().Key()
valueType := dst.Type().Elem()
fnKey, err := dcv.lookupCopyValue(reflect.New(keyType).Elem())
if err != nil {
return err
}
fnValue, err := dcv.lookupCopyValue(reflect.New(valueType).Elem())
if err != nil {
return err
}
iter := src.MapRange()
for iter.Next() {
key := iter.Key()
value := iter.Value()
newKey := reflect.New(keyType).Elem()
newValue := reflect.New(valueType).Elem()
if err := fnKey(ctx, key, newKey); err != nil {
return err
}
if err := fnValue(ctx, value, newValue); err != nil {
return err
}
dst.SetMapIndex(newKey, newValue)
}
return nil
}