Skip to content

Commit

Permalink
Make dst slice consistent with the empty src slice. (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
mennanov authored Nov 27, 2022
1 parent 3225841 commit d82c25e
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
4 changes: 4 additions & 0 deletions copy.go
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,10 @@ func structToMap(filter FieldFilter, src interface{}, dst map[string]interface{}
continue
}
var newValue []map[string]interface{}
if srcField.Kind() == reflect.Slice && !srcField.IsNil() {
// If the source slice is not nil then the dst should not be nil either even if the src slice is empty.
newValue = make([]map[string]interface{}, 0, srcField.Len())
}
existingValue, ok := dst[dstName]
if ok {
v := reflect.ValueOf(existingValue)
Expand Down
37 changes: 36 additions & 1 deletion copy_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package fieldmask_utils_test

import (
"encoding/json"
"fmt"
"reflect"
"testing"
Expand Down Expand Up @@ -1990,7 +1991,7 @@ func TestStructToStruct_WithMultiTagComma(t *testing.T) {
}, dst)
}

func TestStructToMap_DiffentTypeWithSameDstKey(t *testing.T) {
func TestStructToMap_DifferentTypeWithSameDstKey(t *testing.T) {
type BB struct {
Field int
}
Expand All @@ -2015,6 +2016,40 @@ func TestStructToMap_DiffentTypeWithSameDstKey(t *testing.T) {
require.Error(t, err)
}

func TestStructToMap_EmptySrcSlice_JsonEncode(t *testing.T) {
type A struct{}
type B struct {
As []*A
}

src := &B{[]*A{}}
dst := make(map[string]interface{})

mask := fieldmask_utils.MaskFromString("As")
err := fieldmask_utils.StructToMap(mask, src, dst)
require.NoError(t, err)

jsonStr, _ := json.Marshal(dst)
assert.Equal(t, string(jsonStr), "{\"As\":[]}")
}

func TestStructToMap_NilSrcSlice_JsonEncode(t *testing.T) {
type A struct{}
type B struct {
As []*A
}

src := &B{}
dst := make(map[string]interface{})

mask := fieldmask_utils.MaskFromString("As")
err := fieldmask_utils.StructToMap(mask, src, dst)
require.NoError(t, err)

jsonStr, _ := json.Marshal(dst)
assert.Equal(t, string(jsonStr), "{\"As\":null}")
}

func TestStructToStruct_CopySlice_WithDiffentAddr_WithDifferentFieldName(t *testing.T) {
type A struct {
Field1 []int
Expand Down

0 comments on commit d82c25e

Please sign in to comment.