Skip to content

Commit

Permalink
Replace json-based implementation of DeepCopy on GenericMap
Browse files Browse the repository at this point in the history
  • Loading branch information
aruiz14 committed Nov 15, 2023
1 parent 33fd98e commit cc77595
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ package v1alpha1

import (
"encoding/json"

"github.com/rancher/wrangler/pkg/data/convert"
)

type GenericMap struct {
Expand All @@ -20,8 +18,19 @@ func (in *GenericMap) UnmarshalJSON(data []byte) error {
}

func (in *GenericMap) DeepCopyInto(out *GenericMap) {
out.Data = map[string]interface{}{}
if err := convert.ToObj(in.Data, &out.Data); err != nil {
panic(err)
out.Data = make(map[string]interface{}, len(in.Data))
deepCopyMap(in.Data, out.Data)
}

func deepCopyMap(src, dest map[string]interface{}) {
for key := range src {
switch value := src[key].(type) {
case map[string]interface{}:
destValue := make(map[string]interface{}, len(value))
deepCopyMap(value, destValue)
dest[key] = destValue
default:
dest[key] = value
}
}
}
41 changes: 41 additions & 0 deletions pkg/apis/fleet.cattle.io/v1alpha1/generic_map_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package v1alpha1

import (
"testing"

"k8s.io/apimachinery/pkg/api/equality"
)

func Test_deepCopyMap(t *testing.T) {
tests := []struct {
name string
src map[string]interface{}
}{
{name: "copies top-level keys", src: map[string]interface{}{
"str": "value",
"list": []any{1, "dos", true},
"boolean": false,
}},
{name: "copies nested values", src: map[string]interface{}{
"first": map[string]any{
"second": map[string]any{
"third": map[string]any{
"str": "value",
"boolean": false,
},
"list": []any{1, "dos", true},
"boolean": false,
},
},
}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
res := map[string]interface{}{}
deepCopyMap(tt.src, res)
if !equality.Semantic.DeepEqual(tt.src, res) {
t.Errorf("result object is not identical: %+v", res)
}
})
}
}

0 comments on commit cc77595

Please sign in to comment.