Skip to content
This repository has been archived by the owner on Jul 22, 2024. It is now read-only.

Commit

Permalink
Use custom copiers declared in Config
Browse files Browse the repository at this point in the history
  • Loading branch information
radeksimko committed Apr 8, 2021
1 parent 1e4d1a1 commit 51d5881
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
4 changes: 3 additions & 1 deletion copystructure.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ func (c Config) Copy(v interface{}) (interface{}, error) {
if c.Copiers == nil {
c.Copiers = Copiers
}
w.copiers = c.Copiers

err := reflectwalk.Walk(v, w)
if err != nil {
Expand Down Expand Up @@ -116,6 +117,7 @@ func ifaceKey(pointers, depth int) uint64 {
type walker struct {
Result interface{}

copiers map[reflect.Type]CopierFunc
depth int
ignoreDepth int
vals []reflect.Value
Expand Down Expand Up @@ -379,7 +381,7 @@ func (w *walker) Struct(s reflect.Value) error {
w.lock(s)

var v reflect.Value
if c, ok := Copiers[s.Type()]; ok {
if c, ok := w.copiers[s.Type()]; ok {
// We have a Copier for this struct, so we use that copier to
// get the copy, and we ignore anything deeper than this.
w.ignoreDepth = w.depth
Expand Down
34 changes: 34 additions & 0 deletions copystructure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1153,3 +1153,37 @@ func TestCopy_timeDoublePointer(t *testing.T) {
t.Fatalf("\n%#v\n\n%#v", v, result)
}
}

type nestedValue struct {
v string
}

func TestCopy_customCopierConfig(t *testing.T) {
type T struct {
Val *nestedValue
}

v := &T{
Val: &nestedValue{v: "original"},
}

cfg := Config{
Copiers: map[reflect.Type]CopierFunc{
reflect.TypeOf(nestedValue{}): customCopier,
},
}
result, err := cfg.Copy(v)
if err != nil {
t.Fatal(err)
}

copiedVal := result.(*T)

if !reflect.DeepEqual(v.Val.v, copiedVal.Val.v) {
t.Fatalf("\nexpected: %#v\ngiven: %#v", v.Val.v, copiedVal.Val.v)
}
}

func customCopier(v interface{}) (interface{}, error) {
return v.(nestedValue), nil
}

0 comments on commit 51d5881

Please sign in to comment.