-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdeepcopy.go
More file actions
83 lines (74 loc) · 1.61 KB
/
deepcopy.go
File metadata and controls
83 lines (74 loc) · 1.61 KB
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
package deepcopy
import (
"fmt"
"sync"
"unsafe"
"github.com/modern-go/reflect2"
)
// DeepCopy copies the data pointed by src to dst
// both src and dst myst be pointers
func DeepCopy(src interface{}, dst interface{}) error {
dstType := reflect2.TypeOf(dst)
srcType := reflect2.TypeOf(src)
if srcType != dstType {
return fmt.Errorf("can not copy objects of different types(%v, %v)", srcType, dstType)
}
ptrType := dstType.(*reflect2.UnsafePtrType)
copier := CopierOf(ptrType.Elem())
if copier == nil {
return fmt.Errorf("object of type %s can not be copied", dstType)
}
copier.Copy(reflect2.PtrOf(src), reflect2.PtrOf(dst))
return nil
}
type Copier interface {
// Copy copies the data pointed by src to dst
// src and dst must be pointer type and they points to the objects of the same type
Copy(src unsafe.Pointer, dst unsafe.Pointer)
}
var copiers = &sync.Map{}
func CopierOf(typ reflect2.Type) Copier {
if c, ok := copiers.Load(typ); ok {
return c.(Copier)
}
c := createCopierOf(typ)
//println("create copier of ", typ.String())
copiers.Store(typ, c)
return c
}
func createCopierOf(typ reflect2.Type) Copier {
c := createCopierOfNative(typ)
if c != nil {
return c
}
c = createCopierOfStruct(typ)
if c != nil {
return c
}
c = createCopierOfSlice(typ)
if c != nil {
return c
}
c = createCopierOfMap(typ)
if c != nil {
return c
}
c = createCopierOfPtr(typ)
if c != nil {
return c
}
c = createCopierOfEface(typ)
if c != nil {
return c
}
c = createCopierOfiface(typ)
if c != nil {
return c
}
c = createCopierOfArray(typ)
if c != nil {
return c
}
// impossible
return nil
}