Skip to content

Commit

Permalink
Merge pull request #81 from k1LoW/empty-slice-and-nil-slice2
Browse files Browse the repository at this point in the history
Encode both empty and nil slices into `[]`
  • Loading branch information
goccy authored Feb 14, 2020
2 parents 609746c + 7286d81 commit fee8ac5
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
6 changes: 5 additions & 1 deletion encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,11 @@ func (e *Encoder) encodeBool(v bool) ast.Node {
}

func (e *Encoder) encodeSlice(value reflect.Value) (ast.Node, error) {
sequence := ast.Sequence(token.New("-", "-", e.pos(e.column)), e.isFlowStyle)
isFlowStyle := e.isFlowStyle
if value.Len() == 0 {
isFlowStyle = true
}
sequence := ast.Sequence(token.New("-", "-", e.pos(e.column)), isFlowStyle)
for i := 0; i < value.Len(); i++ {
node, err := e.encodeValue(value.Index(i), e.column)
if err != nil {
Expand Down
28 changes: 27 additions & 1 deletion encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,24 @@ func TestEncoder(t *testing.T) {
},
},
},

{
"a: 1\nb: []\n",
struct {
A int
B []string
}{
1, ([]string)(nil),
},
},
{
"a: 1\nb: []\n",
struct {
A int
B []string
}{
1, []string{},
},
},
{
"a: b\nc: d\n",
struct {
Expand Down Expand Up @@ -265,6 +282,15 @@ func TestEncoder(t *testing.T) {
B float64 `yaml:"b,omitempty"`
}{1, 0},
},
{
"a: 1\n",
struct {
A int
B []string `yaml:"b,omitempty"`
}{
1, []string{},
},
},

// Flow flag
{
Expand Down

0 comments on commit fee8ac5

Please sign in to comment.