Explorar o código

decode: fix pointers and fix null into string

Fixes bug #1133337.
Gustavo Niemeyer %!s(int64=13) %!d(string=hai) anos
pai
achega
50e1b1b133
Modificáronse 2 ficheiros con 17 adicións e 4 borrados
  1. 11 2
      decode.go
  2. 6 2
      decode_test.go

+ 11 - 2
decode.go

@@ -307,8 +307,10 @@ func (d *decoder) scalar(n *node, out reflect.Value) (good bool) {
 	}
 	switch out.Kind() {
 	case reflect.String:
-		out.SetString(n.value)
-		good = true
+		if resolved != nil {
+			out.SetString(n.value)
+			good = true
+		}
 	case reflect.Interface:
 		if resolved == nil {
 			out.Set(reflect.Zero(out.Type()))
@@ -359,6 +361,13 @@ func (d *decoder) scalar(n *node, out reflect.Value) (good bool) {
 		case nil:
 			out.Set(reflect.Zero(out.Type()))
 			good = true
+		default:
+			if out.Type().Elem() == reflect.TypeOf(resolved) {
+				elem := reflect.New(out.Type().Elem())
+				elem.Elem().Set(reflect.ValueOf(resolved))
+				out.Set(elem)
+				good = true
+			}
 		}
 	}
 	return good

+ 6 - 2
decode_test.go

@@ -23,8 +23,8 @@ var unmarshalTests = []struct {
 	{"v: 10", map[string]interface{}{"v": 10}},
 	{"v: 0b10", map[string]interface{}{"v": 2}},
 	{"v: 0xA", map[string]interface{}{"v": 10}},
-	{"v: 4294967296", map[string]interface{}{"v": int64(4294967296)}},
-	{"v: 4294967296", map[string]int64{"v": int64(4294967296)}},
+	{"v: 4294967296", map[string]interface{}{"v": int(4294967296)}},
+	{"v: 4294967296", map[string]int64{"v": 4294967296}},
 	{"v: 0.1", map[string]interface{}{"v": 0.1}},
 	{"v: .1", map[string]interface{}{"v": 0.1}},
 	{"v: .Inf", map[string]interface{}{"v": math.Inf(+1)}},
@@ -122,6 +122,10 @@ var unmarshalTests = []struct {
 			}
 		}{struct{ C int }{1}, struct{ C int }{1}}},
 	{"a: &a [1, 2]\nb: *a", &struct{ B []int }{[]int{1, 2}}},
+
+	// BUG #1133337
+	{"foo: ''", map[string]*string{"foo": new(string)}},
+	{"foo: null", map[string]string{}},
 }
 
 func (s *S) TestUnmarshal(c *C) {