Kaynağa Gözat

Return a descriptive error when a map field has a nil element.

I'm not sure if this matches C++, but it makes sense and otherwise
the output is not decodable by this same package. It also parallels
our rejection of nil elements of a repeated field.
David Symonds 10 yıl önce
ebeveyn
işleme
cab84a3485
2 değiştirilmiş dosya ile 17 ekleme ve 0 silme
  1. 12 0
      proto/all_test.go
  2. 5 0
      proto/encode.go

+ 12 - 0
proto/all_test.go

@@ -1925,6 +1925,18 @@ func TestMapFieldRoundTrips(t *testing.T) {
 	}
 }
 
+func TestMapFieldWithNil(t *testing.T) {
+	m := &MessageWithMap{
+		MsgMapping: map[int64]*FloatingPoint{
+			1: nil,
+		},
+	}
+	b, err := Marshal(m)
+	if err == nil {
+		t.Fatalf("Marshal of bad map should have failed, got these bytes: %v", b)
+	}
+}
+
 // Benchmarks
 
 func testMsg() *GoTest {

+ 5 - 0
proto/encode.go

@@ -1106,6 +1106,11 @@ func (o *Buffer) enc_new_map(p *Properties, base structPointer) error {
 	for _, key := range keys {
 		val := v.MapIndex(key)
 
+		// The only illegal map entry values are nil message pointers.
+		if val.Kind() == reflect.Ptr && val.IsNil() {
+			return errors.New("proto: map has nil element")
+		}
+
 		keycopy.Set(key)
 		valcopy.Set(val)