Skip to content

Commit

Permalink
Encode and decode arrays.
Browse files Browse the repository at this point in the history
Closes #20, #130, #143, #221, #259, #260.
  • Loading branch information
niemeyer committed Mar 26, 2018
1 parent 7b8fd2d commit 2aba0a4
Show file tree
Hide file tree
Showing 4 changed files with 14 additions and 2 deletions.
8 changes: 7 additions & 1 deletion decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,10 @@ func (d *decoder) sequence(n *node, out reflect.Value) (good bool) {
switch out.Kind() {
case reflect.Slice:
out.Set(reflect.MakeSlice(out.Type(), l, l))
case reflect.Array:
if l != out.Len() {
failf("invalid array: want %d elements but got %d", out.Len(), l)
}
case reflect.Interface:
// No type hints. Will have to use a generic sequence.
iface = out
Expand All @@ -560,7 +564,9 @@ func (d *decoder) sequence(n *node, out reflect.Value) (good bool) {
j++
}
}
out.Set(out.Slice(0, j))
if out.Kind() != reflect.Array {
out.Set(out.Slice(0, j))
}
if iface.IsValid() {
iface.Set(out)
}
Expand Down
3 changes: 3 additions & 0 deletions decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,9 @@ var unmarshalTests = []struct {
}, {
"a: [1, 2]",
&struct{ A []int }{[]int{1, 2}},
}, {
"a: [1, 2]",
&struct{ A [2]int }{[2]int{1, 2}},
}, {
"a: 1",
&struct{ B int }{0},
Expand Down
2 changes: 1 addition & 1 deletion encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ func (e *encoder) marshal(tag string, in reflect.Value) {
} else {
e.structv(tag, in)
}
case reflect.Slice:
case reflect.Slice, reflect.Array:
if in.Type().Elem() == mapItemType {
e.itemsv(tag, in)
} else {
Expand Down
3 changes: 3 additions & 0 deletions encode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,9 @@ var marshalTests = []struct {
}, {
&struct{ A []int }{[]int{1, 2}},
"a:\n- 1\n- 2\n",
}, {
&struct{ A [2]int }{[2]int{1, 2}},
"a:\n- 1\n- 2\n",
}, {
&struct {
B int "a"
Expand Down

0 comments on commit 2aba0a4

Please sign in to comment.