From b80cc536dedaacf250bc81f499429692c6448471 Mon Sep 17 00:00:00 2001 From: Mike Kruskal Date: Tue, 17 Jan 2023 12:17:58 -0800 Subject: [PATCH] Migrate std::operator+ to Abseil helpers in utility code. This also opportunistically migrates many C-style and STL strings to string_view in touched code. PiperOrigin-RevId: 502655455 --- conformance/binary_json_conformance_suite.cc | 1905 +++++++---------- conformance/text_format_conformance_suite.cc | 26 +- .../protobuf/io/zero_copy_stream_unittest.cc | 32 +- src/google/protobuf/testing/file.cc | 8 +- src/google/protobuf/testing/googletest.cc | 20 +- src/google/protobuf/util/field_mask_util.cc | 61 +- .../util/message_differencer_unittest.cc | 19 +- src/google/protobuf/util/time_util.cc | 28 +- src/google/protobuf/util/time_util.h | 4 +- .../protobuf/util/type_resolver_util.cc | 26 +- src/google/protobuf/util/type_resolver_util.h | 4 +- 11 files changed, 955 insertions(+), 1178 deletions(-) diff --git a/conformance/binary_json_conformance_suite.cc b/conformance/binary_json_conformance_suite.cc index a915c29263..c4fb3d057b 100644 --- a/conformance/binary_json_conformance_suite.cc +++ b/conformance/binary_json_conformance_suite.cc @@ -30,6 +30,11 @@ #include "binary_json_conformance_suite.h" +#include +#include +#include +#include + #include "google/protobuf/text_format.h" #include "google/protobuf/util/json_util.h" #include "google/protobuf/util/type_resolver_util.h" @@ -52,7 +57,6 @@ using conformance::WireFormat; using google::protobuf::Descriptor; using google::protobuf::FieldDescriptor; using google::protobuf::Message; -using google::protobuf::TextFormat; using google::protobuf::internal::WireFormatLite; using google::protobuf::util::NewTypeResolverForDescriptorPool; using proto2_messages::TestAllTypesProto2; @@ -61,14 +65,14 @@ using std::string; namespace { -static const char kTypeUrlPrefix[] = "type.googleapis.com"; +constexpr absl::string_view kTypeUrlPrefix = "type.googleapis.com"; // The number of repetitions to use for performance tests. // Corresponds approx to 500KB wireformat bytes. -static const size_t kPerformanceRepeatCount = 50000; +const size_t kPerformanceRepeatCount = 50000; -static string GetTypeUrl(const Descriptor* message) { - return string(kTypeUrlPrefix) + "/" + message->full_name(); +string GetTypeUrl(const Descriptor* message) { + return absl::StrCat(kTypeUrlPrefix, "/", message->full_name()); } /* Routines for building arbitrary protos *************************************/ @@ -76,42 +80,14 @@ static string GetTypeUrl(const Descriptor* message) { // We would use CodedOutputStream except that we want more freedom to build // arbitrary protos (even invalid ones). -const string empty; - -string cat(const string& a, const string& b, - const string& c = empty, - const string& d = empty, - const string& e = empty, - const string& f = empty, - const string& g = empty, - const string& h = empty, - const string& i = empty, - const string& j = empty, - const string& k = empty, - const string& l = empty) { - string ret; - ret.reserve(a.size() + b.size() + c.size() + d.size() + e.size() + f.size() + - g.size() + h.size() + i.size() + j.size() + k.size() + l.size()); - ret.append(a); - ret.append(b); - ret.append(c); - ret.append(d); - ret.append(e); - ret.append(f); - ret.append(g); - ret.append(h); - ret.append(i); - ret.append(j); - ret.append(k); - ret.append(l); - return ret; -} - // The maximum number of bytes that it takes to encode a 64-bit varint. #define VARINT_MAX_LEN 10 -size_t vencode64(uint64_t val, int over_encoded_bytes, char *buf) { - if (val == 0) { buf[0] = 0; return 1; } +size_t vencode64(uint64_t val, int over_encoded_bytes, char* buf) { + if (val == 0) { + buf[0] = 0; + return 1; + } size_t i = 0; while (val) { uint8_t byte = val & 0x7fU; @@ -142,10 +118,12 @@ string longvarint(uint64_t x, int extra) { } // TODO: proper byte-swapping for big-endian machines. -string fixed32(void *data) { return string(static_cast(data), 4); } -string fixed64(void *data) { return string(static_cast(data), 8); } +string fixed32(void* data) { return string(static_cast(data), 4); } +string fixed64(void* data) { return string(static_cast(data), 8); } -string delim(const string& buf) { return cat(varint(buf.size()), buf); } +string delim(const string& buf) { + return absl::StrCat(varint(buf.size()), buf); +} string u32(uint32_t u32) { return fixed32(&u32); } string u64(uint64_t u64) { return fixed64(&u64); } string flt(float f) { return fixed32(&f); } @@ -157,6 +135,10 @@ string tag(uint32_t fieldnum, char wire_type) { return varint((fieldnum << 3) | wire_type); } +string tag(int fieldnum, char wire_type) { + return tag(static_cast(fieldnum), wire_type); +} + string GetDefaultValue(FieldDescriptor::Type type) { switch (type) { case FieldDescriptor::TYPE_INT32: @@ -217,7 +199,8 @@ string GetNonDefaultValue(FieldDescriptor::Type type) { case FieldDescriptor::TYPE_BYTES: return delim("a"); case FieldDescriptor::TYPE_MESSAGE: - return delim(cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1234))); + return delim( + absl::StrCat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1234))); default: return ""; } @@ -235,8 +218,8 @@ enum class Packed { const FieldDescriptor* GetFieldForType(FieldDescriptor::Type type, bool repeated, bool is_proto3, Packed packed = Packed::kUnspecified) { - const Descriptor* d = is_proto3 ? - TestAllTypesProto3().GetDescriptor() : TestAllTypesProto2().GetDescriptor(); + const Descriptor* d = is_proto3 ? TestAllTypesProto3().GetDescriptor() + : TestAllTypesProto2().GetDescriptor(); for (int i = 0; i < d->field_count(); i++) { const FieldDescriptor* f = d->field(i); if (f->type() == type && f->is_repeated() == repeated) { @@ -248,19 +231,19 @@ const FieldDescriptor* GetFieldForType(FieldDescriptor::Type type, } } - string packed_string = ""; - const string repeated_string = repeated ? "Repeated " : "Singular "; - const string proto_string = is_proto3 ? "Proto3" : "Proto2"; + absl::string_view packed_string = ""; + const absl::string_view repeated_string = + repeated ? "Repeated " : "Singular "; + const absl::string_view proto_string = is_proto3 ? "Proto3" : "Proto2"; if (packed == Packed::kTrue) { packed_string = "Packed "; } if (packed == Packed::kFalse) { packed_string = "Unpacked "; } - GOOGLE_ABSL_LOG(FATAL) << "Couldn't find field with type: " - << repeated_string.c_str() << packed_string.c_str() - << FieldDescriptor::TypeName(type) << " for " - << proto_string.c_str(); + GOOGLE_ABSL_LOG(FATAL) << "Couldn't find field with type: " << repeated_string + << packed_string << FieldDescriptor::TypeName(type) << " for " + << proto_string; return nullptr; } @@ -281,11 +264,11 @@ const FieldDescriptor* GetFieldForMapType(FieldDescriptor::Type key_type, } } - const string proto_string = is_proto3 ? "Proto3" : "Proto2"; + const absl::string_view proto_string = is_proto3 ? "Proto3" : "Proto2"; GOOGLE_ABSL_LOG(FATAL) << "Couldn't find map field with type: " << FieldDescriptor::TypeName(key_type) << " and " << FieldDescriptor::TypeName(key_type) << " for " - << proto_string.c_str(); + << proto_string; return nullptr; } @@ -301,10 +284,9 @@ const FieldDescriptor* GetFieldForOneofType(FieldDescriptor::Type type, } } - const string proto_string = is_proto3 ? "Proto3" : "Proto2"; + const absl::string_view proto_string = is_proto3 ? "Proto3" : "Proto2"; GOOGLE_ABSL_LOG(FATAL) << "Couldn't find oneof field with type: " - << FieldDescriptor::TypeName(type) << " for " - << proto_string.c_str(); + << FieldDescriptor::TypeName(type) << " for " << proto_string; return nullptr; } @@ -318,9 +300,9 @@ string UpperCase(string str) { std::unique_ptr NewTestMessage(bool is_proto3) { std::unique_ptr prototype; if (is_proto3) { - prototype.reset(new TestAllTypesProto3()); + prototype = std::make_unique(); } else { - prototype.reset(new TestAllTypesProto2()); + prototype = std::make_unique(); } return prototype; } @@ -360,8 +342,7 @@ namespace google { namespace protobuf { bool BinaryAndJsonConformanceSuite::ParseJsonResponse( - const ConformanceResponse& response, - Message* test_message) { + const ConformanceResponse& response, Message* test_message) { string binary_protobuf; absl::Status status = JsonToBinaryString(type_resolver_.get(), type_url_, @@ -382,8 +363,7 @@ bool BinaryAndJsonConformanceSuite::ParseJsonResponse( bool BinaryAndJsonConformanceSuite::ParseResponse( const ConformanceResponse& response, - const ConformanceRequestSetting& setting, - Message* test_message) { + const ConformanceRequestSetting& setting, Message* test_message) { const ConformanceRequest& request = setting.GetRequest(); WireFormat requested_output = request.requested_output_format(); const string& test_name = setting.GetTestName(); @@ -395,14 +375,13 @@ bool BinaryAndJsonConformanceSuite::ParseResponse( ReportFailure(test_name, level, request, response, absl::StrCat("Test was asked for ", WireFormatToString(requested_output), - " output but provided PROTOBUF instead.") - .c_str()); + " output but provided PROTOBUF instead.")); return false; } if (!test_message->ParseFromString(response.protobuf_payload())) { ReportFailure(test_name, level, request, response, - "Protobuf output we received from test was unparseable."); + "Protobuf output we received from test was unparseable."); return false; } @@ -414,8 +393,7 @@ bool BinaryAndJsonConformanceSuite::ParseResponse( ReportFailure(test_name, level, request, response, absl::StrCat("Test was asked for ", WireFormatToString(requested_output), - " output but provided JSON instead.") - .c_str()); + " output but provided JSON instead.")); return false; } @@ -436,7 +414,7 @@ bool BinaryAndJsonConformanceSuite::ParseResponse( return true; } -void BinaryAndJsonConformanceSuite::ExpectParseFailureForProtoWithProtoVersion ( +void BinaryAndJsonConformanceSuite::ExpectParseFailureForProtoWithProtoVersion( const string& proto, const string& test_name, ConformanceLevel level, bool is_proto3) { std::unique_ptr prototype = NewTestMessage(is_proto3); @@ -444,8 +422,7 @@ void BinaryAndJsonConformanceSuite::ExpectParseFailureForProtoWithProtoVersion ( // we let it send its response as this. We must not leave it unspecified. ConformanceRequestSetting setting( level, conformance::PROTOBUF, conformance::PROTOBUF, - conformance::BINARY_TEST, - *prototype, test_name, proto); + conformance::BINARY_TEST, *prototype, test_name, proto); const ConformanceRequest& request = setting.GetRequest(); ConformanceResponse response; @@ -505,23 +482,20 @@ void BinaryAndJsonConformanceSuite::RunValidJsonTestWithMessage( const string& test_name, ConformanceLevel level, const string& input_json, const string& equivalent_text_format, const Message& prototype) { ConformanceRequestSetting setting1( - level, conformance::JSON, conformance::PROTOBUF, - conformance::JSON_TEST, + level, conformance::JSON, conformance::PROTOBUF, conformance::JSON_TEST, prototype, test_name, input_json); RunValidInputTest(setting1, equivalent_text_format); - ConformanceRequestSetting setting2( - level, conformance::JSON, conformance::JSON, - conformance::JSON_TEST, - prototype, test_name, input_json); + ConformanceRequestSetting setting2(level, conformance::JSON, + conformance::JSON, conformance::JSON_TEST, + prototype, test_name, input_json); RunValidInputTest(setting2, equivalent_text_format); } void BinaryAndJsonConformanceSuite::RunValidJsonTestWithProtobufInput( - const string& test_name, ConformanceLevel level, const TestAllTypesProto3& input, - const string& equivalent_text_format) { + const string& test_name, ConformanceLevel level, + const TestAllTypesProto3& input, const string& equivalent_text_format) { ConformanceRequestSetting setting( - level, conformance::PROTOBUF, conformance::JSON, - conformance::JSON_TEST, + level, conformance::PROTOBUF, conformance::JSON, conformance::JSON_TEST, input, test_name, input.SerializeAsString()); RunValidInputTest(setting, equivalent_text_format); } @@ -532,8 +506,8 @@ void BinaryAndJsonConformanceSuite::RunValidJsonIgnoreUnknownTest( TestAllTypesProto3 prototype; ConformanceRequestSetting setting( level, conformance::JSON, conformance::PROTOBUF, - conformance::JSON_IGNORE_UNKNOWN_PARSING_TEST, - prototype, test_name, input_json); + conformance::JSON_IGNORE_UNKNOWN_PARSING_TEST, prototype, test_name, + input_json); RunValidInputTest(setting, equivalent_text_format); } @@ -545,15 +519,13 @@ void BinaryAndJsonConformanceSuite::RunValidProtobufTest( ConformanceRequestSetting setting1( level, conformance::PROTOBUF, conformance::PROTOBUF, - conformance::BINARY_TEST, - *prototype, test_name, input_protobuf); + conformance::BINARY_TEST, *prototype, test_name, input_protobuf); RunValidInputTest(setting1, equivalent_text_format); if (is_proto3) { ConformanceRequestSetting setting2( level, conformance::PROTOBUF, conformance::JSON, - conformance::BINARY_TEST, - *prototype, test_name, input_protobuf); + conformance::BINARY_TEST, *prototype, test_name, input_protobuf); RunValidInputTest(setting2, equivalent_text_format); } } @@ -572,15 +544,14 @@ void BinaryAndJsonConformanceSuite::RunValidBinaryProtobufTest( std::unique_ptr prototype = NewTestMessage(is_proto3); ConformanceRequestSetting setting( level, conformance::PROTOBUF, conformance::PROTOBUF, - conformance::BINARY_TEST, - *prototype, test_name, input_protobuf); + conformance::BINARY_TEST, *prototype, test_name, input_protobuf); RunValidBinaryInputTest(setting, expected_protobuf, true); } void BinaryAndJsonConformanceSuite::RunBinaryPerformanceMergeMessageWithField( const string& test_name, const string& field_proto, bool is_proto3) { string message_tag = tag(27, WireFormatLite::WIRETYPE_LENGTH_DELIMITED); - string message_proto = cat(message_tag, delim(field_proto)); + string message_proto = absl::StrCat(message_tag, delim(field_proto)); string proto; for (size_t i = 0; i < kPerformanceRepeatCount; i++) { @@ -592,14 +563,14 @@ void BinaryAndJsonConformanceSuite::RunBinaryPerformanceMergeMessageWithField( multiple_repeated_field_proto.append(field_proto); } string expected_proto = - cat(message_tag, delim(multiple_repeated_field_proto)); + absl::StrCat(message_tag, delim(multiple_repeated_field_proto)); RunValidBinaryProtobufTest(test_name, RECOMMENDED, proto, expected_proto, is_proto3); } void BinaryAndJsonConformanceSuite::RunValidProtobufTestWithMessage( - const string& test_name, ConformanceLevel level, const Message *input, + const string& test_name, ConformanceLevel level, const Message* input, const string& equivalent_text_format, bool is_proto3) { RunValidProtobufTest(test_name, level, input->SerializeAsString(), equivalent_text_format, is_proto3); @@ -658,10 +629,9 @@ void BinaryAndJsonConformanceSuite::ExpectParseFailureForJson( TestAllTypesProto3 prototype; // We don't expect output, but if the program erroneously accepts the protobuf // we let it send its response as this. We must not leave it unspecified. - ConformanceRequestSetting setting( - level, conformance::JSON, conformance::JSON, - conformance::JSON_TEST, - prototype, test_name, input_json); + ConformanceRequestSetting setting(level, conformance::JSON, conformance::JSON, + conformance::JSON_TEST, prototype, + test_name, input_json); const ConformanceRequest& request = setting.GetRequest(); ConformanceResponse response; string effective_test_name = absl::StrCat( @@ -679,15 +649,15 @@ void BinaryAndJsonConformanceSuite::ExpectParseFailureForJson( } void BinaryAndJsonConformanceSuite::ExpectSerializeFailureForJson( - const string& test_name, ConformanceLevel level, const string& text_format) { + const string& test_name, ConformanceLevel level, + const string& text_format) { TestAllTypesProto3 payload_message; GOOGLE_ABSL_CHECK(TextFormat::ParseFromString(text_format, &payload_message)) << "Failed to parse: " << text_format; TestAllTypesProto3 prototype; ConformanceRequestSetting setting( - level, conformance::PROTOBUF, conformance::JSON, - conformance::JSON_TEST, + level, conformance::PROTOBUF, conformance::JSON, conformance::JSON_TEST, prototype, test_name, payload_message.SerializeAsString()); const ConformanceRequest& request = setting.GetRequest(); ConformanceResponse response; @@ -708,88 +678,97 @@ void BinaryAndJsonConformanceSuite::ExpectSerializeFailureForJson( void BinaryAndJsonConformanceSuite::TestPrematureEOFForType( FieldDescriptor::Type type) { // Incomplete values for each wire type. - static const string incompletes[6] = { - string("\x80"), // VARINT - string("abcdefg"), // 64BIT - string("\x80"), // DELIMITED (partial length) - string(), // START_GROUP (no value required) - string(), // END_GROUP (no value required) - string("abc") // 32BIT + static constexpr absl::string_view incompletes[6] = { + "\x80", // VARINT + "abcdefg", // 64BIT + "\x80", // DELIMITED (partial length) + "", // START_GROUP (no value required) + "", // END_GROUP (no value required) + "abc" // 32BIT }; const FieldDescriptor* field = GetFieldForType(type, false, true); const FieldDescriptor* rep_field = GetFieldForType(type, true, true); WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType( static_cast(type)); - const string& incomplete = incompletes[wire_type]; + absl::string_view incomplete = incompletes[wire_type]; const string type_name = - UpperCase(string(".") + FieldDescriptor::TypeName(type)); + UpperCase(absl::StrCat(".", FieldDescriptor::TypeName(type))); ExpectParseFailureForProto( tag(field->number(), wire_type), - "PrematureEofBeforeKnownNonRepeatedValue" + type_name, REQUIRED); + absl::StrCat("PrematureEofBeforeKnownNonRepeatedValue", type_name), + REQUIRED); ExpectParseFailureForProto( tag(rep_field->number(), wire_type), - "PrematureEofBeforeKnownRepeatedValue" + type_name, REQUIRED); + absl::StrCat("PrematureEofBeforeKnownRepeatedValue", type_name), + REQUIRED); ExpectParseFailureForProto( tag(UNKNOWN_FIELD, wire_type), - "PrematureEofBeforeUnknownValue" + type_name, REQUIRED); + absl::StrCat("PrematureEofBeforeUnknownValue", type_name), REQUIRED); ExpectParseFailureForProto( - cat( tag(field->number(), wire_type), incomplete ), - "PrematureEofInsideKnownNonRepeatedValue" + type_name, REQUIRED); + absl::StrCat(tag(field->number(), wire_type), incomplete), + absl::StrCat("PrematureEofInsideKnownNonRepeatedValue", type_name), + REQUIRED); ExpectParseFailureForProto( - cat( tag(rep_field->number(), wire_type), incomplete ), - "PrematureEofInsideKnownRepeatedValue" + type_name, REQUIRED); + absl::StrCat(tag(rep_field->number(), wire_type), incomplete), + absl::StrCat("PrematureEofInsideKnownRepeatedValue", type_name), + REQUIRED); ExpectParseFailureForProto( - cat( tag(UNKNOWN_FIELD, wire_type), incomplete ), - "PrematureEofInsideUnknownValue" + type_name, REQUIRED); + absl::StrCat(tag(UNKNOWN_FIELD, wire_type), incomplete), + absl::StrCat("PrematureEofInsideUnknownValue", type_name), REQUIRED); if (wire_type == WireFormatLite::WIRETYPE_LENGTH_DELIMITED) { ExpectParseFailureForProto( - cat( tag(field->number(), wire_type), varint(1) ), - "PrematureEofInDelimitedDataForKnownNonRepeatedValue" + type_name, + absl::StrCat(tag(field->number(), wire_type), varint(1)), + absl::StrCat("PrematureEofInDelimitedDataForKnownNonRepeatedValue", + type_name), REQUIRED); ExpectParseFailureForProto( - cat( tag(rep_field->number(), wire_type), varint(1) ), - "PrematureEofInDelimitedDataForKnownRepeatedValue" + type_name, + absl::StrCat(tag(rep_field->number(), wire_type), varint(1)), + absl::StrCat("PrematureEofInDelimitedDataForKnownRepeatedValue", + type_name), REQUIRED); // EOF in the middle of delimited data for unknown value. ExpectParseFailureForProto( - cat( tag(UNKNOWN_FIELD, wire_type), varint(1) ), - "PrematureEofInDelimitedDataForUnknownValue" + type_name, REQUIRED); + absl::StrCat(tag(UNKNOWN_FIELD, wire_type), varint(1)), + absl::StrCat("PrematureEofInDelimitedDataForUnknownValue", type_name), + REQUIRED); if (type == FieldDescriptor::TYPE_MESSAGE) { // Submessage ends in the middle of a value. - string incomplete_submsg = - cat( tag(WireFormatLite::TYPE_INT32, WireFormatLite::WIRETYPE_VARINT), - incompletes[WireFormatLite::WIRETYPE_VARINT] ); + string incomplete_submsg = absl::StrCat( + tag(WireFormatLite::TYPE_INT32, WireFormatLite::WIRETYPE_VARINT), + incompletes[WireFormatLite::WIRETYPE_VARINT]); ExpectHardParseFailureForProto( - cat( tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - varint(incomplete_submsg.size()), - incomplete_submsg ), - "PrematureEofInSubmessageValue" + type_name, REQUIRED); + absl::StrCat( + tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + varint(incomplete_submsg.size()), incomplete_submsg), + absl::StrCat("PrematureEofInSubmessageValue", type_name), REQUIRED); } } else if (type != FieldDescriptor::TYPE_GROUP) { // Non-delimited, non-group: eligible for packing. // Packed region ends in the middle of a value. ExpectHardParseFailureForProto( - cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + absl::StrCat( + tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), varint(incomplete.size()), incomplete), - "PrematureEofInPackedFieldValue" + type_name, REQUIRED); + absl::StrCat("PrematureEofInPackedFieldValue", type_name), REQUIRED); // EOF in the middle of packed region. ExpectParseFailureForProto( - cat(tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + absl::StrCat( + tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), varint(1)), - "PrematureEofInPackedField" + type_name, REQUIRED); + absl::StrCat("PrematureEofInPackedField", type_name), REQUIRED); } } @@ -798,7 +777,7 @@ void BinaryAndJsonConformanceSuite::TestValidDataForType( std::vector> values) { for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) { const string type_name = - UpperCase(string(".") + FieldDescriptor::TypeName(type)); + UpperCase(absl::StrCat(".", FieldDescriptor::TypeName(type))); WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType( static_cast(type)); const FieldDescriptor* field = GetFieldForType(type, false, is_proto3); @@ -806,12 +785,13 @@ void BinaryAndJsonConformanceSuite::TestValidDataForType( // Test singular data for singular fields. for (size_t i = 0; i < values.size(); i++) { - string proto = cat(tag(field->number(), wire_type), values[i].first); + string proto = + absl::StrCat(tag(field->number(), wire_type), values[i].first); // In proto3, default primitive fields should not be encoded. string expected_proto = is_proto3 && IsProto3Default(field->type(), values[i].second) ? "" - : cat(tag(field->number(), wire_type), values[i].second); + : absl::StrCat(tag(field->number(), wire_type), values[i].second); std::unique_ptr test_message = NewTestMessage(is_proto3); test_message->MergeFromString(expected_proto); string text; @@ -831,17 +811,17 @@ void BinaryAndJsonConformanceSuite::TestValidDataForType( if (type != FieldDescriptor::TYPE_MESSAGE) { string proto; for (size_t i = 0; i < values.size(); i++) { - proto += cat(tag(field->number(), wire_type), values[i].first); + proto += absl::StrCat(tag(field->number(), wire_type), values[i].first); } string expected_proto = - cat(tag(field->number(), wire_type), values.back().second); + absl::StrCat(tag(field->number(), wire_type), values.back().second); std::unique_ptr test_message = NewTestMessage(is_proto3); test_message->MergeFromString(expected_proto); string text; TextFormat::PrintToString(*test_message, &text); - RunValidProtobufTest("RepeatedScalarSelectsLast" + type_name, REQUIRED, - proto, text, is_proto3); + RunValidProtobufTest(absl::StrCat("RepeatedScalarSelectsLast", type_name), + REQUIRED, proto, text, is_proto3); } // Test repeated fields. @@ -864,38 +844,39 @@ void BinaryAndJsonConformanceSuite::TestValidDataForType( for (size_t i = 0; i < values.size(); i++) { default_proto_unpacked += - cat(tag(rep_field->number(), wire_type), values[i].first); + absl::StrCat(tag(rep_field->number(), wire_type), values[i].first); default_proto_unpacked_expected += - cat(tag(rep_field->number(), wire_type), values[i].second); + absl::StrCat(tag(rep_field->number(), wire_type), values[i].second); default_proto_packed += values[i].first; default_proto_packed_expected += values[i].second; - packed_proto_unpacked += - cat(tag(packed_field->number(), wire_type), values[i].first); + packed_proto_unpacked += absl::StrCat( + tag(packed_field->number(), wire_type), values[i].first); packed_proto_packed += values[i].first; packed_proto_expected += values[i].second; - unpacked_proto_unpacked += - cat(tag(unpacked_field->number(), wire_type), values[i].first); + unpacked_proto_unpacked += absl::StrCat( + tag(unpacked_field->number(), wire_type), values[i].first); unpacked_proto_packed += values[i].first; - unpacked_proto_expected += - cat(tag(unpacked_field->number(), wire_type), values[i].second); + unpacked_proto_expected += absl::StrCat( + tag(unpacked_field->number(), wire_type), values[i].second); } - default_proto_packed = cat( + default_proto_packed = absl::StrCat( tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), delim(default_proto_packed)); - default_proto_packed_expected = cat( + default_proto_packed_expected = absl::StrCat( tag(rep_field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), delim(default_proto_packed_expected)); - packed_proto_packed = cat(tag(packed_field->number(), - WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(packed_proto_packed)); + packed_proto_packed = + absl::StrCat(tag(packed_field->number(), + WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(packed_proto_packed)); packed_proto_expected = - cat(tag(packed_field->number(), - WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(packed_proto_expected)); + absl::StrCat(tag(packed_field->number(), + WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(packed_proto_expected)); unpacked_proto_packed = - cat(tag(unpacked_field->number(), - WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(unpacked_proto_packed)); + absl::StrCat(tag(unpacked_field->number(), + WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(unpacked_proto_packed)); std::unique_ptr test_message = NewTestMessage(is_proto3); test_message->MergeFromString(default_proto_packed_expected); @@ -943,9 +924,10 @@ void BinaryAndJsonConformanceSuite::TestValidDataForType( string proto; string expected_proto; for (size_t i = 0; i < values.size(); i++) { - proto += cat(tag(rep_field->number(), wire_type), values[i].first); + proto += + absl::StrCat(tag(rep_field->number(), wire_type), values[i].first); expected_proto += - cat(tag(rep_field->number(), wire_type), values[i].second); + absl::StrCat(tag(rep_field->number(), wire_type), values[i].second); } std::unique_ptr test_message = NewTestMessage(is_proto3); test_message->MergeFromString(expected_proto); @@ -960,16 +942,18 @@ void BinaryAndJsonConformanceSuite::TestValidDataForType( void BinaryAndJsonConformanceSuite::TestValidDataForRepeatedScalarMessage() { std::vector values = { - delim(cat( + delim(absl::StrCat( tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1234), - tag(2, WireFormatLite::WIRETYPE_VARINT), varint(1234), - tag(31, WireFormatLite::WIRETYPE_VARINT), varint(1234))))), - delim(cat( + delim(absl::StrCat( + tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1234), + tag(2, WireFormatLite::WIRETYPE_VARINT), varint(1234), + tag(31, WireFormatLite::WIRETYPE_VARINT), varint(1234))))), + delim(absl::StrCat( tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(4321), - tag(3, WireFormatLite::WIRETYPE_VARINT), varint(4321), - tag(31, WireFormatLite::WIRETYPE_VARINT), varint(4321))))), + delim(absl::StrCat( + tag(1, WireFormatLite::WIRETYPE_VARINT), varint(4321), + tag(3, WireFormatLite::WIRETYPE_VARINT), varint(4321), + tag(31, WireFormatLite::WIRETYPE_VARINT), varint(4321))))), }; const std::string expected = @@ -987,34 +971,37 @@ void BinaryAndJsonConformanceSuite::TestValidDataForRepeatedScalarMessage() { const FieldDescriptor* field = GetFieldForType(FieldDescriptor::TYPE_MESSAGE, false, is_proto3); for (size_t i = 0; i < values.size(); i++) { - proto += - cat(tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - values[i]); + proto += absl::StrCat( + tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + values[i]); } RunValidProtobufTest("RepeatedScalarMessageMerge", REQUIRED, proto, - field->name() + ": " + expected, is_proto3); + absl::StrCat(field->name(), ": ", expected), + is_proto3); } } void BinaryAndJsonConformanceSuite::TestValidDataForMapType( FieldDescriptor::Type key_type, FieldDescriptor::Type value_type) { const string key_type_name = - UpperCase(string(".") + FieldDescriptor::TypeName(key_type)); + UpperCase(absl::StrCat(".", FieldDescriptor::TypeName(key_type))); const string value_type_name = - UpperCase(string(".") + FieldDescriptor::TypeName(value_type)); + UpperCase(absl::StrCat(".", FieldDescriptor::TypeName(value_type))); WireFormatLite::WireType key_wire_type = WireFormatLite::WireTypeForFieldType( static_cast(key_type)); WireFormatLite::WireType value_wire_type = WireFormatLite::WireTypeForFieldType( static_cast(value_type)); - string key1_data = cat(tag(1, key_wire_type), GetDefaultValue(key_type)); + string key1_data = + absl::StrCat(tag(1, key_wire_type), GetDefaultValue(key_type)); string value1_data = - cat(tag(2, value_wire_type), GetDefaultValue(value_type)); - string key2_data = cat(tag(1, key_wire_type), GetNonDefaultValue(key_type)); + absl::StrCat(tag(2, value_wire_type), GetDefaultValue(value_type)); + string key2_data = + absl::StrCat(tag(1, key_wire_type), GetNonDefaultValue(key_type)); string value2_data = - cat(tag(2, value_wire_type), GetNonDefaultValue(value_type)); + absl::StrCat(tag(2, value_wire_type), GetNonDefaultValue(value_type)); for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) { const FieldDescriptor* field = @@ -1022,9 +1009,9 @@ void BinaryAndJsonConformanceSuite::TestValidDataForMapType( { // Tests map with default key and value. - string proto = - cat(tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(cat(key1_data, value1_data))); + string proto = absl::StrCat( + tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(absl::StrCat(key1_data, value1_data))); std::unique_ptr test_message = NewTestMessage(is_proto3); test_message->MergeFromString(proto); string text; @@ -1036,9 +1023,9 @@ void BinaryAndJsonConformanceSuite::TestValidDataForMapType( { // Tests map with missing default key and value. - string proto = - cat(tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim("")); + string proto = absl::StrCat( + tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim("")); std::unique_ptr test_message = NewTestMessage(is_proto3); test_message->MergeFromString(proto); string text; @@ -1050,9 +1037,9 @@ void BinaryAndJsonConformanceSuite::TestValidDataForMapType( { // Tests map with non-default key and value. - string proto = - cat(tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(cat(key2_data, value2_data))); + string proto = absl::StrCat( + tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(absl::StrCat(key2_data, value2_data))); std::unique_ptr test_message = NewTestMessage(is_proto3); test_message->MergeFromString(proto); string text; @@ -1064,9 +1051,9 @@ void BinaryAndJsonConformanceSuite::TestValidDataForMapType( { // Tests map with unordered key and value. - string proto = - cat(tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(cat(value2_data, key2_data))); + string proto = absl::StrCat( + tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(absl::StrCat(value2_data, key2_data))); std::unique_ptr test_message = NewTestMessage(is_proto3); test_message->MergeFromString(proto); string text; @@ -1078,13 +1065,13 @@ void BinaryAndJsonConformanceSuite::TestValidDataForMapType( { // Tests map with duplicate key. - string proto1 = - cat(tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(cat(key2_data, value1_data))); - string proto2 = - cat(tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(cat(key2_data, value2_data))); - string proto = cat(proto1, proto2); + string proto1 = absl::StrCat( + tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(absl::StrCat(key2_data, value1_data))); + string proto2 = absl::StrCat( + tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(absl::StrCat(key2_data, value2_data))); + string proto = absl::StrCat(proto1, proto2); std::unique_ptr test_message = NewTestMessage(is_proto3); test_message->MergeFromString(proto2); string text; @@ -1096,9 +1083,9 @@ void BinaryAndJsonConformanceSuite::TestValidDataForMapType( { // Tests map with duplicate key in map entry. - string proto = - cat(tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(cat(key1_data, key2_data, value2_data))); + string proto = absl::StrCat( + tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(absl::StrCat(key1_data, key2_data, value2_data))); std::unique_ptr test_message = NewTestMessage(is_proto3); test_message->MergeFromString(proto); string text; @@ -1111,9 +1098,9 @@ void BinaryAndJsonConformanceSuite::TestValidDataForMapType( { // Tests map with duplicate value in map entry. - string proto = - cat(tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(cat(key2_data, value1_data, value2_data))); + string proto = absl::StrCat( + tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(absl::StrCat(key2_data, value1_data, value2_data))); std::unique_ptr test_message = NewTestMessage(is_proto3); test_message->MergeFromString(proto); string text; @@ -1127,34 +1114,36 @@ void BinaryAndJsonConformanceSuite::TestValidDataForMapType( } void BinaryAndJsonConformanceSuite::TestOverwriteMessageValueMap() { - string key_data = - cat(tag(1, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), delim("")); - string field1_data = cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1)); - string field2_data = cat(tag(2, WireFormatLite::WIRETYPE_VARINT), varint(1)); + string key_data = absl::StrCat( + tag(1, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), delim("")); + string field1_data = + absl::StrCat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1)); + string field2_data = + absl::StrCat(tag(2, WireFormatLite::WIRETYPE_VARINT), varint(1)); string field31_data = - cat(tag(31, WireFormatLite::WIRETYPE_VARINT), varint(1)); - string submsg1_data = delim(cat(field1_data, field31_data)); - string submsg2_data = delim(cat(field2_data, field31_data)); - string value1_data = - cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - submsg1_data))); - string value2_data = - cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - submsg2_data))); + absl::StrCat(tag(31, WireFormatLite::WIRETYPE_VARINT), varint(1)); + string submsg1_data = delim(absl::StrCat(field1_data, field31_data)); + string submsg2_data = delim(absl::StrCat(field2_data, field31_data)); + string value1_data = absl::StrCat( + tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(absl::StrCat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + submsg1_data))); + string value2_data = absl::StrCat( + tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(absl::StrCat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + submsg2_data))); for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) { const FieldDescriptor* field = GetFieldForMapType( FieldDescriptor::TYPE_STRING, FieldDescriptor::TYPE_MESSAGE, is_proto3); - string proto1 = - cat(tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(cat(key_data, value1_data))); - string proto2 = - cat(tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(cat(key_data, value2_data))); - string proto = cat(proto1, proto2); + string proto1 = absl::StrCat( + tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(absl::StrCat(key_data, value1_data))); + string proto2 = absl::StrCat( + tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(absl::StrCat(key_data, value2_data))); + string proto = absl::StrCat(proto1, proto2); std::unique_ptr test_message = NewTestMessage(is_proto3); test_message->MergeFromString(proto2); string text; @@ -1167,16 +1156,16 @@ void BinaryAndJsonConformanceSuite::TestOverwriteMessageValueMap() { void BinaryAndJsonConformanceSuite::TestValidDataForOneofType( FieldDescriptor::Type type) { const string type_name = - UpperCase(string(".") + FieldDescriptor::TypeName(type)); + UpperCase(absl::StrCat(".", FieldDescriptor::TypeName(type))); WireFormatLite::WireType wire_type = WireFormatLite::WireTypeForFieldType( static_cast(type)); for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) { const FieldDescriptor* field = GetFieldForOneofType(type, is_proto3); const string default_value = - cat(tag(field->number(), wire_type), GetDefaultValue(type)); + absl::StrCat(tag(field->number(), wire_type), GetDefaultValue(type)); const string non_default_value = - cat(tag(field->number(), wire_type), GetNonDefaultValue(type)); + absl::StrCat(tag(field->number(), wire_type), GetNonDefaultValue(type)); { // Tests oneof with default value. @@ -1236,8 +1225,8 @@ void BinaryAndJsonConformanceSuite::TestValidDataForOneofType( WireFormatLite::WireTypeForFieldType( static_cast(other_type)); const string other_value = - cat(tag(other_field->number(), other_wire_type), - GetDefaultValue(other_type)); + absl::StrCat(tag(other_field->number(), other_wire_type), + GetDefaultValue(other_type)); const string proto = absl::StrCat(other_value, non_default_value); const string expected_proto = non_default_value; @@ -1258,34 +1247,39 @@ void BinaryAndJsonConformanceSuite::TestValidDataForOneofType( } void BinaryAndJsonConformanceSuite::TestMergeOneofMessage() { - string field1_data = cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1)); - string field2a_data = cat(tag(2, WireFormatLite::WIRETYPE_VARINT), varint(1)); - string field2b_data = cat(tag(2, WireFormatLite::WIRETYPE_VARINT), varint(1)); + string field1_data = + absl::StrCat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1)); + string field2a_data = + absl::StrCat(tag(2, WireFormatLite::WIRETYPE_VARINT), varint(1)); + string field2b_data = + absl::StrCat(tag(2, WireFormatLite::WIRETYPE_VARINT), varint(1)); string field89_data = - cat(tag(89, WireFormatLite::WIRETYPE_VARINT), varint(1)); - string submsg1_data = - cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(cat(field1_data, field2a_data, field89_data))); - string submsg2_data = cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(cat(field2b_data, field89_data))); + absl::StrCat(tag(89, WireFormatLite::WIRETYPE_VARINT), varint(1)); + string submsg1_data = absl::StrCat( + tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(absl::StrCat(field1_data, field2a_data, field89_data))); + string submsg2_data = + absl::StrCat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(absl::StrCat(field2b_data, field89_data))); string merged_data = - cat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(cat(field1_data, field2b_data, field89_data, field89_data))); + absl::StrCat(tag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(absl::StrCat(field1_data, field2b_data, field89_data, + field89_data))); for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) { const FieldDescriptor* field = GetFieldForOneofType(FieldDescriptor::TYPE_MESSAGE, is_proto3); - string proto1 = - cat(tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(submsg1_data)); - string proto2 = - cat(tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(submsg2_data)); - string proto = cat(proto1, proto2); - string expected_proto = - cat(tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), - delim(merged_data)); + string proto1 = absl::StrCat( + tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(submsg1_data)); + string proto2 = absl::StrCat( + tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(submsg2_data)); + string proto = absl::StrCat(proto1, proto2); + string expected_proto = absl::StrCat( + tag(field->number(), WireFormatLite::WIRETYPE_LENGTH_DELIMITED), + delim(merged_data)); std::unique_ptr test_message = NewTestMessage(is_proto3); test_message->MergeFromString(expected_proto); @@ -1300,12 +1294,7 @@ void BinaryAndJsonConformanceSuite::TestMergeOneofMessage() { void BinaryAndJsonConformanceSuite::TestIllegalTags() { // field num 0 is illegal - string nullfield[] = { - "\1DEADBEEF", - "\2\1\1", - "\3\4", - "\5DEAD" - }; + string nullfield[] = {"\1DEADBEEF", "\2\1\1", "\3\4", "\5DEAD"}; for (int i = 0; i < 4; i++) { string name = "IllegalZeroFieldNum_Case_0"; name.back() += i; @@ -1313,47 +1302,46 @@ void BinaryAndJsonConformanceSuite::TestIllegalTags() { } } template -void BinaryAndJsonConformanceSuite::TestOneofMessage ( - MessageType &message, bool is_proto3) { +void BinaryAndJsonConformanceSuite::TestOneofMessage(MessageType& message, + bool is_proto3) { message.set_oneof_uint32(0); - RunValidProtobufTestWithMessage( - "OneofZeroUint32", RECOMMENDED, &message, "oneof_uint32: 0", is_proto3); + RunValidProtobufTestWithMessage("OneofZeroUint32", RECOMMENDED, &message, + "oneof_uint32: 0", is_proto3); message.mutable_oneof_nested_message()->set_a(0); RunValidProtobufTestWithMessage( "OneofZeroMessage", RECOMMENDED, &message, is_proto3 ? "oneof_nested_message: {}" : "oneof_nested_message: {a: 0}", is_proto3); message.mutable_oneof_nested_message()->set_a(1); - RunValidProtobufTestWithMessage( - "OneofZeroMessageSetTwice", RECOMMENDED, &message, - "oneof_nested_message: {a: 1}", - is_proto3); + RunValidProtobufTestWithMessage("OneofZeroMessageSetTwice", RECOMMENDED, + &message, "oneof_nested_message: {a: 1}", + is_proto3); message.set_oneof_string(""); - RunValidProtobufTestWithMessage( - "OneofZeroString", RECOMMENDED, &message, "oneof_string: \"\"", is_proto3); + RunValidProtobufTestWithMessage("OneofZeroString", RECOMMENDED, &message, + "oneof_string: \"\"", is_proto3); message.set_oneof_bytes(""); - RunValidProtobufTestWithMessage( - "OneofZeroBytes", RECOMMENDED, &message, "oneof_bytes: \"\"", is_proto3); + RunValidProtobufTestWithMessage("OneofZeroBytes", RECOMMENDED, &message, + "oneof_bytes: \"\"", is_proto3); message.set_oneof_bool(false); - RunValidProtobufTestWithMessage( - "OneofZeroBool", RECOMMENDED, &message, "oneof_bool: false", is_proto3); + RunValidProtobufTestWithMessage("OneofZeroBool", RECOMMENDED, &message, + "oneof_bool: false", is_proto3); message.set_oneof_uint64(0); - RunValidProtobufTestWithMessage( - "OneofZeroUint64", RECOMMENDED, &message, "oneof_uint64: 0", is_proto3); + RunValidProtobufTestWithMessage("OneofZeroUint64", RECOMMENDED, &message, + "oneof_uint64: 0", is_proto3); message.set_oneof_float(0.0f); - RunValidProtobufTestWithMessage( - "OneofZeroFloat", RECOMMENDED, &message, "oneof_float: 0", is_proto3); + RunValidProtobufTestWithMessage("OneofZeroFloat", RECOMMENDED, &message, + "oneof_float: 0", is_proto3); message.set_oneof_double(0.0); - RunValidProtobufTestWithMessage( - "OneofZeroDouble", RECOMMENDED, &message, "oneof_double: 0", is_proto3); + RunValidProtobufTestWithMessage("OneofZeroDouble", RECOMMENDED, &message, + "oneof_double: 0", is_proto3); message.set_oneof_enum(MessageType::FOO); - RunValidProtobufTestWithMessage( - "OneofZeroEnum", RECOMMENDED, &message, "oneof_enum: FOO", is_proto3); + RunValidProtobufTestWithMessage("OneofZeroEnum", RECOMMENDED, &message, + "oneof_enum: FOO", is_proto3); } template -void BinaryAndJsonConformanceSuite::TestUnknownMessage( - MessageType& message, bool is_proto3) { +void BinaryAndJsonConformanceSuite::TestUnknownMessage(MessageType& message, + bool is_proto3) { message.ParseFromString("\xA8\x1F\x01"); RunValidBinaryProtobufTest("UnknownVarint", REQUIRED, message.SerializeAsString(), is_proto3); @@ -1361,9 +1349,9 @@ void BinaryAndJsonConformanceSuite::TestUnknownMessage( void BinaryAndJsonConformanceSuite:: TestBinaryPerformanceForAlternatingUnknownFields() { - string unknown_field_1 = - cat(tag(UNKNOWN_FIELD, WireFormatLite::WIRETYPE_VARINT), varint(1234)); - string unknown_field_2 = cat( + string unknown_field_1 = absl::StrCat( + tag(UNKNOWN_FIELD, WireFormatLite::WIRETYPE_VARINT), varint(1234)); + string unknown_field_2 = absl::StrCat( tag(UNKNOWN_FIELD + 1, WireFormatLite::WIRETYPE_VARINT), varint(5678)); for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) { string proto; @@ -1382,17 +1370,19 @@ void BinaryAndJsonConformanceSuite:: TestBinaryPerformanceMergeMessageWithRepeatedFieldForType( FieldDescriptor::Type type) { const string type_name = - UpperCase(string(".") + FieldDescriptor::TypeName(type)); + UpperCase(absl::StrCat(".", FieldDescriptor::TypeName(type))); for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) { int field_number = GetFieldForType(type, true, is_proto3, Packed::kFalse)->number(); - string rep_field_proto = cat( + string rep_field_proto = absl::StrCat( tag(field_number, WireFormatLite::WireTypeForFieldType( static_cast(type))), GetNonDefaultValue(type)); RunBinaryPerformanceMergeMessageWithField( - "TestBinaryPerformanceMergeMessageWithRepeatedFieldForType" + type_name, + absl::StrCat( + "TestBinaryPerformanceMergeMessageWithRepeatedFieldForType", + type_name), rep_field_proto, is_proto3); } } @@ -1401,14 +1391,15 @@ void BinaryAndJsonConformanceSuite:: TestBinaryPerformanceMergeMessageWithUnknownFieldForType( FieldDescriptor::Type type) { const string type_name = - UpperCase(string(".") + FieldDescriptor::TypeName(type)); - string unknown_field_proto = - cat(tag(UNKNOWN_FIELD, WireFormatLite::WireTypeForFieldType( - static_cast(type))), - GetNonDefaultValue(type)); + UpperCase(absl::StrCat(".", FieldDescriptor::TypeName(type))); + string unknown_field_proto = absl::StrCat( + tag(UNKNOWN_FIELD, WireFormatLite::WireTypeForFieldType( + static_cast(type))), + GetNonDefaultValue(type)); for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) { RunBinaryPerformanceMergeMessageWithField( - "TestBinaryPerformanceMergeMessageWithUnknownFieldForType" + type_name, + absl::StrCat("TestBinaryPerformanceMergeMessageWithUnknownFieldForType", + type_name), unknown_field_proto, is_proto3); } } @@ -1568,7 +1559,8 @@ void BinaryAndJsonConformanceSuite::RunSuiteImpl() { {delim("谷歌"), delim("谷歌")}, // Google in Chinese {delim("\u8C37\u6B4C"), delim("谷歌")}, // unicode escape {delim("\u8c37\u6b4c"), delim("谷歌")}, // lowercase unicode - {delim("\xF0\x9F\x98\x81"), delim("\xF0\x9F\x98\x81")}, // emoji: 😁 + {delim("\xF0\x9F\x98\x81"), + delim("\xF0\x9F\x98\x81")}, // emoji: 😁 }); TestValidDataForType(FieldDescriptor::TYPE_BYTES, { @@ -1591,8 +1583,10 @@ void BinaryAndJsonConformanceSuite::RunSuiteImpl() { FieldDescriptor::TYPE_MESSAGE, { {delim(""), delim("")}, - {delim(cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1234))), - delim(cat(tag(1, WireFormatLite::WIRETYPE_VARINT), varint(1234)))}, + {delim(absl::StrCat(tag(1, WireFormatLite::WIRETYPE_VARINT), + varint(1234))), + delim(absl::StrCat(tag(1, WireFormatLite::WIRETYPE_VARINT), + varint(1234)))}, }); TestValidDataForMapType(FieldDescriptor::TYPE_INT32, @@ -1724,30 +1718,32 @@ void BinaryAndJsonConformanceSuite:: TestJsonPerformanceMergeMessageWithRepeatedFieldForType( FieldDescriptor::Type type, string field_value) { const string type_name = - UpperCase(string(".") + FieldDescriptor::TypeName(type)); + UpperCase(absl::StrCat(".", FieldDescriptor::TypeName(type))); for (int is_proto3 = 0; is_proto3 < 2; is_proto3++) { const FieldDescriptor* field = GetFieldForType(type, true, is_proto3, Packed::kFalse); string field_name = field->name(); - string message_field = "\"" + field_name + "\": [" + field_value + "]"; + string message_field = + absl::StrCat("\"", field_name, "\": [", field_value, "]"); string recursive_message = - "\"recursive_message\": { " + message_field + "}"; - string input = "{"; - input.append(recursive_message); + absl::StrCat("\"recursive_message\": { ", message_field, "}"); + string input = absl::StrCat("{", recursive_message); for (size_t i = 1; i < kPerformanceRepeatCount; i++) { - input.append("," + recursive_message); + absl::StrAppend(&input, ",", recursive_message); } - input.append("}"); + absl::StrAppend(&input, "}"); - string textproto_message_field = field_name + ": " + field_value; + string textproto_message_field = + absl::StrCat(field_name, ": ", field_value); string expected_textproto = "recursive_message { "; for (size_t i = 0; i < kPerformanceRepeatCount; i++) { - expected_textproto.append(textproto_message_field + " "); + absl::StrAppend(&expected_textproto, textproto_message_field, " "); } - expected_textproto.append("}"); + absl::StrAppend(&expected_textproto, "}"); RunValidJsonTest( - "TestJsonPerformanceMergeMessageWithRepeatedFieldForType" + type_name, + absl::StrCat("TestJsonPerformanceMergeMessageWithRepeatedFieldForType", + type_name), RECOMMENDED, input, expected_textproto, is_proto3); } } @@ -1841,33 +1837,30 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForUnknownEnumStringValues() { } void BinaryAndJsonConformanceSuite::RunJsonTestsForFieldNameConvention() { - RunValidJsonTest( - "FieldNameInSnakeCase", REQUIRED, - R"({ + RunValidJsonTest("FieldNameInSnakeCase", REQUIRED, + R"({ "fieldname1": 1, "fieldName2": 2, "FieldName3": 3, "fieldName4": 4 })", - R"( + R"( fieldname1: 1 field_name2: 2 _field_name3: 3 field__name4_: 4 )"); - RunValidJsonTest( - "FieldNameWithNumbers", REQUIRED, - R"({ + RunValidJsonTest("FieldNameWithNumbers", REQUIRED, + R"({ "field0name5": 5, "field0Name6": 6 })", - R"( + R"( field0name5: 5 field_0_name6: 6 )"); - RunValidJsonTest( - "FieldNameWithMixedCases", REQUIRED, - R"({ + RunValidJsonTest("FieldNameWithMixedCases", REQUIRED, + R"({ "fieldName7": 7, "FieldName8": 8, "fieldName9": 9, @@ -1875,7 +1868,7 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForFieldNameConvention() { "FIELDNAME11": 11, "FIELDName12": 12 })", - R"( + R"( fieldName7: 7 FieldName8: 8 field_Name9: 9 @@ -1883,9 +1876,8 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForFieldNameConvention() { FIELD_NAME11: 11 FIELD_name12: 12 )"); - RunValidJsonTest( - "FieldNameWithDoubleUnderscores", RECOMMENDED, - R"({ + RunValidJsonTest("FieldNameWithDoubleUnderscores", RECOMMENDED, + R"({ "FieldName13": 13, "FieldName14": 14, "fieldName15": 15, @@ -1893,7 +1885,7 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForFieldNameConvention() { "fieldName17": 17, "FieldName18": 18 })", - R"( + R"( __field_name13: 13 __Field_name14: 14 field__name15: 15 @@ -1902,9 +1894,8 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForFieldNameConvention() { Field_name18__: 18 )"); // Using the original proto field name in JSON is also allowed. - RunValidJsonTest( - "OriginalProtoFieldName", REQUIRED, - R"({ + RunValidJsonTest("OriginalProtoFieldName", REQUIRED, + R"({ "fieldname1": 1, "field_name2": 2, "_field_name3": 3, @@ -1924,7 +1915,7 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForFieldNameConvention() { "field_name17__": 17, "Field_name18__": 18 })", - R"( + R"( fieldname1: 1 field_name2: 2 _field_name3: 3 @@ -1945,59 +1936,47 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForFieldNameConvention() { Field_name18__: 18 )"); // Field names can be escaped. - RunValidJsonTest( - "FieldNameEscaped", REQUIRED, - R"({"fieldn\u0061me1": 1})", - "fieldname1: 1"); + RunValidJsonTest("FieldNameEscaped", REQUIRED, R"({"fieldn\u0061me1": 1})", + "fieldname1: 1"); // String ends with escape character. - ExpectParseFailureForJson( - "StringEndsWithEscapeChar", RECOMMENDED, - "{\"optionalString\": \"abc\\"); + ExpectParseFailureForJson("StringEndsWithEscapeChar", RECOMMENDED, + "{\"optionalString\": \"abc\\"); // Field names must be quoted (or it's not valid JSON). - ExpectParseFailureForJson( - "FieldNameNotQuoted", RECOMMENDED, - "{fieldname1: 1}"); + ExpectParseFailureForJson("FieldNameNotQuoted", RECOMMENDED, + "{fieldname1: 1}"); // Trailing comma is not allowed (not valid JSON). - ExpectParseFailureForJson( - "TrailingCommaInAnObject", RECOMMENDED, - R"({"fieldname1":1,})"); - ExpectParseFailureForJson( - "TrailingCommaInAnObjectWithSpace", RECOMMENDED, - R"({"fieldname1":1 ,})"); - ExpectParseFailureForJson( - "TrailingCommaInAnObjectWithSpaceCommaSpace", RECOMMENDED, - R"({"fieldname1":1 , })"); - ExpectParseFailureForJson( - "TrailingCommaInAnObjectWithNewlines", RECOMMENDED, - R"({ + ExpectParseFailureForJson("TrailingCommaInAnObject", RECOMMENDED, + R"({"fieldname1":1,})"); + ExpectParseFailureForJson("TrailingCommaInAnObjectWithSpace", RECOMMENDED, + R"({"fieldname1":1 ,})"); + ExpectParseFailureForJson("TrailingCommaInAnObjectWithSpaceCommaSpace", + RECOMMENDED, R"({"fieldname1":1 , })"); + ExpectParseFailureForJson("TrailingCommaInAnObjectWithNewlines", RECOMMENDED, + R"({ "fieldname1":1, })"); // JSON doesn't support comments. - ExpectParseFailureForJson( - "JsonWithComments", RECOMMENDED, - R"({ + ExpectParseFailureForJson("JsonWithComments", RECOMMENDED, + R"({ // This is a comment. "fieldname1": 1 })"); // JSON spec says whitespace doesn't matter, so try a few spacings to be sure. - RunValidJsonTest( - "OneLineNoSpaces", RECOMMENDED, - "{\"optionalInt32\":1,\"optionalInt64\":2}", - R"( + RunValidJsonTest("OneLineNoSpaces", RECOMMENDED, + "{\"optionalInt32\":1,\"optionalInt64\":2}", + R"( optional_int32: 1 optional_int64: 2 )"); - RunValidJsonTest( - "OneLineWithSpaces", RECOMMENDED, - "{ \"optionalInt32\" : 1 , \"optionalInt64\" : 2 }", - R"( + RunValidJsonTest("OneLineWithSpaces", RECOMMENDED, + "{ \"optionalInt32\" : 1 , \"optionalInt64\" : 2 }", + R"( optional_int32: 1 optional_int64: 2 )"); - RunValidJsonTest( - "MultilineNoSpaces", RECOMMENDED, - "{\n\"optionalInt32\"\n:\n1\n,\n\"optionalInt64\"\n:\n2\n}", - R"( + RunValidJsonTest("MultilineNoSpaces", RECOMMENDED, + "{\n\"optionalInt32\"\n:\n1\n,\n\"optionalInt64\"\n:\n2\n}", + R"( optional_int32: 1 optional_int64: 2 )"); @@ -2009,28 +1988,24 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForFieldNameConvention() { optional_int64: 2 )"); // Missing comma between key/value pairs. - ExpectParseFailureForJson( - "MissingCommaOneLine", RECOMMENDED, - "{ \"optionalInt32\": 1 \"optionalInt64\": 2 }"); + ExpectParseFailureForJson("MissingCommaOneLine", RECOMMENDED, + "{ \"optionalInt32\": 1 \"optionalInt64\": 2 }"); ExpectParseFailureForJson( "MissingCommaMultiline", RECOMMENDED, "{\n \"optionalInt32\": 1\n \"optionalInt64\": 2\n}"); // Duplicated field names are not allowed. - ExpectParseFailureForJson( - "FieldNameDuplicate", RECOMMENDED, - R"({ + ExpectParseFailureForJson("FieldNameDuplicate", RECOMMENDED, + R"({ "optionalNestedMessage": {a: 1}, "optionalNestedMessage": {} })"); - ExpectParseFailureForJson( - "FieldNameDuplicateDifferentCasing1", RECOMMENDED, - R"({ + ExpectParseFailureForJson("FieldNameDuplicateDifferentCasing1", RECOMMENDED, + R"({ "optional_nested_message": {a: 1}, "optionalNestedMessage": {} })"); - ExpectParseFailureForJson( - "FieldNameDuplicateDifferentCasing2", RECOMMENDED, - R"({ + ExpectParseFailureForJson("FieldNameDuplicateDifferentCasing2", RECOMMENDED, + R"({ "optionalNestedMessage": {a: 1}, "optional_nested_message": {} })"); @@ -2044,10 +2019,8 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForFieldNameConvention() { "fieldName4": 4 })", [](const Json::Value& value) { - return value.isMember("fieldname1") && - value.isMember("fieldName2") && - value.isMember("FieldName3") && - value.isMember("fieldName4"); + return value.isMember("fieldname1") && value.isMember("fieldName2") && + value.isMember("FieldName3") && value.isMember("fieldName4"); }, true); RunValidJsonTestWithValidator( @@ -2057,8 +2030,7 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForFieldNameConvention() { "field0Name6": 6 })", [](const Json::Value& value) { - return value.isMember("field0name5") && - value.isMember("field0Name6"); + return value.isMember("field0name5") && value.isMember("field0Name6"); }, true); RunValidJsonTestWithValidator( @@ -2072,12 +2044,9 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForFieldNameConvention() { "FIELDName12": 12 })", [](const Json::Value& value) { - return value.isMember("fieldName7") && - value.isMember("FieldName8") && - value.isMember("fieldName9") && - value.isMember("FieldName10") && - value.isMember("FIELDNAME11") && - value.isMember("FIELDName12"); + return value.isMember("fieldName7") && value.isMember("FieldName8") && + value.isMember("fieldName9") && value.isMember("FieldName10") && + value.isMember("FIELDNAME11") && value.isMember("FIELDName12"); }, true); RunValidJsonTestWithValidator( @@ -2091,12 +2060,9 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForFieldNameConvention() { "FieldName18": 18 })", [](const Json::Value& value) { - return value.isMember("FieldName13") && - value.isMember("FieldName14") && - value.isMember("fieldName15") && - value.isMember("fieldName16") && - value.isMember("fieldName17") && - value.isMember("FieldName18"); + return value.isMember("FieldName13") && value.isMember("FieldName14") && + value.isMember("fieldName15") && value.isMember("fieldName16") && + value.isMember("fieldName17") && value.isMember("FieldName18"); }, true); RunValidJsonTestWithValidator( @@ -2127,407 +2093,305 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForFieldNameConvention() { void BinaryAndJsonConformanceSuite::RunJsonTestsForNonRepeatedTypes() { // Integer fields. - RunValidJsonTest( - "Int32FieldMaxValue", REQUIRED, - R"({"optionalInt32": 2147483647})", - "optional_int32: 2147483647"); - RunValidJsonTest( - "Int32FieldMinValue", REQUIRED, - R"({"optionalInt32": -2147483648})", - "optional_int32: -2147483648"); - RunValidJsonTest( - "Uint32FieldMaxValue", REQUIRED, - R"({"optionalUint32": 4294967295})", - "optional_uint32: 4294967295"); - RunValidJsonTest( - "Int64FieldMaxValue", REQUIRED, - R"({"optionalInt64": "9223372036854775807"})", - "optional_int64: 9223372036854775807"); - RunValidJsonTest( - "Int64FieldMinValue", REQUIRED, - R"({"optionalInt64": "-9223372036854775808"})", - "optional_int64: -9223372036854775808"); - RunValidJsonTest( - "Uint64FieldMaxValue", REQUIRED, - R"({"optionalUint64": "18446744073709551615"})", - "optional_uint64: 18446744073709551615"); + RunValidJsonTest("Int32FieldMaxValue", REQUIRED, + R"({"optionalInt32": 2147483647})", + "optional_int32: 2147483647"); + RunValidJsonTest("Int32FieldMinValue", REQUIRED, + R"({"optionalInt32": -2147483648})", + "optional_int32: -2147483648"); + RunValidJsonTest("Uint32FieldMaxValue", REQUIRED, + R"({"optionalUint32": 4294967295})", + "optional_uint32: 4294967295"); + RunValidJsonTest("Int64FieldMaxValue", REQUIRED, + R"({"optionalInt64": "9223372036854775807"})", + "optional_int64: 9223372036854775807"); + RunValidJsonTest("Int64FieldMinValue", REQUIRED, + R"({"optionalInt64": "-9223372036854775808"})", + "optional_int64: -9223372036854775808"); + RunValidJsonTest("Uint64FieldMaxValue", REQUIRED, + R"({"optionalUint64": "18446744073709551615"})", + "optional_uint64: 18446744073709551615"); // While not the largest Int64, this is the largest // Int64 which can be exactly represented within an // IEEE-754 64-bit float, which is the expected level // of interoperability guarantee. Larger values may // work in some implementations, but should not be // relied upon. - RunValidJsonTest( - "Int64FieldMaxValueNotQuoted", REQUIRED, - R"({"optionalInt64": 9223372036854774784})", - "optional_int64: 9223372036854774784"); - RunValidJsonTest( - "Int64FieldMinValueNotQuoted", REQUIRED, - R"({"optionalInt64": -9223372036854775808})", - "optional_int64: -9223372036854775808"); + RunValidJsonTest("Int64FieldMaxValueNotQuoted", REQUIRED, + R"({"optionalInt64": 9223372036854774784})", + "optional_int64: 9223372036854774784"); + RunValidJsonTest("Int64FieldMinValueNotQuoted", REQUIRED, + R"({"optionalInt64": -9223372036854775808})", + "optional_int64: -9223372036854775808"); // Largest interoperable Uint64; see comment above // for Int64FieldMaxValueNotQuoted. - RunValidJsonTest( - "Uint64FieldMaxValueNotQuoted", REQUIRED, - R"({"optionalUint64": 18446744073709549568})", - "optional_uint64: 18446744073709549568"); + RunValidJsonTest("Uint64FieldMaxValueNotQuoted", REQUIRED, + R"({"optionalUint64": 18446744073709549568})", + "optional_uint64: 18446744073709549568"); // Values can be represented as JSON strings. - RunValidJsonTest( - "Int32FieldStringValue", REQUIRED, - R"({"optionalInt32": "2147483647"})", - "optional_int32: 2147483647"); - RunValidJsonTest( - "Int32FieldStringValueEscaped", REQUIRED, - R"({"optionalInt32": "2\u003147483647"})", - "optional_int32: 2147483647"); + RunValidJsonTest("Int32FieldStringValue", REQUIRED, + R"({"optionalInt32": "2147483647"})", + "optional_int32: 2147483647"); + RunValidJsonTest("Int32FieldStringValueEscaped", REQUIRED, + R"({"optionalInt32": "2\u003147483647"})", + "optional_int32: 2147483647"); // Parsers reject out-of-bound integer values. - ExpectParseFailureForJson( - "Int32FieldTooLarge", REQUIRED, - R"({"optionalInt32": 2147483648})"); - ExpectParseFailureForJson( - "Int32FieldTooSmall", REQUIRED, - R"({"optionalInt32": -2147483649})"); - ExpectParseFailureForJson( - "Uint32FieldTooLarge", REQUIRED, - R"({"optionalUint32": 4294967296})"); - ExpectParseFailureForJson( - "Int64FieldTooLarge", REQUIRED, - R"({"optionalInt64": "9223372036854775808"})"); - ExpectParseFailureForJson( - "Int64FieldTooSmall", REQUIRED, - R"({"optionalInt64": "-9223372036854775809"})"); - ExpectParseFailureForJson( - "Uint64FieldTooLarge", REQUIRED, - R"({"optionalUint64": "18446744073709551616"})"); + ExpectParseFailureForJson("Int32FieldTooLarge", REQUIRED, + R"({"optionalInt32": 2147483648})"); + ExpectParseFailureForJson("Int32FieldTooSmall", REQUIRED, + R"({"optionalInt32": -2147483649})"); + ExpectParseFailureForJson("Uint32FieldTooLarge", REQUIRED, + R"({"optionalUint32": 4294967296})"); + ExpectParseFailureForJson("Int64FieldTooLarge", REQUIRED, + R"({"optionalInt64": "9223372036854775808"})"); + ExpectParseFailureForJson("Int64FieldTooSmall", REQUIRED, + R"({"optionalInt64": "-9223372036854775809"})"); + ExpectParseFailureForJson("Uint64FieldTooLarge", REQUIRED, + R"({"optionalUint64": "18446744073709551616"})"); // Parser reject non-integer numeric values as well. - ExpectParseFailureForJson( - "Int32FieldNotInteger", REQUIRED, - R"({"optionalInt32": 0.5})"); - ExpectParseFailureForJson( - "Uint32FieldNotInteger", REQUIRED, - R"({"optionalUint32": 0.5})"); - ExpectParseFailureForJson( - "Int64FieldNotInteger", REQUIRED, - R"({"optionalInt64": "0.5"})"); - ExpectParseFailureForJson( - "Uint64FieldNotInteger", REQUIRED, - R"({"optionalUint64": "0.5"})"); + ExpectParseFailureForJson("Int32FieldNotInteger", REQUIRED, + R"({"optionalInt32": 0.5})"); + ExpectParseFailureForJson("Uint32FieldNotInteger", REQUIRED, + R"({"optionalUint32": 0.5})"); + ExpectParseFailureForJson("Int64FieldNotInteger", REQUIRED, + R"({"optionalInt64": "0.5"})"); + ExpectParseFailureForJson("Uint64FieldNotInteger", REQUIRED, + R"({"optionalUint64": "0.5"})"); // Integers but represented as float values are accepted. - RunValidJsonTest( - "Int32FieldFloatTrailingZero", REQUIRED, - R"({"optionalInt32": 100000.000})", - "optional_int32: 100000"); - RunValidJsonTest( - "Int32FieldExponentialFormat", REQUIRED, - R"({"optionalInt32": 1e5})", - "optional_int32: 100000"); - RunValidJsonTest( - "Int32FieldMaxFloatValue", REQUIRED, - R"({"optionalInt32": 2.147483647e9})", - "optional_int32: 2147483647"); - RunValidJsonTest( - "Int32FieldMinFloatValue", REQUIRED, - R"({"optionalInt32": -2.147483648e9})", - "optional_int32: -2147483648"); - RunValidJsonTest( - "Uint32FieldMaxFloatValue", REQUIRED, - R"({"optionalUint32": 4.294967295e9})", - "optional_uint32: 4294967295"); + RunValidJsonTest("Int32FieldFloatTrailingZero", REQUIRED, + R"({"optionalInt32": 100000.000})", + "optional_int32: 100000"); + RunValidJsonTest("Int32FieldExponentialFormat", REQUIRED, + R"({"optionalInt32": 1e5})", "optional_int32: 100000"); + RunValidJsonTest("Int32FieldMaxFloatValue", REQUIRED, + R"({"optionalInt32": 2.147483647e9})", + "optional_int32: 2147483647"); + RunValidJsonTest("Int32FieldMinFloatValue", REQUIRED, + R"({"optionalInt32": -2.147483648e9})", + "optional_int32: -2147483648"); + RunValidJsonTest("Uint32FieldMaxFloatValue", REQUIRED, + R"({"optionalUint32": 4.294967295e9})", + "optional_uint32: 4294967295"); // Parser reject non-numeric values. - ExpectParseFailureForJson( - "Int32FieldNotNumber", REQUIRED, - R"({"optionalInt32": "3x3"})"); - ExpectParseFailureForJson( - "Uint32FieldNotNumber", REQUIRED, - R"({"optionalUint32": "3x3"})"); - ExpectParseFailureForJson( - "Int64FieldNotNumber", REQUIRED, - R"({"optionalInt64": "3x3"})"); - ExpectParseFailureForJson( - "Uint64FieldNotNumber", REQUIRED, - R"({"optionalUint64": "3x3"})"); + ExpectParseFailureForJson("Int32FieldNotNumber", REQUIRED, + R"({"optionalInt32": "3x3"})"); + ExpectParseFailureForJson("Uint32FieldNotNumber", REQUIRED, + R"({"optionalUint32": "3x3"})"); + ExpectParseFailureForJson("Int64FieldNotNumber", REQUIRED, + R"({"optionalInt64": "3x3"})"); + ExpectParseFailureForJson("Uint64FieldNotNumber", REQUIRED, + R"({"optionalUint64": "3x3"})"); // JSON does not allow "+" on numeric values. - ExpectParseFailureForJson( - "Int32FieldPlusSign", REQUIRED, - R"({"optionalInt32": +1})"); + ExpectParseFailureForJson("Int32FieldPlusSign", REQUIRED, + R"({"optionalInt32": +1})"); // JSON doesn't allow leading 0s. - ExpectParseFailureForJson( - "Int32FieldLeadingZero", REQUIRED, - R"({"optionalInt32": 01})"); - ExpectParseFailureForJson( - "Int32FieldNegativeWithLeadingZero", REQUIRED, - R"({"optionalInt32": -01})"); + ExpectParseFailureForJson("Int32FieldLeadingZero", REQUIRED, + R"({"optionalInt32": 01})"); + ExpectParseFailureForJson("Int32FieldNegativeWithLeadingZero", REQUIRED, + R"({"optionalInt32": -01})"); // String values must follow the same syntax rule. Specifically leading // or trailing spaces are not allowed. - ExpectParseFailureForJson( - "Int32FieldLeadingSpace", REQUIRED, - R"({"optionalInt32": " 1"})"); - ExpectParseFailureForJson( - "Int32FieldTrailingSpace", REQUIRED, - R"({"optionalInt32": "1 "})"); + ExpectParseFailureForJson("Int32FieldLeadingSpace", REQUIRED, + R"({"optionalInt32": " 1"})"); + ExpectParseFailureForJson("Int32FieldTrailingSpace", REQUIRED, + R"({"optionalInt32": "1 "})"); // 64-bit values are serialized as strings. RunValidJsonTestWithValidator( "Int64FieldBeString", RECOMMENDED, R"({"optionalInt64": 1})", [](const Json::Value& value) { return value["optionalInt64"].type() == Json::stringValue && - value["optionalInt64"].asString() == "1"; + value["optionalInt64"].asString() == "1"; }, true); RunValidJsonTestWithValidator( "Uint64FieldBeString", RECOMMENDED, R"({"optionalUint64": 1})", [](const Json::Value& value) { return value["optionalUint64"].type() == Json::stringValue && - value["optionalUint64"].asString() == "1"; + value["optionalUint64"].asString() == "1"; }, true); // Bool fields. - RunValidJsonTest( - "BoolFieldTrue", REQUIRED, - R"({"optionalBool":true})", - "optional_bool: true"); - RunValidJsonTest( - "BoolFieldFalse", REQUIRED, - R"({"optionalBool":false})", - "optional_bool: false"); + RunValidJsonTest("BoolFieldTrue", REQUIRED, R"({"optionalBool":true})", + "optional_bool: true"); + RunValidJsonTest("BoolFieldFalse", REQUIRED, R"({"optionalBool":false})", + "optional_bool: false"); // Other forms are not allowed. - ExpectParseFailureForJson( - "BoolFieldIntegerZero", RECOMMENDED, - R"({"optionalBool":0})"); - ExpectParseFailureForJson( - "BoolFieldIntegerOne", RECOMMENDED, - R"({"optionalBool":1})"); - ExpectParseFailureForJson( - "BoolFieldCamelCaseTrue", RECOMMENDED, - R"({"optionalBool":True})"); - ExpectParseFailureForJson( - "BoolFieldCamelCaseFalse", RECOMMENDED, - R"({"optionalBool":False})"); - ExpectParseFailureForJson( - "BoolFieldAllCapitalTrue", RECOMMENDED, - R"({"optionalBool":TRUE})"); - ExpectParseFailureForJson( - "BoolFieldAllCapitalFalse", RECOMMENDED, - R"({"optionalBool":FALSE})"); - ExpectParseFailureForJson( - "BoolFieldDoubleQuotedTrue", RECOMMENDED, - R"({"optionalBool":"true"})"); - ExpectParseFailureForJson( - "BoolFieldDoubleQuotedFalse", RECOMMENDED, - R"({"optionalBool":"false"})"); + ExpectParseFailureForJson("BoolFieldIntegerZero", RECOMMENDED, + R"({"optionalBool":0})"); + ExpectParseFailureForJson("BoolFieldIntegerOne", RECOMMENDED, + R"({"optionalBool":1})"); + ExpectParseFailureForJson("BoolFieldCamelCaseTrue", RECOMMENDED, + R"({"optionalBool":True})"); + ExpectParseFailureForJson("BoolFieldCamelCaseFalse", RECOMMENDED, + R"({"optionalBool":False})"); + ExpectParseFailureForJson("BoolFieldAllCapitalTrue", RECOMMENDED, + R"({"optionalBool":TRUE})"); + ExpectParseFailureForJson("BoolFieldAllCapitalFalse", RECOMMENDED, + R"({"optionalBool":FALSE})"); + ExpectParseFailureForJson("BoolFieldDoubleQuotedTrue", RECOMMENDED, + R"({"optionalBool":"true"})"); + ExpectParseFailureForJson("BoolFieldDoubleQuotedFalse", RECOMMENDED, + R"({"optionalBool":"false"})"); // Float fields. - RunValidJsonTest( - "FloatFieldMinPositiveValue", REQUIRED, - R"({"optionalFloat": 1.175494e-38})", - "optional_float: 1.175494e-38"); - RunValidJsonTest( - "FloatFieldMaxNegativeValue", REQUIRED, - R"({"optionalFloat": -1.175494e-38})", - "optional_float: -1.175494e-38"); - RunValidJsonTest( - "FloatFieldMaxPositiveValue", REQUIRED, - R"({"optionalFloat": 3.402823e+38})", - "optional_float: 3.402823e+38"); - RunValidJsonTest( - "FloatFieldMinNegativeValue", REQUIRED, - R"({"optionalFloat": 3.402823e+38})", - "optional_float: 3.402823e+38"); + RunValidJsonTest("FloatFieldMinPositiveValue", REQUIRED, + R"({"optionalFloat": 1.175494e-38})", + "optional_float: 1.175494e-38"); + RunValidJsonTest("FloatFieldMaxNegativeValue", REQUIRED, + R"({"optionalFloat": -1.175494e-38})", + "optional_float: -1.175494e-38"); + RunValidJsonTest("FloatFieldMaxPositiveValue", REQUIRED, + R"({"optionalFloat": 3.402823e+38})", + "optional_float: 3.402823e+38"); + RunValidJsonTest("FloatFieldMinNegativeValue", REQUIRED, + R"({"optionalFloat": 3.402823e+38})", + "optional_float: 3.402823e+38"); // Values can be quoted. - RunValidJsonTest( - "FloatFieldQuotedValue", REQUIRED, - R"({"optionalFloat": "1"})", - "optional_float: 1"); + RunValidJsonTest("FloatFieldQuotedValue", REQUIRED, + R"({"optionalFloat": "1"})", "optional_float: 1"); // Special values. - RunValidJsonTest( - "FloatFieldNan", REQUIRED, - R"({"optionalFloat": "NaN"})", - "optional_float: nan"); - RunValidJsonTest( - "FloatFieldInfinity", REQUIRED, - R"({"optionalFloat": "Infinity"})", - "optional_float: inf"); - RunValidJsonTest( - "FloatFieldNegativeInfinity", REQUIRED, - R"({"optionalFloat": "-Infinity"})", - "optional_float: -inf"); + RunValidJsonTest("FloatFieldNan", REQUIRED, R"({"optionalFloat": "NaN"})", + "optional_float: nan"); + RunValidJsonTest("FloatFieldInfinity", REQUIRED, + R"({"optionalFloat": "Infinity"})", "optional_float: inf"); + RunValidJsonTest("FloatFieldNegativeInfinity", REQUIRED, + R"({"optionalFloat": "-Infinity"})", "optional_float: -inf"); // Non-canonical Nan will be correctly normalized. { TestAllTypesProto3 message; // IEEE floating-point standard 32-bit quiet NaN: // 0111 1111 1xxx xxxx xxxx xxxx xxxx xxxx - message.set_optional_float( - WireFormatLite::DecodeFloat(0x7FA12345)); - RunValidJsonTestWithProtobufInput( - "FloatFieldNormalizeQuietNan", REQUIRED, message, - "optional_float: nan"); + message.set_optional_float(WireFormatLite::DecodeFloat(0x7FA12345)); + RunValidJsonTestWithProtobufInput("FloatFieldNormalizeQuietNan", REQUIRED, + message, "optional_float: nan"); // IEEE floating-point standard 64-bit signaling NaN: // 1111 1111 1xxx xxxx xxxx xxxx xxxx xxxx - message.set_optional_float( - WireFormatLite::DecodeFloat(0xFFB54321)); - RunValidJsonTestWithProtobufInput( - "FloatFieldNormalizeSignalingNan", REQUIRED, message, - "optional_float: nan"); + message.set_optional_float(WireFormatLite::DecodeFloat(0xFFB54321)); + RunValidJsonTestWithProtobufInput("FloatFieldNormalizeSignalingNan", + REQUIRED, message, "optional_float: nan"); } // Special values must be quoted. - ExpectParseFailureForJson( - "FloatFieldNanNotQuoted", RECOMMENDED, - R"({"optionalFloat": NaN})"); - ExpectParseFailureForJson( - "FloatFieldInfinityNotQuoted", RECOMMENDED, - R"({"optionalFloat": Infinity})"); - ExpectParseFailureForJson( - "FloatFieldNegativeInfinityNotQuoted", RECOMMENDED, - R"({"optionalFloat": -Infinity})"); + ExpectParseFailureForJson("FloatFieldNanNotQuoted", RECOMMENDED, + R"({"optionalFloat": NaN})"); + ExpectParseFailureForJson("FloatFieldInfinityNotQuoted", RECOMMENDED, + R"({"optionalFloat": Infinity})"); + ExpectParseFailureForJson("FloatFieldNegativeInfinityNotQuoted", RECOMMENDED, + R"({"optionalFloat": -Infinity})"); // Parsers should reject out-of-bound values. - ExpectParseFailureForJson( - "FloatFieldTooSmall", REQUIRED, - R"({"optionalFloat": -3.502823e+38})"); - ExpectParseFailureForJson( - "FloatFieldTooLarge", REQUIRED, - R"({"optionalFloat": 3.502823e+38})"); + ExpectParseFailureForJson("FloatFieldTooSmall", REQUIRED, + R"({"optionalFloat": -3.502823e+38})"); + ExpectParseFailureForJson("FloatFieldTooLarge", REQUIRED, + R"({"optionalFloat": 3.502823e+38})"); // Double fields. - RunValidJsonTest( - "DoubleFieldMinPositiveValue", REQUIRED, - R"({"optionalDouble": 2.22507e-308})", - "optional_double: 2.22507e-308"); - RunValidJsonTest( - "DoubleFieldMaxNegativeValue", REQUIRED, - R"({"optionalDouble": -2.22507e-308})", - "optional_double: -2.22507e-308"); - RunValidJsonTest( - "DoubleFieldMaxPositiveValue", REQUIRED, - R"({"optionalDouble": 1.79769e+308})", - "optional_double: 1.79769e+308"); - RunValidJsonTest( - "DoubleFieldMinNegativeValue", REQUIRED, - R"({"optionalDouble": -1.79769e+308})", - "optional_double: -1.79769e+308"); + RunValidJsonTest("DoubleFieldMinPositiveValue", REQUIRED, + R"({"optionalDouble": 2.22507e-308})", + "optional_double: 2.22507e-308"); + RunValidJsonTest("DoubleFieldMaxNegativeValue", REQUIRED, + R"({"optionalDouble": -2.22507e-308})", + "optional_double: -2.22507e-308"); + RunValidJsonTest("DoubleFieldMaxPositiveValue", REQUIRED, + R"({"optionalDouble": 1.79769e+308})", + "optional_double: 1.79769e+308"); + RunValidJsonTest("DoubleFieldMinNegativeValue", REQUIRED, + R"({"optionalDouble": -1.79769e+308})", + "optional_double: -1.79769e+308"); // Values can be quoted. - RunValidJsonTest( - "DoubleFieldQuotedValue", REQUIRED, - R"({"optionalDouble": "1"})", - "optional_double: 1"); + RunValidJsonTest("DoubleFieldQuotedValue", REQUIRED, + R"({"optionalDouble": "1"})", "optional_double: 1"); // Special values. - RunValidJsonTest( - "DoubleFieldNan", REQUIRED, - R"({"optionalDouble": "NaN"})", - "optional_double: nan"); - RunValidJsonTest( - "DoubleFieldInfinity", REQUIRED, - R"({"optionalDouble": "Infinity"})", - "optional_double: inf"); - RunValidJsonTest( - "DoubleFieldNegativeInfinity", REQUIRED, - R"({"optionalDouble": "-Infinity"})", - "optional_double: -inf"); + RunValidJsonTest("DoubleFieldNan", REQUIRED, R"({"optionalDouble": "NaN"})", + "optional_double: nan"); + RunValidJsonTest("DoubleFieldInfinity", REQUIRED, + R"({"optionalDouble": "Infinity"})", "optional_double: inf"); + RunValidJsonTest("DoubleFieldNegativeInfinity", REQUIRED, + R"({"optionalDouble": "-Infinity"})", + "optional_double: -inf"); // Non-canonical Nan will be correctly normalized. { TestAllTypesProto3 message; message.set_optional_double( WireFormatLite::DecodeDouble(int64{0x7FFA123456789ABC})); - RunValidJsonTestWithProtobufInput( - "DoubleFieldNormalizeQuietNan", REQUIRED, message, - "optional_double: nan"); + RunValidJsonTestWithProtobufInput("DoubleFieldNormalizeQuietNan", REQUIRED, + message, "optional_double: nan"); message.set_optional_double( WireFormatLite::DecodeDouble(uint64{0xFFFBCBA987654321})); - RunValidJsonTestWithProtobufInput( - "DoubleFieldNormalizeSignalingNan", REQUIRED, message, - "optional_double: nan"); + RunValidJsonTestWithProtobufInput("DoubleFieldNormalizeSignalingNan", + REQUIRED, message, + "optional_double: nan"); } // Special values must be quoted. - ExpectParseFailureForJson( - "DoubleFieldNanNotQuoted", RECOMMENDED, - R"({"optionalDouble": NaN})"); - ExpectParseFailureForJson( - "DoubleFieldInfinityNotQuoted", RECOMMENDED, - R"({"optionalDouble": Infinity})"); - ExpectParseFailureForJson( - "DoubleFieldNegativeInfinityNotQuoted", RECOMMENDED, - R"({"optionalDouble": -Infinity})"); + ExpectParseFailureForJson("DoubleFieldNanNotQuoted", RECOMMENDED, + R"({"optionalDouble": NaN})"); + ExpectParseFailureForJson("DoubleFieldInfinityNotQuoted", RECOMMENDED, + R"({"optionalDouble": Infinity})"); + ExpectParseFailureForJson("DoubleFieldNegativeInfinityNotQuoted", RECOMMENDED, + R"({"optionalDouble": -Infinity})"); // Parsers should reject out-of-bound values. - ExpectParseFailureForJson( - "DoubleFieldTooSmall", REQUIRED, - R"({"optionalDouble": -1.89769e+308})"); - ExpectParseFailureForJson( - "DoubleFieldTooLarge", REQUIRED, - R"({"optionalDouble": +1.89769e+308})"); + ExpectParseFailureForJson("DoubleFieldTooSmall", REQUIRED, + R"({"optionalDouble": -1.89769e+308})"); + ExpectParseFailureForJson("DoubleFieldTooLarge", REQUIRED, + R"({"optionalDouble": +1.89769e+308})"); // Enum fields. - RunValidJsonTest( - "EnumField", REQUIRED, - R"({"optionalNestedEnum": "FOO"})", - "optional_nested_enum: FOO"); + RunValidJsonTest("EnumField", REQUIRED, R"({"optionalNestedEnum": "FOO"})", + "optional_nested_enum: FOO"); // Enum fields with alias - RunValidJsonTest( - "EnumFieldWithAlias", REQUIRED, - R"({"optionalAliasedEnum": "ALIAS_BAZ"})", - "optional_aliased_enum: ALIAS_BAZ"); - RunValidJsonTest( - "EnumFieldWithAliasUseAlias", REQUIRED, - R"({"optionalAliasedEnum": "MOO"})", - "optional_aliased_enum: ALIAS_BAZ"); - RunValidJsonTest( - "EnumFieldWithAliasLowerCase", REQUIRED, - R"({"optionalAliasedEnum": "moo"})", - "optional_aliased_enum: ALIAS_BAZ"); - RunValidJsonTest( - "EnumFieldWithAliasDifferentCase", REQUIRED, - R"({"optionalAliasedEnum": "bAz"})", - "optional_aliased_enum: ALIAS_BAZ"); + RunValidJsonTest("EnumFieldWithAlias", REQUIRED, + R"({"optionalAliasedEnum": "ALIAS_BAZ"})", + "optional_aliased_enum: ALIAS_BAZ"); + RunValidJsonTest("EnumFieldWithAliasUseAlias", REQUIRED, + R"({"optionalAliasedEnum": "MOO"})", + "optional_aliased_enum: ALIAS_BAZ"); + RunValidJsonTest("EnumFieldWithAliasLowerCase", REQUIRED, + R"({"optionalAliasedEnum": "moo"})", + "optional_aliased_enum: ALIAS_BAZ"); + RunValidJsonTest("EnumFieldWithAliasDifferentCase", REQUIRED, + R"({"optionalAliasedEnum": "bAz"})", + "optional_aliased_enum: ALIAS_BAZ"); // Enum values must be represented as strings. - ExpectParseFailureForJson( - "EnumFieldNotQuoted", REQUIRED, - R"({"optionalNestedEnum": FOO})"); + ExpectParseFailureForJson("EnumFieldNotQuoted", REQUIRED, + R"({"optionalNestedEnum": FOO})"); // Numeric values are allowed. - RunValidJsonTest( - "EnumFieldNumericValueZero", REQUIRED, - R"({"optionalNestedEnum": 0})", - "optional_nested_enum: FOO"); - RunValidJsonTest( - "EnumFieldNumericValueNonZero", REQUIRED, - R"({"optionalNestedEnum": 1})", - "optional_nested_enum: BAR"); + RunValidJsonTest("EnumFieldNumericValueZero", REQUIRED, + R"({"optionalNestedEnum": 0})", "optional_nested_enum: FOO"); + RunValidJsonTest("EnumFieldNumericValueNonZero", REQUIRED, + R"({"optionalNestedEnum": 1})", "optional_nested_enum: BAR"); // Unknown enum values are represented as numeric values. RunValidJsonTestWithValidator( "EnumFieldUnknownValue", REQUIRED, R"({"optionalNestedEnum": 123})", [](const Json::Value& value) { return value["optionalNestedEnum"].type() == Json::intValue && - value["optionalNestedEnum"].asInt() == 123; + value["optionalNestedEnum"].asInt() == 123; }, true); // String fields. - RunValidJsonTest( - "StringField", REQUIRED, - R"({"optionalString": "Hello world!"})", - "optional_string: \"Hello world!\""); - RunValidJsonTest( - "StringFieldUnicode", REQUIRED, - // Google in Chinese. - R"({"optionalString": "谷歌"})", - R"(optional_string: "谷歌")"); - RunValidJsonTest( - "StringFieldEscape", REQUIRED, - R"({"optionalString": "\"\\\/\b\f\n\r\t"})", - R"(optional_string: "\"\\/\b\f\n\r\t")"); - RunValidJsonTest( - "StringFieldUnicodeEscape", REQUIRED, - R"({"optionalString": "\u8C37\u6B4C"})", - R"(optional_string: "谷歌")"); - RunValidJsonTest( - "StringFieldUnicodeEscapeWithLowercaseHexLetters", REQUIRED, - R"({"optionalString": "\u8c37\u6b4c"})", - R"(optional_string: "谷歌")"); + RunValidJsonTest("StringField", REQUIRED, + R"({"optionalString": "Hello world!"})", + "optional_string: \"Hello world!\""); + RunValidJsonTest("StringFieldUnicode", REQUIRED, + // Google in Chinese. + R"({"optionalString": "谷歌"})", + R"(optional_string: "谷歌")"); + RunValidJsonTest("StringFieldEscape", REQUIRED, + R"({"optionalString": "\"\\\/\b\f\n\r\t"})", + R"(optional_string: "\"\\/\b\f\n\r\t")"); + RunValidJsonTest("StringFieldUnicodeEscape", REQUIRED, + R"({"optionalString": "\u8C37\u6B4C"})", + R"(optional_string: "谷歌")"); + RunValidJsonTest("StringFieldUnicodeEscapeWithLowercaseHexLetters", REQUIRED, + R"({"optionalString": "\u8c37\u6b4c"})", + R"(optional_string: "谷歌")"); RunValidJsonTest( "StringFieldSurrogatePair", REQUIRED, // The character is an emoji: grinning face with smiling eyes. 😁 @@ -2535,48 +2399,35 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForNonRepeatedTypes() { R"(optional_string: "\xF0\x9F\x98\x81")"); // Unicode escapes must start with "\u" (lowercase u). - ExpectParseFailureForJson( - "StringFieldUppercaseEscapeLetter", RECOMMENDED, - R"({"optionalString": "\U8C37\U6b4C"})"); - ExpectParseFailureForJson( - "StringFieldInvalidEscape", RECOMMENDED, - R"({"optionalString": "\uXXXX\u6B4C"})"); - ExpectParseFailureForJson( - "StringFieldUnterminatedEscape", RECOMMENDED, - R"({"optionalString": "\u8C3"})"); - ExpectParseFailureForJson( - "StringFieldUnpairedHighSurrogate", RECOMMENDED, - R"({"optionalString": "\uD800"})"); - ExpectParseFailureForJson( - "StringFieldUnpairedLowSurrogate", RECOMMENDED, - R"({"optionalString": "\uDC00"})"); - ExpectParseFailureForJson( - "StringFieldSurrogateInWrongOrder", RECOMMENDED, - R"({"optionalString": "\uDE01\uD83D"})"); - ExpectParseFailureForJson( - "StringFieldNotAString", REQUIRED, - R"({"optionalString": 12345})"); + ExpectParseFailureForJson("StringFieldUppercaseEscapeLetter", RECOMMENDED, + R"({"optionalString": "\U8C37\U6b4C"})"); + ExpectParseFailureForJson("StringFieldInvalidEscape", RECOMMENDED, + R"({"optionalString": "\uXXXX\u6B4C"})"); + ExpectParseFailureForJson("StringFieldUnterminatedEscape", RECOMMENDED, + R"({"optionalString": "\u8C3"})"); + ExpectParseFailureForJson("StringFieldUnpairedHighSurrogate", RECOMMENDED, + R"({"optionalString": "\uD800"})"); + ExpectParseFailureForJson("StringFieldUnpairedLowSurrogate", RECOMMENDED, + R"({"optionalString": "\uDC00"})"); + ExpectParseFailureForJson("StringFieldSurrogateInWrongOrder", RECOMMENDED, + R"({"optionalString": "\uDE01\uD83D"})"); + ExpectParseFailureForJson("StringFieldNotAString", REQUIRED, + R"({"optionalString": 12345})"); // Bytes fields. - RunValidJsonTest( - "BytesField", REQUIRED, - R"({"optionalBytes": "AQI="})", - R"(optional_bytes: "\x01\x02")"); - RunValidJsonTest( - "BytesFieldBase64Url", RECOMMENDED, - R"({"optionalBytes": "-_"})", - R"(optional_bytes: "\xfb")"); + RunValidJsonTest("BytesField", REQUIRED, R"({"optionalBytes": "AQI="})", + R"(optional_bytes: "\x01\x02")"); + RunValidJsonTest("BytesFieldBase64Url", RECOMMENDED, + R"({"optionalBytes": "-_"})", R"(optional_bytes: "\xfb")"); // Message fields. - RunValidJsonTest( - "MessageField", REQUIRED, - R"({"optionalNestedMessage": {"a": 1234}})", - "optional_nested_message: {a: 1234}"); + RunValidJsonTest("MessageField", REQUIRED, + R"({"optionalNestedMessage": {"a": 1234}})", + "optional_nested_message: {a: 1234}"); // Oneof fields. - ExpectParseFailureForJson( - "OneofFieldDuplicate", REQUIRED, - R"({"oneofUint32": 1, "oneofString": "test"})"); + ExpectParseFailureForJson("OneofFieldDuplicate", REQUIRED, + R"({"oneofUint32": 1, "oneofString": "test"})"); RunValidJsonTest("OneofFieldNullFirst", REQUIRED, R"({"oneofUint32": null, "oneofString": "test"})", "oneof_string: \"test\""); @@ -2588,84 +2439,64 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForNonRepeatedTypes() { TestAllTypesProto2 messageProto2; TestOneofMessage(messageProto3, true); TestOneofMessage(messageProto2, false); - RunValidJsonTest( - "OneofZeroUint32", RECOMMENDED, - R"({"oneofUint32": 0})", "oneof_uint32: 0"); - RunValidJsonTest( - "OneofZeroMessage", RECOMMENDED, - R"({"oneofNestedMessage": {}})", "oneof_nested_message: {}"); - RunValidJsonTest( - "OneofZeroString", RECOMMENDED, - R"({"oneofString": ""})", "oneof_string: \"\""); - RunValidJsonTest( - "OneofZeroBytes", RECOMMENDED, - R"({"oneofBytes": ""})", "oneof_bytes: \"\""); - RunValidJsonTest( - "OneofZeroBool", RECOMMENDED, - R"({"oneofBool": false})", "oneof_bool: false"); - RunValidJsonTest( - "OneofZeroUint64", RECOMMENDED, - R"({"oneofUint64": 0})", "oneof_uint64: 0"); - RunValidJsonTest( - "OneofZeroFloat", RECOMMENDED, - R"({"oneofFloat": 0.0})", "oneof_float: 0"); - RunValidJsonTest( - "OneofZeroDouble", RECOMMENDED, - R"({"oneofDouble": 0.0})", "oneof_double: 0"); - RunValidJsonTest( - "OneofZeroEnum", RECOMMENDED, - R"({"oneofEnum":"FOO"})", "oneof_enum: FOO"); + RunValidJsonTest("OneofZeroUint32", RECOMMENDED, R"({"oneofUint32": 0})", + "oneof_uint32: 0"); + RunValidJsonTest("OneofZeroMessage", RECOMMENDED, + R"({"oneofNestedMessage": {}})", "oneof_nested_message: {}"); + RunValidJsonTest("OneofZeroString", RECOMMENDED, R"({"oneofString": ""})", + "oneof_string: \"\""); + RunValidJsonTest("OneofZeroBytes", RECOMMENDED, R"({"oneofBytes": ""})", + "oneof_bytes: \"\""); + RunValidJsonTest("OneofZeroBool", RECOMMENDED, R"({"oneofBool": false})", + "oneof_bool: false"); + RunValidJsonTest("OneofZeroUint64", RECOMMENDED, R"({"oneofUint64": 0})", + "oneof_uint64: 0"); + RunValidJsonTest("OneofZeroFloat", RECOMMENDED, R"({"oneofFloat": 0.0})", + "oneof_float: 0"); + RunValidJsonTest("OneofZeroDouble", RECOMMENDED, R"({"oneofDouble": 0.0})", + "oneof_double: 0"); + RunValidJsonTest("OneofZeroEnum", RECOMMENDED, R"({"oneofEnum":"FOO"})", + "oneof_enum: FOO"); // Map fields. - RunValidJsonTest( - "Int32MapField", REQUIRED, - R"({"mapInt32Int32": {"1": 2, "3": 4}})", - "map_int32_int32: {key: 1 value: 2}" - "map_int32_int32: {key: 3 value: 4}"); - ExpectParseFailureForJson( - "Int32MapFieldKeyNotQuoted", RECOMMENDED, - R"({"mapInt32Int32": {1: 2, 3: 4}})"); - RunValidJsonTest( - "Uint32MapField", REQUIRED, - R"({"mapUint32Uint32": {"1": 2, "3": 4}})", - "map_uint32_uint32: {key: 1 value: 2}" - "map_uint32_uint32: {key: 3 value: 4}"); - ExpectParseFailureForJson( - "Uint32MapFieldKeyNotQuoted", RECOMMENDED, - R"({"mapUint32Uint32": {1: 2, 3: 4}})"); - RunValidJsonTest( - "Int64MapField", REQUIRED, - R"({"mapInt64Int64": {"1": 2, "3": 4}})", - "map_int64_int64: {key: 1 value: 2}" - "map_int64_int64: {key: 3 value: 4}"); - ExpectParseFailureForJson( - "Int64MapFieldKeyNotQuoted", RECOMMENDED, - R"({"mapInt64Int64": {1: 2, 3: 4}})"); - RunValidJsonTest( - "Uint64MapField", REQUIRED, - R"({"mapUint64Uint64": {"1": 2, "3": 4}})", - "map_uint64_uint64: {key: 1 value: 2}" - "map_uint64_uint64: {key: 3 value: 4}"); - ExpectParseFailureForJson( - "Uint64MapFieldKeyNotQuoted", RECOMMENDED, - R"({"mapUint64Uint64": {1: 2, 3: 4}})"); - RunValidJsonTest( - "BoolMapField", REQUIRED, - R"({"mapBoolBool": {"true": true, "false": false}})", - "map_bool_bool: {key: true value: true}" - "map_bool_bool: {key: false value: false}"); - ExpectParseFailureForJson( - "BoolMapFieldKeyNotQuoted", RECOMMENDED, - R"({"mapBoolBool": {true: true, false: false}})"); - RunValidJsonTest( - "MessageMapField", REQUIRED, - R"({ + RunValidJsonTest("Int32MapField", REQUIRED, + R"({"mapInt32Int32": {"1": 2, "3": 4}})", + "map_int32_int32: {key: 1 value: 2}" + "map_int32_int32: {key: 3 value: 4}"); + ExpectParseFailureForJson("Int32MapFieldKeyNotQuoted", RECOMMENDED, + R"({"mapInt32Int32": {1: 2, 3: 4}})"); + RunValidJsonTest("Uint32MapField", REQUIRED, + R"({"mapUint32Uint32": {"1": 2, "3": 4}})", + "map_uint32_uint32: {key: 1 value: 2}" + "map_uint32_uint32: {key: 3 value: 4}"); + ExpectParseFailureForJson("Uint32MapFieldKeyNotQuoted", RECOMMENDED, + R"({"mapUint32Uint32": {1: 2, 3: 4}})"); + RunValidJsonTest("Int64MapField", REQUIRED, + R"({"mapInt64Int64": {"1": 2, "3": 4}})", + "map_int64_int64: {key: 1 value: 2}" + "map_int64_int64: {key: 3 value: 4}"); + ExpectParseFailureForJson("Int64MapFieldKeyNotQuoted", RECOMMENDED, + R"({"mapInt64Int64": {1: 2, 3: 4}})"); + RunValidJsonTest("Uint64MapField", REQUIRED, + R"({"mapUint64Uint64": {"1": 2, "3": 4}})", + "map_uint64_uint64: {key: 1 value: 2}" + "map_uint64_uint64: {key: 3 value: 4}"); + ExpectParseFailureForJson("Uint64MapFieldKeyNotQuoted", RECOMMENDED, + R"({"mapUint64Uint64": {1: 2, 3: 4}})"); + RunValidJsonTest("BoolMapField", REQUIRED, + R"({"mapBoolBool": {"true": true, "false": false}})", + "map_bool_bool: {key: true value: true}" + "map_bool_bool: {key: false value: false}"); + ExpectParseFailureForJson("BoolMapFieldKeyNotQuoted", RECOMMENDED, + R"({"mapBoolBool": {true: true, false: false}})"); + RunValidJsonTest("MessageMapField", REQUIRED, + R"({ "mapStringNestedMessage": { "hello": {"a": 1234}, "world": {"a": 5678} } })", - R"( + R"( map_string_nested_message: { key: "hello" value: {a: 1234} @@ -2676,18 +2507,15 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForNonRepeatedTypes() { } )"); // Since Map keys are represented as JSON strings, escaping should be allowed. - RunValidJsonTest( - "Int32MapEscapedKey", REQUIRED, - R"({"mapInt32Int32": {"\u0031": 2}})", - "map_int32_int32: {key: 1 value: 2}"); - RunValidJsonTest( - "Int64MapEscapedKey", REQUIRED, - R"({"mapInt64Int64": {"\u0031": 2}})", - "map_int64_int64: {key: 1 value: 2}"); - RunValidJsonTest( - "BoolMapEscapedKey", REQUIRED, - R"({"mapBoolBool": {"tr\u0075e": true}})", - "map_bool_bool: {key: true value: true}"); + RunValidJsonTest("Int32MapEscapedKey", REQUIRED, + R"({"mapInt32Int32": {"\u0031": 2}})", + "map_int32_int32: {key: 1 value: 2}"); + RunValidJsonTest("Int64MapEscapedKey", REQUIRED, + R"({"mapInt64Int64": {"\u0031": 2}})", + "map_int64_int64: {key: 1 value: 2}"); + RunValidJsonTest("BoolMapEscapedKey", REQUIRED, + R"({"mapBoolBool": {"tr\u0075e": true}})", + "map_bool_bool: {key: true value: true}"); // http://www.rfc-editor.org/rfc/rfc7159.txt says strings have to use double // quotes. @@ -2761,9 +2589,8 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForRepeatedTypes() { void BinaryAndJsonConformanceSuite::RunJsonTestsForNullTypes() { // "null" is accepted for all fields types. - RunValidJsonTest( - "AllFieldAcceptNull", REQUIRED, - R"({ + RunValidJsonTest("AllFieldAcceptNull", REQUIRED, + R"({ "optionalInt32": null, "optionalInt64": null, "optionalUint32": null, @@ -2802,64 +2629,52 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForNullTypes() { "mapBoolBool": null, "mapStringNestedMessage": null })", - ""); + ""); // Repeated field elements cannot be null. - ExpectParseFailureForJson( - "RepeatedFieldPrimitiveElementIsNull", RECOMMENDED, - R"({"repeatedInt32": [1, null, 2]})"); + ExpectParseFailureForJson("RepeatedFieldPrimitiveElementIsNull", RECOMMENDED, + R"({"repeatedInt32": [1, null, 2]})"); ExpectParseFailureForJson( "RepeatedFieldMessageElementIsNull", RECOMMENDED, R"({"repeatedNestedMessage": [{"a":1}, null, {"a":2}]})"); // Map field keys cannot be null. - ExpectParseFailureForJson( - "MapFieldKeyIsNull", RECOMMENDED, - R"({"mapInt32Int32": {null: 1}})"); + ExpectParseFailureForJson("MapFieldKeyIsNull", RECOMMENDED, + R"({"mapInt32Int32": {null: 1}})"); // Map field values cannot be null. - ExpectParseFailureForJson( - "MapFieldValueIsNull", RECOMMENDED, - R"({"mapInt32Int32": {"0": null}})"); + ExpectParseFailureForJson("MapFieldValueIsNull", RECOMMENDED, + R"({"mapInt32Int32": {"0": null}})"); } void BinaryAndJsonConformanceSuite::RunJsonTestsForWrapperTypes() { RunValidJsonTest("OptionalBoolWrapper", REQUIRED, R"({"optionalBoolWrapper": false})", "optional_bool_wrapper: {value: false}"); - RunValidJsonTest( - "OptionalInt32Wrapper", REQUIRED, - R"({"optionalInt32Wrapper": 0})", - "optional_int32_wrapper: {value: 0}"); - RunValidJsonTest( - "OptionalUint32Wrapper", REQUIRED, - R"({"optionalUint32Wrapper": 0})", - "optional_uint32_wrapper: {value: 0}"); - RunValidJsonTest( - "OptionalInt64Wrapper", REQUIRED, - R"({"optionalInt64Wrapper": 0})", - "optional_int64_wrapper: {value: 0}"); - RunValidJsonTest( - "OptionalUint64Wrapper", REQUIRED, - R"({"optionalUint64Wrapper": 0})", - "optional_uint64_wrapper: {value: 0}"); - RunValidJsonTest( - "OptionalFloatWrapper", REQUIRED, - R"({"optionalFloatWrapper": 0})", - "optional_float_wrapper: {value: 0}"); - RunValidJsonTest( - "OptionalDoubleWrapper", REQUIRED, - R"({"optionalDoubleWrapper": 0})", - "optional_double_wrapper: {value: 0}"); - RunValidJsonTest( - "OptionalStringWrapper", REQUIRED, - R"({"optionalStringWrapper": ""})", - R"(optional_string_wrapper: {value: ""})"); - RunValidJsonTest( - "OptionalBytesWrapper", REQUIRED, - R"({"optionalBytesWrapper": ""})", - R"(optional_bytes_wrapper: {value: ""})"); - RunValidJsonTest( - "OptionalWrapperTypesWithNonDefaultValue", REQUIRED, - R"({ + RunValidJsonTest("OptionalInt32Wrapper", REQUIRED, + R"({"optionalInt32Wrapper": 0})", + "optional_int32_wrapper: {value: 0}"); + RunValidJsonTest("OptionalUint32Wrapper", REQUIRED, + R"({"optionalUint32Wrapper": 0})", + "optional_uint32_wrapper: {value: 0}"); + RunValidJsonTest("OptionalInt64Wrapper", REQUIRED, + R"({"optionalInt64Wrapper": 0})", + "optional_int64_wrapper: {value: 0}"); + RunValidJsonTest("OptionalUint64Wrapper", REQUIRED, + R"({"optionalUint64Wrapper": 0})", + "optional_uint64_wrapper: {value: 0}"); + RunValidJsonTest("OptionalFloatWrapper", REQUIRED, + R"({"optionalFloatWrapper": 0})", + "optional_float_wrapper: {value: 0}"); + RunValidJsonTest("OptionalDoubleWrapper", REQUIRED, + R"({"optionalDoubleWrapper": 0})", + "optional_double_wrapper: {value: 0}"); + RunValidJsonTest("OptionalStringWrapper", REQUIRED, + R"({"optionalStringWrapper": ""})", + R"(optional_string_wrapper: {value: ""})"); + RunValidJsonTest("OptionalBytesWrapper", REQUIRED, + R"({"optionalBytesWrapper": ""})", + R"(optional_bytes_wrapper: {value: ""})"); + RunValidJsonTest("OptionalWrapperTypesWithNonDefaultValue", REQUIRED, + R"({ "optionalBoolWrapper": true, "optionalInt32Wrapper": 1, "optionalUint32Wrapper": 1, @@ -2870,7 +2685,7 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForWrapperTypes() { "optionalStringWrapper": "1", "optionalBytesWrapper": "AQI=" })", - R"( + R"( optional_bool_wrapper: {value: true} optional_int32_wrapper: {value: 1} optional_uint32_wrapper: {value: 1} @@ -2881,58 +2696,48 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForWrapperTypes() { optional_string_wrapper: {value: "1"} optional_bytes_wrapper: {value: "\x01\x02"} )"); - RunValidJsonTest( - "RepeatedBoolWrapper", REQUIRED, - R"({"repeatedBoolWrapper": [true, false]})", - "repeated_bool_wrapper: {value: true}" - "repeated_bool_wrapper: {value: false}"); - RunValidJsonTest( - "RepeatedInt32Wrapper", REQUIRED, - R"({"repeatedInt32Wrapper": [0, 1]})", - "repeated_int32_wrapper: {value: 0}" - "repeated_int32_wrapper: {value: 1}"); - RunValidJsonTest( - "RepeatedUint32Wrapper", REQUIRED, - R"({"repeatedUint32Wrapper": [0, 1]})", - "repeated_uint32_wrapper: {value: 0}" - "repeated_uint32_wrapper: {value: 1}"); - RunValidJsonTest( - "RepeatedInt64Wrapper", REQUIRED, - R"({"repeatedInt64Wrapper": [0, 1]})", - "repeated_int64_wrapper: {value: 0}" - "repeated_int64_wrapper: {value: 1}"); - RunValidJsonTest( - "RepeatedUint64Wrapper", REQUIRED, - R"({"repeatedUint64Wrapper": [0, 1]})", - "repeated_uint64_wrapper: {value: 0}" - "repeated_uint64_wrapper: {value: 1}"); - RunValidJsonTest( - "RepeatedFloatWrapper", REQUIRED, - R"({"repeatedFloatWrapper": [0, 1]})", - "repeated_float_wrapper: {value: 0}" - "repeated_float_wrapper: {value: 1}"); - RunValidJsonTest( - "RepeatedDoubleWrapper", REQUIRED, - R"({"repeatedDoubleWrapper": [0, 1]})", - "repeated_double_wrapper: {value: 0}" - "repeated_double_wrapper: {value: 1}"); - RunValidJsonTest( - "RepeatedStringWrapper", REQUIRED, - R"({"repeatedStringWrapper": ["", "AQI="]})", - R"( + RunValidJsonTest("RepeatedBoolWrapper", REQUIRED, + R"({"repeatedBoolWrapper": [true, false]})", + "repeated_bool_wrapper: {value: true}" + "repeated_bool_wrapper: {value: false}"); + RunValidJsonTest("RepeatedInt32Wrapper", REQUIRED, + R"({"repeatedInt32Wrapper": [0, 1]})", + "repeated_int32_wrapper: {value: 0}" + "repeated_int32_wrapper: {value: 1}"); + RunValidJsonTest("RepeatedUint32Wrapper", REQUIRED, + R"({"repeatedUint32Wrapper": [0, 1]})", + "repeated_uint32_wrapper: {value: 0}" + "repeated_uint32_wrapper: {value: 1}"); + RunValidJsonTest("RepeatedInt64Wrapper", REQUIRED, + R"({"repeatedInt64Wrapper": [0, 1]})", + "repeated_int64_wrapper: {value: 0}" + "repeated_int64_wrapper: {value: 1}"); + RunValidJsonTest("RepeatedUint64Wrapper", REQUIRED, + R"({"repeatedUint64Wrapper": [0, 1]})", + "repeated_uint64_wrapper: {value: 0}" + "repeated_uint64_wrapper: {value: 1}"); + RunValidJsonTest("RepeatedFloatWrapper", REQUIRED, + R"({"repeatedFloatWrapper": [0, 1]})", + "repeated_float_wrapper: {value: 0}" + "repeated_float_wrapper: {value: 1}"); + RunValidJsonTest("RepeatedDoubleWrapper", REQUIRED, + R"({"repeatedDoubleWrapper": [0, 1]})", + "repeated_double_wrapper: {value: 0}" + "repeated_double_wrapper: {value: 1}"); + RunValidJsonTest("RepeatedStringWrapper", REQUIRED, + R"({"repeatedStringWrapper": ["", "AQI="]})", + R"( repeated_string_wrapper: {value: ""} repeated_string_wrapper: {value: "AQI="} )"); - RunValidJsonTest( - "RepeatedBytesWrapper", REQUIRED, - R"({"repeatedBytesWrapper": ["", "AQI="]})", - R"( + RunValidJsonTest("RepeatedBytesWrapper", REQUIRED, + R"({"repeatedBytesWrapper": ["", "AQI="]})", + R"( repeated_bytes_wrapper: {value: ""} repeated_bytes_wrapper: {value: "\x01\x02"} )"); - RunValidJsonTest( - "WrapperTypesWithNullValue", REQUIRED, - R"({ + RunValidJsonTest("WrapperTypesWithNullValue", REQUIRED, + R"({ "optionalBoolWrapper": null, "optionalInt32Wrapper": null, "optionalUint32Wrapper": null, @@ -2952,7 +2757,7 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForWrapperTypes() { "repeatedStringWrapper": null, "repeatedBytesWrapper": null })", - ""); + ""); // Duration RunValidJsonTest( @@ -2963,15 +2768,12 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForWrapperTypes() { "DurationMaxValue", REQUIRED, R"({"optionalDuration": "315576000000.999999999s"})", "optional_duration: {seconds: 315576000000 nanos: 999999999}"); - RunValidJsonTest( - "DurationRepeatedValue", REQUIRED, - R"({"repeatedDuration": ["1.5s", "-1.5s"]})", - "repeated_duration: {seconds: 1 nanos: 500000000}" - "repeated_duration: {seconds: -1 nanos: -500000000}"); - RunValidJsonTest( - "DurationNull", REQUIRED, - R"({"optionalDuration": null})", - ""); + RunValidJsonTest("DurationRepeatedValue", REQUIRED, + R"({"repeatedDuration": ["1.5s", "-1.5s"]})", + "repeated_duration: {seconds: 1 nanos: 500000000}" + "repeated_duration: {seconds: -1 nanos: -500000000}"); + RunValidJsonTest("DurationNull", REQUIRED, R"({"optionalDuration": null})", + ""); RunValidJsonTest("DurationNegativeSeconds", REQUIRED, R"({"optionalDuration": "-5s"})", "optional_duration: {seconds: -5 nanos: 0}"); @@ -2979,9 +2781,8 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForWrapperTypes() { R"({"optionalDuration": "-0.5s"})", "optional_duration: {seconds: 0 nanos: -500000000}"); - ExpectParseFailureForJson( - "DurationMissingS", REQUIRED, - R"({"optionalDuration": "1"})"); + ExpectParseFailureForJson("DurationMissingS", REQUIRED, + R"({"optionalDuration": "1"})"); ExpectParseFailureForJson( "DurationJsonInputTooSmall", REQUIRED, R"({"optionalDuration": "-315576000001.000000000s"})"); @@ -3025,10 +2826,9 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForWrapperTypes() { true); // Timestamp - RunValidJsonTest( - "TimestampMinValue", REQUIRED, - R"({"optionalTimestamp": "0001-01-01T00:00:00Z"})", - "optional_timestamp: {seconds: -62135596800}"); + RunValidJsonTest("TimestampMinValue", REQUIRED, + R"({"optionalTimestamp": "0001-01-01T00:00:00Z"})", + "optional_timestamp: {seconds: -62135596800}"); RunValidJsonTest( "TimestampMaxValue", REQUIRED, R"({"optionalTimestamp": "9999-12-31T23:59:59.999999999Z"})", @@ -3052,35 +2852,26 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForWrapperTypes() { RunValidJsonTest("TimestampWithNegativeOffset", REQUIRED, R"({"optionalTimestamp": "1969-12-31T16:00:01-08:00"})", "optional_timestamp: {seconds: 1}"); - RunValidJsonTest( - "TimestampNull", REQUIRED, - R"({"optionalTimestamp": null})", - ""); + RunValidJsonTest("TimestampNull", REQUIRED, R"({"optionalTimestamp": null})", + ""); - ExpectParseFailureForJson( - "TimestampJsonInputTooSmall", REQUIRED, - R"({"optionalTimestamp": "0000-01-01T00:00:00Z"})"); + ExpectParseFailureForJson("TimestampJsonInputTooSmall", REQUIRED, + R"({"optionalTimestamp": "0000-01-01T00:00:00Z"})"); ExpectParseFailureForJson( "TimestampJsonInputTooLarge", REQUIRED, R"({"optionalTimestamp": "10000-01-01T00:00:00Z"})"); - ExpectParseFailureForJson( - "TimestampJsonInputMissingZ", REQUIRED, - R"({"optionalTimestamp": "0001-01-01T00:00:00"})"); - ExpectParseFailureForJson( - "TimestampJsonInputMissingT", REQUIRED, - R"({"optionalTimestamp": "0001-01-01 00:00:00Z"})"); - ExpectParseFailureForJson( - "TimestampJsonInputLowercaseZ", REQUIRED, - R"({"optionalTimestamp": "0001-01-01T00:00:00z"})"); - ExpectParseFailureForJson( - "TimestampJsonInputLowercaseT", REQUIRED, - R"({"optionalTimestamp": "0001-01-01t00:00:00Z"})"); - ExpectSerializeFailureForJson( - "TimestampProtoInputTooSmall", REQUIRED, - "optional_timestamp: {seconds: -62135596801}"); - ExpectSerializeFailureForJson( - "TimestampProtoInputTooLarge", REQUIRED, - "optional_timestamp: {seconds: 253402300800}"); + ExpectParseFailureForJson("TimestampJsonInputMissingZ", REQUIRED, + R"({"optionalTimestamp": "0001-01-01T00:00:00"})"); + ExpectParseFailureForJson("TimestampJsonInputMissingT", REQUIRED, + R"({"optionalTimestamp": "0001-01-01 00:00:00Z"})"); + ExpectParseFailureForJson("TimestampJsonInputLowercaseZ", REQUIRED, + R"({"optionalTimestamp": "0001-01-01T00:00:00z"})"); + ExpectParseFailureForJson("TimestampJsonInputLowercaseT", REQUIRED, + R"({"optionalTimestamp": "0001-01-01t00:00:00Z"})"); + ExpectSerializeFailureForJson("TimestampProtoInputTooSmall", REQUIRED, + "optional_timestamp: {seconds: -62135596801}"); + ExpectSerializeFailureForJson("TimestampProtoInputTooLarge", REQUIRED, + "optional_timestamp: {seconds: 253402300800}"); RunValidJsonTestWithValidator( "TimestampZeroNormalized", RECOMMENDED, R"({"optionalTimestamp": "1969-12-31T16:00:00-08:00"})", @@ -3122,32 +2913,24 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForWrapperTypes() { } void BinaryAndJsonConformanceSuite::RunJsonTestsForFieldMask() { - RunValidJsonTest( - "FieldMask", REQUIRED, - R"({"optionalFieldMask": "foo,barBaz"})", - R"(optional_field_mask: {paths: "foo" paths: "bar_baz"})"); - RunValidJsonTest( - "EmptyFieldMask", REQUIRED, - R"({"optionalFieldMask": ""})", - R"(optional_field_mask: {})"); - ExpectParseFailureForJson( - "FieldMaskInvalidCharacter", RECOMMENDED, - R"({"optionalFieldMask": "foo,bar_bar"})"); - ExpectSerializeFailureForJson( - "FieldMaskPathsDontRoundTrip", RECOMMENDED, - R"(optional_field_mask: {paths: "fooBar"})"); - ExpectSerializeFailureForJson( - "FieldMaskNumbersDontRoundTrip", RECOMMENDED, - R"(optional_field_mask: {paths: "foo_3_bar"})"); - ExpectSerializeFailureForJson( - "FieldMaskTooManyUnderscore", RECOMMENDED, - R"(optional_field_mask: {paths: "foo__bar"})"); + RunValidJsonTest("FieldMask", REQUIRED, + R"({"optionalFieldMask": "foo,barBaz"})", + R"(optional_field_mask: {paths: "foo" paths: "bar_baz"})"); + RunValidJsonTest("EmptyFieldMask", REQUIRED, R"({"optionalFieldMask": ""})", + R"(optional_field_mask: {})"); + ExpectParseFailureForJson("FieldMaskInvalidCharacter", RECOMMENDED, + R"({"optionalFieldMask": "foo,bar_bar"})"); + ExpectSerializeFailureForJson("FieldMaskPathsDontRoundTrip", RECOMMENDED, + R"(optional_field_mask: {paths: "fooBar"})"); + ExpectSerializeFailureForJson("FieldMaskNumbersDontRoundTrip", RECOMMENDED, + R"(optional_field_mask: {paths: "foo_3_bar"})"); + ExpectSerializeFailureForJson("FieldMaskTooManyUnderscore", RECOMMENDED, + R"(optional_field_mask: {paths: "foo__bar"})"); } void BinaryAndJsonConformanceSuite::RunJsonTestsForStruct() { - RunValidJsonTest( - "Struct", REQUIRED, - R"({ + RunValidJsonTest("Struct", REQUIRED, + R"({ "optionalStruct": { "nullValue": null, "intValue": 1234, @@ -3160,7 +2943,7 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForStruct() { } } })", - R"( + R"( optional_struct: { fields: { key: "nullValue" @@ -3210,14 +2993,13 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForStruct() { } } )"); - RunValidJsonTest( - "StructWithEmptyListValue", REQUIRED, - R"({ + RunValidJsonTest("StructWithEmptyListValue", REQUIRED, + R"({ "optionalStruct": { "listValue": [] } })", - R"( + R"( optional_struct: { fields: { key: "listValue" @@ -3231,30 +3013,20 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForStruct() { } void BinaryAndJsonConformanceSuite::RunJsonTestsForValue() { - RunValidJsonTest( - "ValueAcceptInteger", REQUIRED, - R"({"optionalValue": 1})", - "optional_value: { number_value: 1}"); - RunValidJsonTest( - "ValueAcceptFloat", REQUIRED, - R"({"optionalValue": 1.5})", - "optional_value: { number_value: 1.5}"); - RunValidJsonTest( - "ValueAcceptBool", REQUIRED, - R"({"optionalValue": false})", - "optional_value: { bool_value: false}"); - RunValidJsonTest( - "ValueAcceptNull", REQUIRED, - R"({"optionalValue": null})", - "optional_value: { null_value: NULL_VALUE}"); - RunValidJsonTest( - "ValueAcceptString", REQUIRED, - R"({"optionalValue": "hello"})", - R"(optional_value: { string_value: "hello"})"); - RunValidJsonTest( - "ValueAcceptList", REQUIRED, - R"({"optionalValue": [0, "hello"]})", - R"( + RunValidJsonTest("ValueAcceptInteger", REQUIRED, R"({"optionalValue": 1})", + "optional_value: { number_value: 1}"); + RunValidJsonTest("ValueAcceptFloat", REQUIRED, R"({"optionalValue": 1.5})", + "optional_value: { number_value: 1.5}"); + RunValidJsonTest("ValueAcceptBool", REQUIRED, R"({"optionalValue": false})", + "optional_value: { bool_value: false}"); + RunValidJsonTest("ValueAcceptNull", REQUIRED, R"({"optionalValue": null})", + "optional_value: { null_value: NULL_VALUE}"); + RunValidJsonTest("ValueAcceptString", REQUIRED, + R"({"optionalValue": "hello"})", + R"(optional_value: { string_value: "hello"})"); + RunValidJsonTest("ValueAcceptList", REQUIRED, + R"({"optionalValue": [0, "hello"]})", + R"( optional_value: { list_value: { values: { @@ -3266,10 +3038,9 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForValue() { } } )"); - RunValidJsonTest( - "ValueAcceptObject", REQUIRED, - R"({"optionalValue": {"value": 1}})", - R"( + RunValidJsonTest("ValueAcceptObject", REQUIRED, + R"({"optionalValue": {"value": 1}})", + R"( optional_value: { struct_value: { fields: { @@ -3281,12 +3052,11 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForValue() { } } )"); - RunValidJsonTest( - "RepeatedValue", REQUIRED, - R"({ + RunValidJsonTest("RepeatedValue", REQUIRED, + R"({ "repeatedValue": [["a"]] })", - R"( + R"( repeated_value: [ { list_value: { @@ -3297,12 +3067,11 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForValue() { } ] )"); - RunValidJsonTest( - "RepeatedListValue", REQUIRED, - R"({ + RunValidJsonTest("RepeatedListValue", REQUIRED, + R"({ "repeatedListValue": [["a"]] })", - R"( + R"( repeated_list_value: [ { values: [ @@ -3341,24 +3110,22 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForValue() { } void BinaryAndJsonConformanceSuite::RunJsonTestsForAny() { - RunValidJsonTest( - "Any", REQUIRED, - R"({ + RunValidJsonTest("Any", REQUIRED, + R"({ "optionalAny": { "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3", "optionalInt32": 12345 } })", - R"( + R"( optional_any: { [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] { optional_int32: 12345 } } )"); - RunValidJsonTest( - "AnyNested", REQUIRED, - R"({ + RunValidJsonTest("AnyNested", REQUIRED, + R"({ "optionalAny": { "@type": "type.googleapis.com/google.protobuf.Any", "value": { @@ -3367,7 +3134,7 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForAny() { } } })", - R"( + R"( optional_any: { [type.googleapis.com/google.protobuf.Any] { [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] { @@ -3377,15 +3144,14 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForAny() { } )"); // The special "@type" tag is not required to appear first. - RunValidJsonTest( - "AnyUnorderedTypeTag", REQUIRED, - R"({ + RunValidJsonTest("AnyUnorderedTypeTag", REQUIRED, + R"({ "optionalAny": { "optionalInt32": 12345, "@type": "type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3" } })", - R"( + R"( optional_any: { [type.googleapis.com/protobuf_test_messages.proto3.TestAllTypesProto3] { optional_int32: 12345 @@ -3393,30 +3159,28 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForAny() { } )"); // Well-known types in Any. - RunValidJsonTest( - "AnyWithInt32ValueWrapper", REQUIRED, - R"({ + RunValidJsonTest("AnyWithInt32ValueWrapper", REQUIRED, + R"({ "optionalAny": { "@type": "type.googleapis.com/google.protobuf.Int32Value", "value": 12345 } })", - R"( + R"( optional_any: { [type.googleapis.com/google.protobuf.Int32Value] { value: 12345 } } )"); - RunValidJsonTest( - "AnyWithDuration", REQUIRED, - R"({ + RunValidJsonTest("AnyWithDuration", REQUIRED, + R"({ "optionalAny": { "@type": "type.googleapis.com/google.protobuf.Duration", "value": "1.5s" } })", - R"( + R"( optional_any: { [type.googleapis.com/google.protobuf.Duration] { seconds: 1 @@ -3424,15 +3188,14 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForAny() { } } )"); - RunValidJsonTest( - "AnyWithTimestamp", REQUIRED, - R"({ + RunValidJsonTest("AnyWithTimestamp", REQUIRED, + R"({ "optionalAny": { "@type": "type.googleapis.com/google.protobuf.Timestamp", "value": "1970-01-01T00:00:00Z" } })", - R"( + R"( optional_any: { [type.googleapis.com/google.protobuf.Timestamp] { seconds: 0 @@ -3440,24 +3203,22 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForAny() { } } )"); - RunValidJsonTest( - "AnyWithFieldMask", REQUIRED, - R"({ + RunValidJsonTest("AnyWithFieldMask", REQUIRED, + R"({ "optionalAny": { "@type": "type.googleapis.com/google.protobuf.FieldMask", "value": "foo,barBaz" } })", - R"( + R"( optional_any: { [type.googleapis.com/google.protobuf.FieldMask] { paths: ["foo", "bar_baz"] } } )"); - RunValidJsonTest( - "AnyWithStruct", REQUIRED, - R"({ + RunValidJsonTest("AnyWithStruct", REQUIRED, + R"({ "optionalAny": { "@type": "type.googleapis.com/google.protobuf.Struct", "value": { @@ -3465,7 +3226,7 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForAny() { } } })", - R"( + R"( optional_any: { [type.googleapis.com/google.protobuf.Struct] { fields: { @@ -3477,9 +3238,8 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForAny() { } } )"); - RunValidJsonTest( - "AnyWithValueForJsonObject", REQUIRED, - R"({ + RunValidJsonTest("AnyWithValueForJsonObject", REQUIRED, + R"({ "optionalAny": { "@type": "type.googleapis.com/google.protobuf.Value", "value": { @@ -3487,7 +3247,7 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForAny() { } } })", - R"( + R"( optional_any: { [type.googleapis.com/google.protobuf.Value] { struct_value: { @@ -3501,15 +3261,14 @@ void BinaryAndJsonConformanceSuite::RunJsonTestsForAny() { } } )"); - RunValidJsonTest( - "AnyWithValueForInteger", REQUIRED, - R"({ + RunValidJsonTest("AnyWithValueForInteger", REQUIRED, + R"({ "optionalAny": { "@type": "type.googleapis.com/google.protobuf.Value", "value": 1 } })", - R"( + R"( optional_any: { [type.googleapis.com/google.protobuf.Value] { number_value: 1 diff --git a/conformance/text_format_conformance_suite.cc b/conformance/text_format_conformance_suite.cc index bc76453ea7..c3ba248fb1 100644 --- a/conformance/text_format_conformance_suite.cc +++ b/conformance/text_format_conformance_suite.cc @@ -33,6 +33,7 @@ #include "google/protobuf/any.pb.h" #include "google/protobuf/text_format.h" #include "google/protobuf/stubs/logging.h" +#include "absl/strings/str_cat.h" #include "conformance_test.h" #include "google/protobuf/test_messages_proto2.pb.h" #include "google/protobuf/test_messages_proto3.pb.h" @@ -220,15 +221,15 @@ void TextFormatConformanceTestSuite::RunValidUnknownTextFormatTest( TestAllTypesProto3 prototype; ConformanceRequestSetting setting1( RECOMMENDED, conformance::PROTOBUF, conformance::TEXT_FORMAT, - conformance::TEXT_FORMAT_TEST, prototype, test_name + "_Drop", - serialized_input); + conformance::TEXT_FORMAT_TEST, prototype, + absl::StrCat(test_name, "_Drop"), serialized_input); setting1.SetPrototypeMessageForCompare(message); RunValidBinaryInputTest(setting1, ""); ConformanceRequestSetting setting2( RECOMMENDED, conformance::PROTOBUF, conformance::TEXT_FORMAT, - conformance::TEXT_FORMAT_TEST, prototype, test_name + "_Print", - serialized_input); + conformance::TEXT_FORMAT_TEST, prototype, + absl::StrCat(test_name, "_Print"), serialized_input); setting2.SetPrototypeMessageForCompare(message); setting2.SetPrintUnknownFields(true); RunValidBinaryInputTest(setting2, serialized_input); @@ -532,26 +533,27 @@ void TextFormatConformanceTestSuite::RunTextFormatPerformanceTests() { void TextFormatConformanceTestSuite:: TestTextFormatPerformanceMergeMessageWithRepeatedField( const string& test_type_name, const string& message_field) { - string recursive_message = "recursive_message { " + message_field + " }"; + string recursive_message = + absl::StrCat("recursive_message { ", message_field, " }"); string input; for (size_t i = 0; i < kPerformanceRepeatCount; i++) { - input.append(recursive_message); + absl::StrAppend(&input, recursive_message); } string expected = "recursive_message { "; for (size_t i = 0; i < kPerformanceRepeatCount; i++) { - expected.append(message_field + " "); + absl::StrAppend(&expected, message_field, " "); } - expected.append("}"); + absl::StrAppend(&expected, "}"); RunValidTextFormatTestProto2WithExpected( - "TestTextFormatPerformanceMergeMessageWithRepeatedField" + - test_type_name + "Proto2", + absl::StrCat("TestTextFormatPerformanceMergeMessageWithRepeatedField", + test_type_name, "Proto2"), RECOMMENDED, input, expected); RunValidTextFormatTestWithExpected( - "TestTextFormatPerformanceMergeMessageWithRepeatedField" + - test_type_name + "Proto3", + absl::StrCat("TestTextFormatPerformanceMergeMessageWithRepeatedField", + test_type_name, "Proto3"), RECOMMENDED, input, expected); } diff --git a/src/google/protobuf/io/zero_copy_stream_unittest.cc b/src/google/protobuf/io/zero_copy_stream_unittest.cc index 4aa305e8f8..d2b12fbf6a 100644 --- a/src/google/protobuf/io/zero_copy_stream_unittest.cc +++ b/src/google/protobuf/io/zero_copy_stream_unittest.cc @@ -46,10 +46,6 @@ // "parametized tests" so that one set of tests can be used on all the // implementations. -#include -#include -#include - #ifndef _WIN32 #include #include @@ -60,15 +56,26 @@ #include #include +#include +#include #include #include #include +#include #include #include +#include "google/protobuf/stubs/common.h" +#include "google/protobuf/testing/file.h" #include "google/protobuf/testing/file.h" +#include "google/protobuf/testing/googletest.h" +#include +#include "google/protobuf/stubs/logging.h" +#include "google/protobuf/stubs/logging.h" +#include "absl/status/status.h" #include "absl/strings/cord.h" #include "absl/strings/cord_buffer.h" +#include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/io/io_win32.h" @@ -79,17 +86,6 @@ #include "google/protobuf/io/gzip_stream.h" #endif -#include "google/protobuf/stubs/common.h" -#include "google/protobuf/testing/file.h" -#include "google/protobuf/testing/googletest.h" -#include -#include "google/protobuf/stubs/logging.h" -#include "google/protobuf/stubs/logging.h" -#include "absl/status/status.h" -#include "absl/strings/cord.h" -#include "absl/strings/cord_buffer.h" -#include "absl/strings/string_view.h" - // Must be included last. #include "google/protobuf/port_def.inc" @@ -1447,7 +1443,8 @@ TEST_F(IoTest, CordOutputBufferEndsAtSizeHint) { // To test files, we create a temporary file, write, read, truncate, repeat. TEST_F(IoTest, FileIo) { - std::string filename = TestTempDir() + "/zero_copy_stream_test_file"; + std::string filename = + absl::StrCat(TestTempDir(), "/zero_copy_stream_test_file"); for (int i = 0; i < kBlockSizeCount; i++) { for (int j = 0; j < kBlockSizeCount; j++) { @@ -1544,7 +1541,8 @@ TEST_F(IoTest, BlockingFileIoWithTimeout) { #if HAVE_ZLIB TEST_F(IoTest, GzipFileIo) { - std::string filename = TestTempDir() + "/zero_copy_stream_test_file"; + std::string filename = + absl::StrCat(TestTempDir(), "/zero_copy_stream_test_file"); for (int i = 0; i < kBlockSizeCount; i++) { for (int j = 0; j < kBlockSizeCount; j++) { diff --git a/src/google/protobuf/testing/file.cc b/src/google/protobuf/testing/file.cc index 0ade2df4c2..d75aa8a2d1 100644 --- a/src/google/protobuf/testing/file.cc +++ b/src/google/protobuf/testing/file.cc @@ -46,6 +46,7 @@ #endif #include +#include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "google/protobuf/io/io_win32.h" #include "google/protobuf/stubs/logging.h" @@ -158,7 +159,8 @@ void File::DeleteRecursively(const std::string& name, void* dummy1, #ifdef _MSC_VER // This interface is so weird. WIN32_FIND_DATAA find_data; - HANDLE find_handle = FindFirstFileA((name + "/*").c_str(), &find_data); + HANDLE find_handle = + FindFirstFileA(absl::StrCat(name, "/*").c_str(), &find_data); if (find_handle == INVALID_HANDLE_VALUE) { // Just delete it, whatever it is. DeleteFileA(name.c_str()); @@ -169,7 +171,7 @@ void File::DeleteRecursively(const std::string& name, void* dummy1, do { std::string entry_name = find_data.cFileName; if (entry_name != "." && entry_name != "..") { - std::string path = name + "/" + entry_name; + std::string path = absl::StrCat(name, "/", entry_name); if (find_data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { DeleteRecursively(path, NULL, NULL); RemoveDirectoryA(path.c_str()); @@ -195,7 +197,7 @@ void File::DeleteRecursively(const std::string& name, void* dummy1, if (entry == NULL) break; std::string entry_name = entry->d_name; if (entry_name != "." && entry_name != "..") { - DeleteRecursively(name + "/" + entry_name, NULL, NULL); + DeleteRecursively(absl::StrCat(name, "/", entry_name), NULL, NULL); } } } diff --git a/src/google/protobuf/testing/googletest.cc b/src/google/protobuf/testing/googletest.cc index 8697e87fba..ab415618c8 100644 --- a/src/google/protobuf/testing/googletest.cc +++ b/src/google/protobuf/testing/googletest.cc @@ -39,6 +39,7 @@ #include #include "absl/strings/match.h" +#include "absl/strings/str_cat.h" #include "absl/strings/str_replace.h" #include "google/protobuf/io/io_win32.h" #include "google/protobuf/testing/file.h" @@ -93,15 +94,17 @@ std::string TestSourceDir() { // src/.../descriptor.cc. It is important to look for a particular file, // keeping in mind that with Bazel builds the directory structure under // bazel-bin/ looks similar to the main directory tree in the Git repo. - while (!File::Exists(prefix + "/src/google/protobuf/descriptor.cc")) { + while (!File::Exists( + absl::StrCat(prefix, "/src/google/protobuf/descriptor.cc"))) { if (!File::Exists(prefix)) { GOOGLE_LOG(FATAL) << "Could not find protobuf source code. Please run tests from " "somewhere within the protobuf source package."; } - prefix += "/.."; + absl::StrAppend(&prefix, "/.."); } - return prefix + "/src"; + absl::StrAppend(&prefix, "/src"); + return prefix; #endif // GOOGLE_PROTOBUF_TEST_SOURCE_PATH #else return "third_party/protobuf/src"; @@ -113,9 +116,9 @@ namespace { std::string GetTemporaryDirectoryName() { // Tests run under Bazel "should not" use /tmp. Bazel sets this environment // variable for tests to use instead. - char *from_environment = getenv("TEST_TMPDIR"); + char* from_environment = getenv("TEST_TMPDIR"); if (from_environment != NULL && from_environment[0] != '\0') { - return std::string(from_environment) + "/protobuf_tmpdir"; + return absl::StrCat(from_environment, "/protobuf_tmpdir"); } // tmpnam() is generally not considered safe but we're only using it for @@ -176,7 +179,8 @@ class TempDirDeleter { // Stick a file in the directory that tells people what this is, in case // we abort and don't get a chance to delete it. - File::WriteStringToFileOrDie("", name_ + "/TEMP_DIR_FOR_PROTOBUF_TESTS"); + File::WriteStringToFileOrDie( + "", absl::StrCat(name_, "/TEMP_DIR_FOR_PROTOBUF_TESTS")); } return name_; } @@ -201,7 +205,7 @@ static int original_stderr_ = -1; void CaptureTestStdout() { GOOGLE_CHECK_EQ(original_stdout_, -1) << "Already capturing."; - stdout_capture_filename_ = TestTempDir() + "/captured_stdout"; + stdout_capture_filename_ = absl::StrCat(TestTempDir(), "/captured_stdout"); int fd = open(stdout_capture_filename_.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_BINARY, 0777); @@ -216,7 +220,7 @@ void CaptureTestStdout() { void CaptureTestStderr() { GOOGLE_CHECK_EQ(original_stderr_, -1) << "Already capturing."; - stderr_capture_filename_ = TestTempDir() + "/captured_stderr"; + stderr_capture_filename_ = absl::StrCat(TestTempDir(), "/captured_stderr"); int fd = open(stderr_capture_filename_.c_str(), O_WRONLY | O_CREAT | O_EXCL | O_BINARY, 0777); diff --git a/src/google/protobuf/util/field_mask_util.cc b/src/google/protobuf/util/field_mask_util.cc index 7ec6115a51..638a2790a4 100644 --- a/src/google/protobuf/util/field_mask_util.cc +++ b/src/google/protobuf/util/field_mask_util.cc @@ -41,6 +41,8 @@ #include "absl/memory/memory.h" #include "absl/strings/str_join.h" #include "absl/strings/str_split.h" +#include "absl/strings/string_view.h" +#include "absl/strings/strip.h" #include "google/protobuf/message.h" // Must be included last. @@ -58,8 +60,8 @@ std::string FieldMaskUtil::ToString(const FieldMask& mask) { void FieldMaskUtil::FromString(absl::string_view str, FieldMask* out) { out->Clear(); - std::vector paths = absl::StrSplit(str, ','); - for (const std::string& path : paths) { + std::vector paths = absl::StrSplit(str, ','); + for (absl::string_view path : paths) { if (path.empty()) continue; out->add_paths(path); } @@ -116,7 +118,7 @@ bool FieldMaskUtil::CamelCaseToSnakeCase(absl::string_view input, bool FieldMaskUtil::ToJsonString(const FieldMask& mask, std::string* out) { out->clear(); for (int i = 0; i < mask.paths_size(); ++i) { - const std::string& path = mask.paths(i); + absl::string_view path = mask.paths(i); std::string camelcase_path; if (!SnakeCaseToCamelCase(path, &camelcase_path)) { return false; @@ -131,8 +133,8 @@ bool FieldMaskUtil::ToJsonString(const FieldMask& mask, std::string* out) { bool FieldMaskUtil::FromJsonString(absl::string_view str, FieldMask* out) { out->Clear(); - std::vector paths = absl::StrSplit(str, ','); - for (const std::string& path : paths) { + std::vector paths = absl::StrSplit(str, ','); + for (absl::string_view path : paths) { if (path.empty()) continue; std::string snakecase_path; if (!CamelCaseToSnakeCase(path, &snakecase_path)) { @@ -149,8 +151,8 @@ bool FieldMaskUtil::GetFieldDescriptors( if (field_descriptors != nullptr) { field_descriptors->clear(); } - std::vector parts = absl::StrSplit(path, '.'); - for (const std::string& field_name : parts) { + std::vector parts = absl::StrSplit(path, '.'); + for (absl::string_view field_name : parts) { if (descriptor == nullptr) { return false; } @@ -206,18 +208,18 @@ class FieldMaskTree { // be added to the tree. If the path matches an existing non-leaf node in the // tree, that non-leaf node will be turned into a leaf node with all its // children removed because the path matches all the node's children. - void AddPath(const std::string& path); + void AddPath(absl::string_view path); // Remove a path from the tree. // If the path is a sub-path of an existing field path in the tree, it means // we need remove the existing field path and add all sub-paths except // specified path. If the path matches an existing node in the tree, this node // will be moved. - void RemovePath(const std::string& path, const Descriptor* descriptor); + void RemovePath(absl::string_view path, const Descriptor* descriptor); // Calculate the intersection part of a field path with this tree and add // the intersection field path into out. - void IntersectPath(const std::string& path, FieldMaskTree* out); + void IntersectPath(absl::string_view path, FieldMaskTree* out); // Merge all fields specified by this tree from one message to another. void MergeMessage(const Message& source, @@ -269,11 +271,11 @@ class FieldMaskTree { // Merge a sub-tree to mask. This method adds the field paths represented // by all leaf nodes descended from "node" to mask. - void MergeToFieldMask(const std::string& prefix, const Node* node, + void MergeToFieldMask(absl::string_view prefix, const Node* node, FieldMask* out); // Merge all leaf nodes of a sub-tree to another tree. - void MergeLeafNodesToTree(const std::string& prefix, const Node* node, + void MergeLeafNodesToTree(absl::string_view prefix, const Node* node, FieldMaskTree* out); // Merge all fields specified by a sub-tree from one message to another. @@ -308,8 +310,8 @@ void FieldMaskTree::MergeToFieldMask(FieldMask* mask) { MergeToFieldMask("", &root_, mask); } -void FieldMaskTree::MergeToFieldMask(const std::string& prefix, - const Node* node, FieldMask* out) { +void FieldMaskTree::MergeToFieldMask(absl::string_view prefix, const Node* node, + FieldMask* out) { if (node->children.empty()) { if (prefix.empty()) { // This is the root node. @@ -325,7 +327,7 @@ void FieldMaskTree::MergeToFieldMask(const std::string& prefix, } } -void FieldMaskTree::AddPath(const std::string& path) { +void FieldMaskTree::AddPath(absl::string_view path) { std::vector parts = absl::StrSplit(path, '.'); if (parts.empty()) { return; @@ -351,7 +353,7 @@ void FieldMaskTree::AddPath(const std::string& path) { } } -void FieldMaskTree::RemovePath(const std::string& path, +void FieldMaskTree::RemovePath(absl::string_view path, const Descriptor* descriptor) { if (root_.children.empty()) { // Nothing to be removed from an empty tree. We shortcut it here so an empty @@ -407,13 +409,13 @@ void FieldMaskTree::RemovePath(const std::string& path, } } -void FieldMaskTree::IntersectPath(const std::string& path, FieldMaskTree* out) { - std::vector parts = absl::StrSplit(path, '.'); +void FieldMaskTree::IntersectPath(absl::string_view path, FieldMaskTree* out) { + std::vector parts = absl::StrSplit(path, '.'); if (parts.empty()) { return; } const Node* node = &root_; - for (const std::string& node_name : parts) { + for (absl::string_view node_name : parts) { if (node->children.empty()) { if (node != &root_) { out->AddPath(path); @@ -432,7 +434,7 @@ void FieldMaskTree::IntersectPath(const std::string& path, FieldMaskTree* out) { MergeLeafNodesToTree(path, node, out); } -void FieldMaskTree::MergeLeafNodesToTree(const std::string& prefix, +void FieldMaskTree::MergeLeafNodesToTree(absl::string_view prefix, const Node* node, FieldMaskTree* out) { if (node->children.empty()) { out->AddPath(prefix); @@ -452,7 +454,7 @@ void FieldMaskTree::MergeMessage(const Node* node, const Message& source, const Reflection* destination_reflection = destination->GetReflection(); const Descriptor* descriptor = source.GetDescriptor(); for (const auto& kv : node->children) { - const std::string& field_name = kv.first; + absl::string_view field_name = kv.first; const Node* child = kv.second.get(); const FieldDescriptor* field = descriptor->FindFieldByName(field_name); if (field == nullptr) { @@ -552,7 +554,7 @@ void FieldMaskTree::AddRequiredFieldPath(Node* node, for (int index = 0; index < field_count; ++index) { const FieldDescriptor* field = descriptor->field(index); if (field->is_required()) { - const std::string& node_name = field->name(); + absl::string_view node_name = field->name(); std::unique_ptr& child = node->children[node_name]; if (child == nullptr) { // Add required field path to the tree @@ -662,15 +664,16 @@ void FieldMaskUtil::Subtract(const Descriptor* descriptor, bool FieldMaskUtil::IsPathInFieldMask(absl::string_view path, const FieldMask& mask) { for (int i = 0; i < mask.paths_size(); ++i) { - const std::string& mask_path = mask.paths(i); - if (path == mask_path) { + absl::string_view current = path; + absl::string_view mask_path = mask.paths(i); + if (current == mask_path) { return true; - } else if (mask_path.length() < path.length()) { + } // Also check whether mask.paths(i) is a prefix of path. - if (path.substr(0, mask_path.length() + 1).compare(mask_path + ".") == - 0) { - return true; - } + if (mask_path.length() < current.length() && + absl::ConsumePrefix(¤t, mask_path) && + absl::ConsumePrefix(¤t, ".")) { + return true; } } return false; diff --git a/src/google/protobuf/util/message_differencer_unittest.cc b/src/google/protobuf/util/message_differencer_unittest.cc index 6adcaad3fe..bab9fd6fdc 100644 --- a/src/google/protobuf/util/message_differencer_unittest.cc +++ b/src/google/protobuf/util/message_differencer_unittest.cc @@ -47,7 +47,9 @@ #include #include "absl/functional/bind_front.h" #include "google/protobuf/stubs/logging.h" +#include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" +#include "absl/strings/string_view.h" #include "google/protobuf/any_test.pb.h" #include "google/protobuf/map_test_util.h" #include "google/protobuf/map_unittest.pb.h" @@ -1856,7 +1858,7 @@ TEST(MessageDifferencerTest, PrintMapKeysTest) { diff_with_any); } -static const char* const kIgnoredFields[] = {"rm.b", "rm.m.b"}; +static constexpr absl::string_view kIgnoredFields[] = {"rm.b", "rm.m.b"}; class TestIgnorer : public util::MessageDifferencer::IgnoreCriteria { public: @@ -1865,12 +1867,12 @@ class TestIgnorer : public util::MessageDifferencer::IgnoreCriteria { const std::vector& parent_fields) override { std::string name = ""; - for (int i = 0; i < parent_fields.size(); ++i) { - name += parent_fields[i].field->name() + "."; + for (size_t i = 0; i < parent_fields.size(); ++i) { + absl::StrAppend(&name, parent_fields[i].field->name(), "."); } - name += field->name(); - for (int i = 0; i < ABSL_ARRAYSIZE(kIgnoredFields); ++i) { - if (name.compare(kIgnoredFields[i]) == 0) { + absl::StrAppend(&name, field->name()); + for (size_t i = 0; i < ABSL_ARRAYSIZE(kIgnoredFields); ++i) { + if (name == kIgnoredFields[i]) { return true; } } @@ -2440,8 +2442,9 @@ class ComparisonTest : public testing::Test { } if (!map_field_.empty() && !map_key_.empty()) { - d->TreatAsMap(GetFieldDescriptor(message, map_field_), - GetFieldDescriptor(message, map_field_ + "." + map_key_)); + d->TreatAsMap( + GetFieldDescriptor(message, map_field_), + GetFieldDescriptor(message, absl::StrCat(map_field_, ".", map_key_))); } } diff --git a/src/google/protobuf/util/time_util.cc b/src/google/protobuf/util/time_util.cc index 9644f24d42..9ca17d3140 100644 --- a/src/google/protobuf/util/time_util.cc +++ b/src/google/protobuf/util/time_util.cc @@ -39,6 +39,7 @@ #include "absl/numeric/int128.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" +#include "absl/strings/string_view.h" #include "absl/time/clock.h" #include "absl/time/time.h" @@ -137,7 +138,7 @@ std::string FormatNanos(int32_t nanos) { } std::string FormatTime(int64_t seconds, int32_t nanos) { - static const char kTimestampFormat[] = "%E4Y-%m-%dT%H:%M:%S"; + static constexpr absl::string_view kTimestampFormat = "%E4Y-%m-%dT%H:%M:%S"; timespec spec; spec.tv_sec = seconds; @@ -149,13 +150,13 @@ std::string FormatTime(int64_t seconds, int32_t nanos) { // We format the nanoseconds part separately to meet the precision // requirement. if (nanos != 0) { - result += "." + FormatNanos(nanos); + absl::StrAppend(&result, ".", FormatNanos(nanos)); } - result += "Z"; + absl::StrAppend(&result, "Z"); return result; } -bool ParseTime(const std::string& value, int64_t* seconds, int32_t* nanos) { +bool ParseTime(absl::string_view value, int64_t* seconds, int32_t* nanos) { absl::Time result; if (!absl::ParseTime(absl::RFC3339_full, value, &result, nullptr)) { return false; @@ -207,7 +208,7 @@ std::string TimeUtil::ToString(const Timestamp& timestamp) { return FormatTime(timestamp.seconds(), timestamp.nanos()); } -bool TimeUtil::FromString(const std::string& value, Timestamp* timestamp) { +bool TimeUtil::FromString(absl::string_view value, Timestamp* timestamp) { int64_t seconds; int32_t nanos; if (!ParseTime(value, &seconds, &nanos)) { @@ -231,15 +232,15 @@ std::string TimeUtil::ToString(const Duration& duration) { int64_t seconds = duration.seconds(); int32_t nanos = duration.nanos(); if (seconds < 0 || nanos < 0) { - result += "-"; + result = "-"; seconds = -seconds; nanos = -nanos; } - result += absl::StrCat(seconds); + absl::StrAppend(&result, seconds); if (nanos != 0) { - result += "." + FormatNanos(nanos); + absl::StrAppend(&result, ".", FormatNanos(nanos)); } - result += "s"; + absl::StrAppend(&result, "s"); return result; } @@ -251,7 +252,7 @@ static int64_t Pow(int64_t x, int y) { return result; } -bool TimeUtil::FromString(const std::string& value, Duration* duration) { +bool TimeUtil::FromString(absl::string_view value, Duration* duration) { if (value.length() <= 1 || value[value.length() - 1] != 's') { return false; } @@ -262,11 +263,12 @@ bool TimeUtil::FromString(const std::string& value, Duration* duration) { std::string seconds_part, nanos_part; size_t pos = value.find_last_of('.'); if (pos == std::string::npos) { - seconds_part = value.substr(sign_length, value.length() - 1 - sign_length); + seconds_part = std::string( + value.substr(sign_length, value.length() - 1 - sign_length)); nanos_part = "0"; } else { - seconds_part = value.substr(sign_length, pos - sign_length); - nanos_part = value.substr(pos + 1, value.length() - pos - 2); + seconds_part = std::string(value.substr(sign_length, pos - sign_length)); + nanos_part = std::string(value.substr(pos + 1, value.length() - pos - 2)); } char* end; static_assert(sizeof(int64_t) == sizeof(long long), diff --git a/src/google/protobuf/util/time_util.h b/src/google/protobuf/util/time_util.h index c272199918..7009d12c51 100644 --- a/src/google/protobuf/util/time_util.h +++ b/src/google/protobuf/util/time_util.h @@ -111,7 +111,7 @@ class PROTOBUF_EXPORT TimeUtil { // Example of accepted format: // "1972-01-01T10:00:20.021-05:00" static std::string ToString(const Timestamp& timestamp); - static bool FromString(const std::string& value, Timestamp* timestamp); + static bool FromString(absl::string_view value, Timestamp* timestamp); // Converts Duration to/from string format. The string format will contains // 3, 6, or 9 fractional digits depending on the precision required to @@ -120,7 +120,7 @@ class PROTOBUF_EXPORT TimeUtil { // The range that can be represented by Duration is from -315,576,000,000 // to +315,576,000,000 inclusive (in seconds). static std::string ToString(const Duration& duration); - static bool FromString(const std::string& value, Duration* timestamp); + static bool FromString(absl::string_view value, Duration* duration); // Gets the current UTC time. static Timestamp GetCurrentTime(); diff --git a/src/google/protobuf/util/type_resolver_util.cc b/src/google/protobuf/util/type_resolver_util.cc index a279fa3e2f..6dc0173c13 100644 --- a/src/google/protobuf/util/type_resolver_util.cc +++ b/src/google/protobuf/util/type_resolver_util.cc @@ -38,6 +38,8 @@ #include "absl/status/status.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "absl/strings/strip.h" #include "google/protobuf/io/strtod.h" #include "google/protobuf/util/type_resolver.h" @@ -67,7 +69,7 @@ using google::protobuf::UInt64Value; class DescriptorPoolTypeResolver : public TypeResolver { public: - DescriptorPoolTypeResolver(const std::string& url_prefix, + DescriptorPoolTypeResolver(absl::string_view url_prefix, const DescriptorPool* pool) : url_prefix_(url_prefix), pool_(pool) {} @@ -81,8 +83,8 @@ class DescriptorPoolTypeResolver : public TypeResolver { const Descriptor* descriptor = pool_->FindMessageTypeByName(type_name); if (descriptor == NULL) { - return absl::NotFoundError("Invalid type URL, unknown type: " + - type_name); + return absl::NotFoundError( + absl::StrCat("Invalid type URL, unknown type: ", type_name)); } ConvertDescriptor(descriptor, type); return absl::Status(); @@ -98,8 +100,8 @@ class DescriptorPoolTypeResolver : public TypeResolver { const EnumDescriptor* descriptor = pool_->FindEnumTypeByName(type_name); if (descriptor == NULL) { - return absl::InvalidArgumentError("Invalid type URL, unknown type: " + - type_name); + return absl::InvalidArgumentError( + absl::StrCat("Invalid type URL, unknown type: ", type_name)); } ConvertEnumDescriptor(descriptor, enum_type); return absl::Status(); @@ -297,21 +299,23 @@ class DescriptorPoolTypeResolver : public TypeResolver { } std::string GetTypeUrl(const Descriptor* descriptor) { - return url_prefix_ + "/" + descriptor->full_name(); + return absl::StrCat(url_prefix_, "/", descriptor->full_name()); } std::string GetTypeUrl(const EnumDescriptor* descriptor) { - return url_prefix_ + "/" + descriptor->full_name(); + return absl::StrCat(url_prefix_, "/", descriptor->full_name()); } - absl::Status ParseTypeUrl(const std::string& type_url, + absl::Status ParseTypeUrl(absl::string_view type_url, std::string* type_name) { - if (type_url.substr(0, url_prefix_.size() + 1) != url_prefix_ + "/") { + absl::string_view stripped = type_url; + if (!absl::ConsumePrefix(&stripped, url_prefix_) || + !absl::ConsumePrefix(&stripped, "/")) { return absl::InvalidArgumentError( absl::StrCat("Invalid type URL, type URLs must be of the form '", url_prefix_, "/', got: ", type_url)); } - *type_name = type_url.substr(url_prefix_.size() + 1); + *type_name = std::string(stripped); return absl::Status(); } @@ -361,7 +365,7 @@ class DescriptorPoolTypeResolver : public TypeResolver { } // namespace -TypeResolver* NewTypeResolverForDescriptorPool(const std::string& url_prefix, +TypeResolver* NewTypeResolverForDescriptorPool(absl::string_view url_prefix, const DescriptorPool* pool) { return new DescriptorPoolTypeResolver(url_prefix, pool); } diff --git a/src/google/protobuf/util/type_resolver_util.h b/src/google/protobuf/util/type_resolver_util.h index 0327e61d5d..3670fcb785 100644 --- a/src/google/protobuf/util/type_resolver_util.h +++ b/src/google/protobuf/util/type_resolver_util.h @@ -33,7 +33,7 @@ #ifndef GOOGLE_PROTOBUF_UTIL_TYPE_RESOLVER_UTIL_H__ #define GOOGLE_PROTOBUF_UTIL_TYPE_RESOLVER_UTIL_H__ -#include +#include "absl/strings/string_view.h" // Must be included last. #include "google/protobuf/port_def.inc" @@ -47,7 +47,7 @@ class TypeResolver; // Creates a TypeResolver that serves type information in the given descriptor // pool. Caller takes ownership of the returned TypeResolver. PROTOBUF_EXPORT TypeResolver* NewTypeResolverForDescriptorPool( - const std::string& url_prefix, const DescriptorPool* pool); + absl::string_view url_prefix, const DescriptorPool* pool); } // namespace util } // namespace protobuf