Skip to content

Commit

Permalink
Merge pull request #178 from goccy/feature/support-array-to-encode
Browse files Browse the repository at this point in the history
Support encoding for array type
  • Loading branch information
goccy authored Nov 12, 2020
2 parents d7eb565 + e6e2ae4 commit b92080a
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
14 changes: 14 additions & 0 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,8 @@ func (e *Encoder) encodeValue(ctx context.Context, v reflect.Value, column int)
return e.encodeMapSlice(ctx, mapSlice, column)
}
return e.encodeSlice(ctx, v)
case reflect.Array:
return e.encodeArray(ctx, v)
case reflect.Struct:
if v.CanInterface() {
if mapItem, ok := v.Interface().(MapItem); ok {
Expand Down Expand Up @@ -370,6 +372,18 @@ func (e *Encoder) encodeSlice(ctx context.Context, value reflect.Value) (ast.Nod
return sequence, nil
}

func (e *Encoder) encodeArray(ctx context.Context, value reflect.Value) (ast.Node, error) {
sequence := ast.Sequence(token.New("-", "-", e.pos(e.column)), e.isFlowStyle)
for i := 0; i < value.Len(); i++ {
node, err := e.encodeValue(ctx, value.Index(i), e.column)
if err != nil {
return nil, errors.Wrapf(err, "failed to encode value for array")
}
sequence.Values = append(sequence.Values, node)
}
return sequence, nil
}

func (e *Encoder) encodeMapItem(ctx context.Context, item MapItem, column int) (*ast.MappingValueNode, error) {
k := reflect.ValueOf(item.Key)
v := reflect.ValueOf(item.Value)
Expand Down
4 changes: 4 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,10 @@ func TestEncoder(t *testing.T) {
"v:\n- A\n- B\n",
map[string][]string{"v": {"A", "B"}},
},
{
"v:\n- A\n- B\n",
map[string][2]string{"v": {"A", "B"}},
},
{
"a: -\n",
map[string]string{"a": "-"},
Expand Down

0 comments on commit b92080a

Please sign in to comment.