Skip to content

Commit

Permalink
part: Fix MarshalYAML on empty maps
Browse files Browse the repository at this point in the history
MarshalYAML nil deref'd the 'm.tree' when the map was empty.
Fix this and extend test coverage.

Signed-off-by: Jussi Maki <jussi.maki@isovalent.com>
  • Loading branch information
joamaki committed Nov 8, 2024
1 parent ddc4f15 commit ce7e907
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
8 changes: 5 additions & 3 deletions part/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,9 +243,11 @@ func (m *Map[K, V]) UnmarshalJSON(data []byte) error {

func (m Map[K, V]) MarshalYAML() (any, error) {
kvs := make([]mapKVPair[K, V], 0, m.Len())
iter := m.tree.Iterator()
for _, kv, ok := iter.Next(); ok; _, kv, ok = iter.Next() {
kvs = append(kvs, kv)
if m.tree != nil {
iter := m.tree.Iterator()
for _, kv, ok := iter.Next(); ok; _, kv, ok = iter.Next() {
kvs = append(kvs, kv)
}
}
return kvs, nil
}
Expand Down
8 changes: 7 additions & 1 deletion part/map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,10 +176,16 @@ func TestMapJSON(t *testing.T) {

func TestMapYAMLStringKey(t *testing.T) {
var m part.Map[string, int]
m = m.Set("foo", 1).Set("bar", 2).Set("baz", 3)

bs, err := yaml.Marshal(m)
require.NoError(t, err, "Marshal")
require.Equal(t, "[]\n", string(bs))

m = m.Set("foo", 1).Set("bar", 2).Set("baz", 3)

bs, err = yaml.Marshal(m)
require.NoError(t, err, "Marshal")
require.Equal(t, "- k: bar\n v: 2\n- k: baz\n v: 3\n- k: foo\n v: 1\n", string(bs))

var m2 part.Map[string, int]
err = yaml.Unmarshal(bs, &m2)
Expand Down
7 changes: 7 additions & 0 deletions part/set_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,16 @@ func TestSetYAML(t *testing.T) {

bs, err := yaml.Marshal(s)
require.NoError(t, err, "Marshal")
require.Equal(t, "- bar\n- baz\n- foo\n", string(bs))

var s2 part.Set[string]
err = yaml.Unmarshal(bs, &s2)
require.NoError(t, err, "Unmarshal")
require.True(t, s.Equal(s2), "Equal")

var empty part.Set[string]
bs, err = yaml.Marshal(empty)
require.NoError(t, err, "Unmarshal")
require.Equal(t, "[]\n", string(bs))
require.True(t, s.Equal(s2), "Equal")
}

0 comments on commit ce7e907

Please sign in to comment.