Empty struct should yield empty map in `convert.FromTyped` (#1177)

## Changes

This was an issue in cases where the typed structure contains a non-nil
pointer to an empty struct. After conversion to a `dyn.Value` and back
to the typed structure, the pointer became nil.

## Tests

Unit tests.
This commit is contained in:
Pieter Noordhuis 2024-02-07 10:25:07 +01:00 committed by GitHub
parent 6e075e8cf8
commit dcb9c85201
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 19 additions and 5 deletions

View File

@ -84,11 +84,6 @@ func fromTypedStruct(src reflect.Value, ref dyn.Value) (dyn.Value, error) {
}
}
// If the struct was equal to its zero value, emit a nil.
if len(out) == 0 {
return dyn.NilValue, nil
}
return dyn.NewValue(out, ref.Location()), nil
}

View File

@ -19,6 +19,25 @@ func TestFromTypedStructZeroFields(t *testing.T) {
nv, err := FromTyped(src, ref)
require.NoError(t, err)
assert.Equal(t, dyn.V(map[string]dyn.Value{}), nv)
}
func TestFromTypedStructPointerZeroFields(t *testing.T) {
type Tmp struct {
Foo string `json:"foo"`
Bar string `json:"bar"`
}
// For an initialized pointer we expect an empty map.
src := &Tmp{}
nv, err := FromTyped(src, dyn.NilValue)
require.NoError(t, err)
assert.Equal(t, dyn.V(map[string]dyn.Value{}), nv)
// For a nil pointer we expect nil.
src = nil
nv, err = FromTyped(src, dyn.NilValue)
require.NoError(t, err)
assert.Equal(t, dyn.NilValue, nv)
}