reflect/prototype: avoid unescaping string defaults
According to google.protobuf.FieldDescriptorProto.default_value documentation:
>>>
For strings, contains the default text contents (not escaped in any way).
For bytes, contains the C escaped value. All bytes >= 128 are escaped.
<<<
Thus, use the default value ad-verbatim if the kind is a string.
For the bytes kind, we use the text format hack to unescape the string,
since the text format uses the same unescape syntax as C due to its heritage.
Change-Id: I79e6d4d7e8f0d1ebedccecb9424a49384485589d
Reviewed-on: https://go-review.googlesource.com/138515
Reviewed-by: Damien Neil <dneil@google.com>
diff --git a/reflect/prototype/protofile_desc.go b/reflect/prototype/protofile_desc.go
index 0a2211d..e3df435 100644
--- a/reflect/prototype/protofile_desc.go
+++ b/reflect/prototype/protofile_desc.go
@@ -404,16 +404,16 @@
}
return protoreflect.ValueOf(float64(v)), nil
}
- case protoreflect.StringKind, protoreflect.BytesKind:
- // String values use the same escaping as the text format,
+ case protoreflect.StringKind:
+ // String values are already unescaped and can be used as is.
+ return protoreflect.ValueOf(s), nil
+ case protoreflect.BytesKind:
+ // Bytes values use the same escaping as the text format,
// however they lack the surrounding double quotes.
// TODO: Export unmarshalString in the text package to avoid this hack.
v, err := text.Unmarshal([]byte(`["` + s + `"]:0`))
if err == nil && len(v.Message()) == 1 {
s := v.Message()[0][0].String()
- if k == protoreflect.StringKind {
- return protoreflect.ValueOf(s), nil
- }
return protoreflect.ValueOf([]byte(s)), nil
}
}
diff --git a/reflect/prototype/type_test.go b/reflect/prototype/type_test.go
index b42f503..c5fe70f 100644
--- a/reflect/prototype/type_test.go
+++ b/reflect/prototype/type_test.go
@@ -131,7 +131,7 @@
Number: 1,
Cardinality: pref.Optional,
Kind: pref.StringKind,
- Default: pref.ValueOf("hello"),
+ Default: pref.ValueOf("hello, \"world!\"\n"),
OneofName: "O1",
}, {
Name: "field_two", // "test.B.field_two"
@@ -248,7 +248,7 @@
Number: protoV1.Int32(1),
Label: descriptorV1.FieldDescriptorProto_Label(pref.Optional).Enum(),
Type: descriptorV1.FieldDescriptorProto_Type(pref.StringKind).Enum(),
- DefaultValue: protoV1.String("hello"),
+ DefaultValue: protoV1.String("hello, \"world!\"\n"),
OneofIndex: protoV1.Int32(0),
}, {
Name: protoV1.String("field_two"),
@@ -452,7 +452,7 @@
"Name": pref.Name("field_one"),
"Index": 0,
"JSONName": "fieldOne",
- "Default": "hello",
+ "Default": "hello, \"world!\"\n",
"OneofType": M{"Name": pref.Name("O1"), "IsPlaceholder": false},
},
"ByJSONName:fieldTwo": nil,
@@ -702,7 +702,7 @@
Kind: string
JSONName: "fieldOne"
HasDefault: true
- Default: "hello"
+ Default: "hello, \"world!\"\n"
OneofType: O1
}, {
Name: field_two