diff --git a/part/map.go b/part/map.go index 70d0b07..f3d0455 100644 --- a/part/map.go +++ b/part/map.go @@ -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 } diff --git a/part/map_test.go b/part/map_test.go index 4c61c38..97e6554 100644 --- a/part/map_test.go +++ b/part/map_test.go @@ -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) diff --git a/part/set_test.go b/part/set_test.go index eff33b5..c922edb 100644 --- a/part/set_test.go +++ b/part/set_test.go @@ -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") }