فهرست منبع

marshal top level nil correctly

Roger Peppe 11 سال پیش
والد
کامیت
5206f6dd03
4فایلهای تغییر یافته به همراه11 افزوده شده و 4 حذف شده
  1. 1 1
      decode.go
  2. 1 1
      decode_test.go
  3. 4 0
      encode.go
  4. 5 2
      encode_test.go

+ 1 - 1
decode.go

@@ -516,7 +516,7 @@ func (d *decoder) merge(n *node, out reflect.Value) {
 		d.unmarshal(n, out)
 	case sequenceNode:
 		// Step backwards as earlier nodes take precedence.
-		for i := len(n.children)-1; i >= 0; i-- {
+		for i := len(n.children) - 1; i >= 0; i-- {
 			ni := n.children[i]
 			if ni.kind == aliasNode {
 				an, ok := d.doc.anchors[ni.value]

+ 1 - 1
decode_test.go

@@ -372,7 +372,7 @@ var unmarshalTests = []struct {
 		map[string]time.Duration{"a": 3 * time.Second},
 	},
 
-	// Issue #24. 
+	// Issue #24.
 	{
 		"a: <foo>",
 		map[string]string{"a": "<foo>"},

+ 4 - 0
encode.go

@@ -56,6 +56,10 @@ func (e *encoder) must(ok bool) {
 
 func (e *encoder) marshal(tag string, in reflect.Value) {
 	var value interface{}
+	if !in.IsValid() {
+		e.nilv()
+		return
+	}
 	if getter, ok := in.Interface().(Getter); ok {
 		tag, value = getter.GetYAML()
 		if value == nil {

+ 5 - 2
encode_test.go

@@ -2,8 +2,8 @@ package yaml_test
 
 import (
 	"fmt"
-	"gopkg.in/yaml.v1"
 	. "gopkg.in/check.v1"
+	"gopkg.in/yaml.v1"
 	"math"
 	"strconv"
 	"strings"
@@ -17,6 +17,9 @@ var marshalTests = []struct {
 	data  string
 }{
 	{
+		nil,
+		"null\n",
+	}, {
 		&struct{}{},
 		"{}\n",
 	}, {
@@ -220,7 +223,7 @@ var marshalTests = []struct {
 		"a: 3s\n",
 	},
 
-	// Issue #24. 
+	// Issue #24.
 	{
 		map[string]string{"a": "<foo>"},
 		"a: <foo>\n",