Browse Source

Encode and decode arrays.

Closes #20, #130, #143, #221, #259, #260.
Gustavo Niemeyer 8 năm trước cách đây
mục cha
commit
2aba0a492b
4 tập tin đã thay đổi với 14 bổ sung2 xóa
  1. 7 1
      decode.go
  2. 3 0
      decode_test.go
  3. 1 1
      encode.go
  4. 3 0
      encode_test.go

+ 7 - 1
decode.go

@@ -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
@@ -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)
 	}

+ 3 - 0
decode_test.go

@@ -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},

+ 1 - 1
encode.go

@@ -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 {

+ 3 - 0
encode_test.go

@@ -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"