Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

part: Fix MarshalYAML on empty maps #67

Merged
merged 1 commit into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
joamaki marked this conversation as resolved.
Show resolved Hide resolved
}
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")
}
Loading