Skip to content

Commit

Permalink
Merge pull request #72 from vimeo/set_slice_mangler_nil_slice_propagate
Browse files Browse the repository at this point in the history
transform: propagate nil slice in SetSliceMangler
  • Loading branch information
dfinkel authored Jan 9, 2023
2 parents c5a7ccf + 4308a15 commit 816cb14
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
2 changes: 1 addition & 1 deletion ez/ez_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ func TestYAMLConfigEnvFlagWithValidatingConfigInitiallyValid(t *testing.T) {
Path: path,
Val1: 189,
Val2: "",
Set: map[string]struct{}{},
Set: map[string]struct{}(nil),
}
populatedConf := view.View()
assert.EqualValues(t, expectedConfig, *populatedConf)
Expand Down
7 changes: 6 additions & 1 deletion transform/set_slice_mangler.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ func (*SetSliceMangler) Mangle(sf reflect.StructField) ([]reflect.StructField, e
// Unmangle turns []T back into a map[T]struct{}. Naturally, deduplication will
// occur.
func (*SetSliceMangler) Unmangle(sf reflect.StructField, vs []FieldValueTuple) (reflect.Value, error) {
if !(sf.Type.Kind() == reflect.Map && sf.Type.Elem() == emptyStructType) {
if sf.Type.Kind() != reflect.Map || sf.Type.Elem() != emptyStructType {
return vs[0].Value, nil
}

Expand All @@ -49,6 +49,11 @@ func (*SetSliceMangler) Unmangle(sf reflect.StructField, vs []FieldValueTuple) (
)
}

// If the slice is nil, return a nil map.
if slice.IsZero() {
return reflect.Zero(sf.Type), nil
}

// slice.Len() could be larger if there are duplicates, but it's likely
// a good place to start.
set := reflect.MakeMapWithSize(sf.Type, slice.Len())
Expand Down
5 changes: 5 additions & 0 deletions transform/set_slice_mangler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,11 @@ func TestSetSliceManglerUnmangle(t *testing.T) {
"baz": {},
},
},
"nil": {
StructFieldType: reflect.TypeOf(map[int]struct{}{}),
SrcValue: []int(nil),
ExpectedMap: map[int]struct{}(nil),
},
}

for name, c := range cases {
Expand Down

0 comments on commit 816cb14

Please sign in to comment.