From dcb9c852010ce83b4751f7d0205d4a4fa4ef9b12 Mon Sep 17 00:00:00 2001 From: Pieter Noordhuis Date: Wed, 7 Feb 2024 10:25:07 +0100 Subject: [PATCH] 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. --- libs/dyn/convert/from_typed.go | 5 ----- libs/dyn/convert/from_typed_test.go | 19 +++++++++++++++++++ 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/libs/dyn/convert/from_typed.go b/libs/dyn/convert/from_typed.go index 75f1c721..bd6b6367 100644 --- a/libs/dyn/convert/from_typed.go +++ b/libs/dyn/convert/from_typed.go @@ -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 } diff --git a/libs/dyn/convert/from_typed_test.go b/libs/dyn/convert/from_typed_test.go index d7fa60bb..5fc2b90f 100644 --- a/libs/dyn/convert/from_typed_test.go +++ b/libs/dyn/convert/from_typed_test.go @@ -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) }