-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdeepcopy.go
More file actions
98 lines (78 loc) · 1.68 KB
/
deepcopy.go
File metadata and controls
98 lines (78 loc) · 1.68 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package deepcopy
import (
"reflect"
"time"
)
func Clone(dstPtr interface{}, srcPtr interface{}) {
origin := reflect.ValueOf(srcPtr).Elem()
clone := reflect.ValueOf(dstPtr).Elem()
copy(origin, clone)
return
}
func copy(_origin, _clone reflect.Value) {
oq, cq := values{}, values{}
oq.Init(64)
cq.Init(64)
oq.Push(_origin)
cq.Push(_clone)
for oq.Len() > 0 {
o, c := oq.Shift(), cq.Shift()
switch o.Kind() {
case reflect.Ptr:
originVal := o.Elem()
if originVal.IsValid() == false {
continue
}
c.Set(reflect.New(originVal.Type()))
oq.Push(originVal)
cq.Push(c.Elem())
case reflect.Interface:
if o.IsNil() {
continue
}
originVal := o.Elem()
cloneVal := reflect.New(originVal.Type()).Elem()
c.Set(cloneVal)
oq.Push(originVal)
cq.Push(cloneVal)
case reflect.Struct:
t, ok := o.Interface().(time.Time)
if ok {
c.Set(reflect.ValueOf(t))
continue
}
for i := 0; i < o.NumField(); i++ {
if o.Type().Field(i).PkgPath != "" {
continue
}
oq.Push(o.Field(i))
cq.Push(c.Field(i))
}
case reflect.Slice:
if o.IsNil() {
continue
}
c.Set(reflect.MakeSlice(o.Type(), o.Len(), o.Cap()))
for i := 0; i < o.Len(); i++ {
oq.Push(o.Index(i))
cq.Push(c.Index(i))
}
case reflect.Map:
if o.IsNil() {
continue
}
c.Set(reflect.MakeMap(o.Type()))
for _, key := range o.MapKeys() {
originVal := o.MapIndex(key)
cloneVal := reflect.New(originVal.Type()).Elem()
var copyKey interface{}
Clone(copyKey, key.Interface())
c.SetMapIndex(reflect.ValueOf(copyKey), cloneVal)
}
case reflect.String:
c.SetString(o.String())
default:
c.Set(o)
}
}
}