-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclone.go
102 lines (83 loc) · 1.93 KB
/
clone.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
package goast
import (
"go/ast"
"reflect"
)
type cloneContext struct {
objectDepth int
}
func newCloneContext() *cloneContext {
return &cloneContext{}
}
func copyCloneContext(ctx *cloneContext) *cloneContext {
newCtx := *ctx
return &newCtx
}
func clone(ctx *cloneContext, value reflect.Value) reflect.Value {
adjustValue := func(ret reflect.Value) reflect.Value {
switch value.Kind() {
case reflect.Ptr, reflect.Map, reflect.Slice, reflect.Array:
return ret
default:
return ret.Elem()
}
}
src := value
if value.Kind() == reflect.Ptr {
if value.IsNil() {
return reflect.New(value.Type()).Elem()
}
src = value.Elem()
}
var dst reflect.Value
switch src.Kind() {
case reflect.String:
dst = reflect.New(src.Type())
dst.Elem().SetString(value.String())
case reflect.Struct:
dst = reflect.New(src.Type())
t := src.Type()
for i := 0; i < t.NumField(); i++ {
fv := src.Field(i)
objType := reflect.TypeOf(&ast.Object{})
newCtx := copyCloneContext(ctx)
if fv.Type() == objType {
if newCtx.objectDepth <= 0 {
empty := reflect.New(fv.Type())
dst.Elem().Field(i).Set(empty.Elem())
continue
} else {
newCtx.objectDepth--
}
}
if !fv.CanInterface() {
continue
}
v := clone(newCtx, fv)
dst.Elem().Field(i).Set(v)
}
case reflect.Map:
dst = reflect.MakeMap(src.Type())
keys := src.MapKeys()
for i := 0; i < src.Len(); i++ {
mValue := src.MapIndex(keys[i])
dst.SetMapIndex(keys[i], clone(ctx, mValue))
}
case reflect.Array, reflect.Slice:
dst = reflect.MakeSlice(src.Type(), src.Len(), src.Cap())
for i := 0; i < src.Len(); i++ {
srcValue := src.Index(i)
newValue := clone(ctx, srcValue)
dst.Index(i).Set(newValue)
}
case reflect.Interface:
dst = reflect.New(src.Type())
if !src.IsNil() {
dst.Elem().Set(clone(ctx, src.Elem()))
}
default:
dst = reflect.New(src.Type())
dst.Elem().Set(src)
}
return adjustValue(dst)
}