-
Notifications
You must be signed in to change notification settings - Fork 0
/
iface_copier.go
63 lines (55 loc) · 1.41 KB
/
iface_copier.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
package deepcopy
import (
"reflect"
)
// fromIfaceCopier data structure of copier that copies from an interface
type fromIfaceCopier struct {
ctx *Context
}
func (c *fromIfaceCopier) init(dst, src reflect.Type) error {
return nil
}
// Copy implementation of Copy function for from-iface copier
func (c *fromIfaceCopier) Copy(dst, src reflect.Value) error {
for src.Kind() == reflect.Interface {
src = src.Elem()
if !src.IsValid() {
dst.Set(reflect.Zero(dst.Type())) // NOTE: Go1.18 has no SetZero
return nil
}
}
cp, err := buildCopier(c.ctx, dst.Type(), src.Type())
if err != nil {
return err
}
return cp.Copy(dst, src)
}
// toIfaceCopier data structure of copier that copies to an interface
type toIfaceCopier struct {
ctx *Context
}
func (c *toIfaceCopier) init(dst, src reflect.Type) error {
return nil
}
// Copy implementation of Copy function for to-iface copier
func (c *toIfaceCopier) Copy(dst, src reflect.Value) error {
for src.Kind() == reflect.Interface {
src = src.Elem()
if !src.IsValid() {
dst.Set(reflect.Zero(dst.Type())) // NOTE: Go1.18 has no SetZero
return nil
}
}
// As `dst` is interface, we clone the `src` and assign back to the `dst`
srcType := src.Type()
cloneSrc := reflect.New(srcType).Elem()
cp, err := buildCopier(c.ctx, srcType, srcType)
if err != nil {
return err
}
if err = cp.Copy(cloneSrc, src); err != nil {
return err
}
dst.Set(cloneSrc)
return nil
}