-
Notifications
You must be signed in to change notification settings - Fork 2
/
copy_slice.go
101 lines (86 loc) · 2.39 KB
/
copy_slice.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
package mapper
import (
"context"
"fmt"
"reflect"
)
/***************************
@author: tiansheng.ren
@date: 2022/11/2
@desc:
***************************/
func (dcv *defaultCopyValue) SliceCopyValue(ctx context.Context, src, dst reflect.Value) error {
items, err := dcv.sliceCopyValue(ctx, src, dst)
if err != nil {
return err
}
//dst.SetLen(0)
dst.Set(reflect.Append(dst, items...))
return nil
}
func (dcv *defaultCopyValue) sliceCopyValue(ctx context.Context, src, dst reflect.Value) ([]reflect.Value, error) {
if !dst.CanSet() {
return nil, CanSetError{Name: "sliceCopyValue"}
}
if dst.Kind() != reflect.Slice {
return nil, LookupCopyValueError{Name: "sliceCopyValue", Kinds: []reflect.Kind{reflect.Slice}, Received: dst}
}
src = skipElem(src)
if src.Kind() != reflect.Slice {
return nil, CopyValueError{
Name: "sliceCopyValue",
Types: nil,
Kinds: []reflect.Kind{reflect.Slice},
Received: src,
}
}
if dst.IsZero() {
dst.Set(reflect.MakeSlice(dst.Type(), 0, src.Len()))
}
typ := dst.Type().Elem()
items := make([]reflect.Value, 0, src.Len())
for i := 0; i < src.Len(); i++ {
itemDst := reflect.New(typ).Elem()
fn, err := dcv.lookupCopyValue(itemDst)
if err != nil {
return nil, err
}
if err := fn(ctx, src.Index(i), itemDst); err != nil {
return nil, err
}
items = append(items, itemDst)
}
return items, nil
}
func (dcv *defaultCopyValue) ArrayCopyValue(ctx context.Context, src, dst reflect.Value) error {
if !dst.CanSet() {
return CanSetError{Name: "ArrayCopyValue"}
}
if dst.Kind() != reflect.Array {
return LookupCopyValueError{Name: "ArrayCopyValue", Kinds: []reflect.Kind{reflect.Slice}, Received: dst}
}
if src.Len() > dst.Len() {
return fmt.Errorf("more elements returned in array than can fit inside %s", dst.Type())
}
switch src.Kind() {
case reflect.Array:
if src.Elem().Kind() != dst.Elem().Kind() {
return CopyValueError{Name: "ArrayCopyValue", Kinds: []reflect.Kind{reflect.Array}, Received: src}
}
default:
return CopyValueError{Name: "ArrayCopyValue", Kinds: []reflect.Kind{reflect.Array}, Received: src}
}
typ := dst.Elem().Type()
for i := 0; i < src.Len(); i++ {
fn, err := dcv.lookupCopyValue(dst.Elem())
if err != nil {
return err
}
itemDst := reflect.New(typ)
if err := fn(ctx, src.Index(i), itemDst); err != nil {
return err
}
dst.Index(i).Set(itemDst)
}
return nil
}