Skip to content

Commit

Permalink
Copy the value from map and slice to avoid the original value being m…
Browse files Browse the repository at this point in the history
…odified.
  • Loading branch information
ktong committed Nov 21, 2024
1 parent 411ab81 commit 1d2f58f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 8 deletions.
21 changes: 13 additions & 8 deletions internal/convert/converter.go
Original file line number Diff line number Diff line change
Expand Up @@ -553,22 +553,27 @@ func (c Converter) convertStruct(name string, fromVal, toVal reflect.Value) erro
}

func (c Converter) convertInterface(name string, fromVal, toVal reflect.Value) error {
switch fromVal.Kind() {
case reflect.Map:
if fromVal.IsNil() {
toVal.SetZero()
if fromVal.IsZero() {
toVal.SetZero()

return nil
}
return nil
}

// Copy the value from map and slice to avoid the original value being modified.
switch fromVal.Kind() {
case reflect.Map:
toVal.Set(reflect.MakeMapWithSize(fromVal.Type(), fromVal.Len()))

return c.convertMap(name, fromVal, toVal.Elem())
case reflect.Slice:
newSlice := reflect.MakeSlice(fromVal.Type(), fromVal.Len(), fromVal.Len())
reflect.Copy(newSlice, fromVal)
toVal.Set(newSlice)
default:
toVal.Set(fromVal)

return nil
}

return nil
}

func pointer(val reflect.Value) reflect.Value {
Expand Down
4 changes: 4 additions & 0 deletions internal/convert/converter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -961,17 +961,21 @@ func TestConverter(t *testing.T) { //nolint:maintidx
Value: "value1",
},
"key2": "value2",
"key3": []int{1, 2},
},
to: pointer(struct {
Key1 interface{}
Key2 interface{}
Key3 interface{}
}{}),
expected: pointer(struct {
Key1 interface{}
Key2 interface{}
Key3 interface{}
}{
Key1: "value1",
Key2: "value2",
Key3: []int{1, 2},
}),
},
{
Expand Down

0 comments on commit 1d2f58f

Please sign in to comment.