diff --git a/conformance/binary_json_conformance_suite.cc b/conformance/binary_json_conformance_suite.cc index 36306eb865..1d2c298006 100644 --- a/conformance/binary_json_conformance_suite.cc +++ b/conformance/binary_json_conformance_suite.cc @@ -124,7 +124,7 @@ std::string fixed64(void* data) { return std::string(reinterpret_cast(&data_le), 8); } -std::string delim(absl::string_view buf) { +std::string delim(const std::string& buf) { return absl::StrCat(varint(buf.size()), buf); } std::string u32(uint32_t u32) { return fixed32(&u32); } @@ -239,7 +239,7 @@ std::string UpperCase(std::string str) { } bool IsProto3Default(FieldDescriptor::Type type, - absl::string_view binary_data) { + const std::string& binary_data) { switch (type) { case FieldDescriptor::TYPE_DOUBLE: return binary_data == dbl(0); @@ -299,7 +299,7 @@ bool BinaryAndJsonConformanceSuite::ParseResponse( const ConformanceRequestSetting& setting, Message* test_message) { const ConformanceRequest& request = setting.GetRequest(); WireFormat requested_output = request.requested_output_format(); - const std::string test_name = setting.GetTestName(); + const std::string& test_name = setting.GetTestName(); ConformanceLevel level = setting.GetLevel(); switch (response.result_case()) { @@ -421,8 +421,8 @@ void BinaryAndJsonConformanceSuite::RunDelimitedFieldTests() { template void BinaryAndJsonConformanceSuiteImpl:: - ExpectParseFailureForProtoWithProtoVersion(absl::string_view proto, - absl::string_view test_name, + ExpectParseFailureForProtoWithProtoVersion(const std::string& proto, + const std::string& test_name, ConformanceLevel level) { MessageType prototype; // We don't expect output, but if the program erroneously accepts the protobuf @@ -451,7 +451,7 @@ void BinaryAndJsonConformanceSuiteImpl:: // Expect that this precise protobuf will cause a parse error. template void BinaryAndJsonConformanceSuiteImpl::ExpectParseFailureForProto( - absl::string_view proto, absl::string_view test_name, + const std::string& proto, const std::string& test_name, ConformanceLevel level) { ExpectParseFailureForProtoWithProtoVersion(proto, test_name, level); } @@ -463,16 +463,16 @@ void BinaryAndJsonConformanceSuiteImpl::ExpectParseFailureForProto( // TODO: implement the second of these. template void BinaryAndJsonConformanceSuiteImpl< - MessageType>::ExpectHardParseFailureForProto(absl::string_view proto, - absl::string_view test_name, + MessageType>::ExpectHardParseFailureForProto(const std::string& proto, + const std::string& test_name, ConformanceLevel level) { return ExpectParseFailureForProto(proto, test_name, level); } template void BinaryAndJsonConformanceSuiteImpl::RunValidJsonTest( - absl::string_view test_name, ConformanceLevel level, - absl::string_view input_json, absl::string_view equivalent_text_format) { + const std::string& test_name, ConformanceLevel level, + const std::string& input_json, const std::string& equivalent_text_format) { MessageType prototype; RunValidJsonTestWithMessage(test_name, level, input_json, equivalent_text_format, prototype); @@ -480,10 +480,10 @@ void BinaryAndJsonConformanceSuiteImpl::RunValidJsonTest( template void BinaryAndJsonConformanceSuiteImpl:: - RunValidJsonTestWithMessage(absl::string_view test_name, + RunValidJsonTestWithMessage(const std::string& test_name, ConformanceLevel level, - absl::string_view input_json, - absl::string_view equivalent_text_format, + const std::string& input_json, + const std::string& equivalent_text_format, const Message& prototype) { ConformanceRequestSetting setting1( level, conformance::JSON, conformance::PROTOBUF, conformance::JSON_TEST, @@ -498,8 +498,8 @@ void BinaryAndJsonConformanceSuiteImpl:: template void BinaryAndJsonConformanceSuiteImpl:: RunValidJsonTestWithProtobufInput( - absl::string_view test_name, ConformanceLevel level, - const MessageType& input, absl::string_view equivalent_text_format) { + const std::string& test_name, ConformanceLevel level, + const MessageType& input, const std::string& equivalent_text_format) { ConformanceRequestSetting setting( level, conformance::PROTOBUF, conformance::JSON, conformance::JSON_TEST, input, test_name, input.SerializeAsString()); @@ -508,10 +508,10 @@ void BinaryAndJsonConformanceSuiteImpl:: template void BinaryAndJsonConformanceSuiteImpl:: - RunValidJsonIgnoreUnknownTest(absl::string_view test_name, + RunValidJsonIgnoreUnknownTest(const std::string& test_name, ConformanceLevel level, - absl::string_view input_json, - absl::string_view equivalent_text_format) { + const std::string& input_json, + const std::string& equivalent_text_format) { MessageType prototype; ConformanceRequestSetting setting( level, conformance::JSON, conformance::PROTOBUF, @@ -522,9 +522,9 @@ void BinaryAndJsonConformanceSuiteImpl:: template void BinaryAndJsonConformanceSuite::RunValidBinaryProtobufTest( - absl::string_view test_name, ConformanceLevel level, - absl::string_view input_protobuf, - absl::string_view equivalent_text_format) { + const std::string& test_name, ConformanceLevel level, + const std::string& input_protobuf, + const std::string& equivalent_text_format) { MessageType prototype; ConformanceRequestSetting binary_to_binary( @@ -535,9 +535,9 @@ void BinaryAndJsonConformanceSuite::RunValidBinaryProtobufTest( template void BinaryAndJsonConformanceSuite::RunValidProtobufTest( - absl::string_view test_name, ConformanceLevel level, - absl::string_view input_protobuf, - absl::string_view equivalent_text_format) { + const std::string& test_name, ConformanceLevel level, + const std::string& input_protobuf, + const std::string& equivalent_text_format) { MessageType prototype; ConformanceRequestSetting binary_to_binary( @@ -553,24 +553,24 @@ void BinaryAndJsonConformanceSuite::RunValidProtobufTest( template void BinaryAndJsonConformanceSuiteImpl::RunValidProtobufTest( - absl::string_view test_name, ConformanceLevel level, - absl::string_view input_protobuf, - absl::string_view equivalent_text_format) { + const std::string& test_name, ConformanceLevel level, + const std::string& input_protobuf, + const std::string& equivalent_text_format) { suite_.RunValidProtobufTest(test_name, level, input_protobuf, equivalent_text_format); } template void BinaryAndJsonConformanceSuiteImpl::RunValidBinaryProtobufTest( - absl::string_view test_name, ConformanceLevel level, - absl::string_view input_protobuf) { + const std::string& test_name, ConformanceLevel level, + const std::string& input_protobuf) { RunValidBinaryProtobufTest(test_name, level, input_protobuf, input_protobuf); } template void BinaryAndJsonConformanceSuiteImpl::RunValidBinaryProtobufTest( - absl::string_view test_name, ConformanceLevel level, - absl::string_view input_protobuf, absl::string_view expected_protobuf) { + const std::string& test_name, ConformanceLevel level, + const std::string& input_protobuf, const std::string& expected_protobuf) { MessageType prototype; ConformanceRequestSetting setting( level, conformance::PROTOBUF, conformance::PROTOBUF, @@ -580,8 +580,8 @@ void BinaryAndJsonConformanceSuiteImpl::RunValidBinaryProtobufTest( template void BinaryAndJsonConformanceSuiteImpl:: - RunBinaryPerformanceMergeMessageWithField(absl::string_view test_name, - absl::string_view field_proto) { + RunBinaryPerformanceMergeMessageWithField(const std::string& test_name, + const std::string& field_proto) { std::string message_tag = tag(27, WireFormatLite::WIRETYPE_LENGTH_DELIMITED); std::string message_proto = absl::StrCat(message_tag, delim(field_proto)); @@ -592,7 +592,7 @@ void BinaryAndJsonConformanceSuiteImpl:: std::string multiple_repeated_field_proto; for (size_t i = 0; i < kPerformanceRepeatCount; i++) { - multiple_repeated_field_proto.append(std::string(field_proto)); + multiple_repeated_field_proto.append(field_proto); } std::string expected_proto = absl::StrCat(message_tag, delim(multiple_repeated_field_proto)); @@ -602,10 +602,10 @@ void BinaryAndJsonConformanceSuiteImpl:: template void BinaryAndJsonConformanceSuiteImpl:: - RunValidProtobufTestWithMessage(absl::string_view test_name, + RunValidProtobufTestWithMessage(const std::string& test_name, ConformanceLevel level, const Message* input, - absl::string_view equivalent_text_format) { + const std::string& equivalent_text_format) { RunValidProtobufTest(test_name, level, input->SerializeAsString(), equivalent_text_format); } @@ -617,9 +617,9 @@ void BinaryAndJsonConformanceSuiteImpl:: template // the JSON output directly. void BinaryAndJsonConformanceSuiteImpl< - MessageType>::RunValidJsonTestWithValidator(absl::string_view test_name, + MessageType>::RunValidJsonTestWithValidator(const std::string& test_name, ConformanceLevel level, - absl::string_view input_json, + const std::string& input_json, const Validator& validator) { MessageType prototype; ConformanceRequestSetting setting(level, conformance::JSON, conformance::JSON, @@ -663,8 +663,8 @@ void BinaryAndJsonConformanceSuiteImpl< template void BinaryAndJsonConformanceSuiteImpl::ExpectParseFailureForJson( - absl::string_view test_name, ConformanceLevel level, - absl::string_view input_json) { + const std::string& test_name, ConformanceLevel level, + const std::string& input_json) { MessageType 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. @@ -689,10 +689,10 @@ void BinaryAndJsonConformanceSuiteImpl::ExpectParseFailureForJson( } template -void BinaryAndJsonConformanceSuiteImpl< - MessageType>::ExpectSerializeFailureForJson(absl::string_view test_name, - ConformanceLevel level, - absl::string_view text_format) { +void BinaryAndJsonConformanceSuiteImpl:: + ExpectSerializeFailureForJson(const std::string& test_name, + ConformanceLevel level, + const std::string& text_format) { MessageType payload_message; ABSL_CHECK(TextFormat::ParseFromString(text_format, &payload_message)) << "Failed to parse: " << text_format; diff --git a/conformance/binary_json_conformance_suite.h b/conformance/binary_json_conformance_suite.h index 3a8a8a04bb..325a76e3ba 100644 --- a/conformance/binary_json_conformance_suite.h +++ b/conformance/binary_json_conformance_suite.h @@ -39,15 +39,16 @@ class BinaryAndJsonConformanceSuite : public ConformanceTestSuite { } template - void RunValidBinaryProtobufTest(absl::string_view test_name, + void RunValidBinaryProtobufTest(const std::string& test_name, ConformanceLevel level, - absl::string_view input_protobuf, - absl::string_view equivalent_text_format); + const std::string& input_protobuf, + const std::string& equivalent_text_format); template - void RunValidProtobufTest(absl::string_view test_name, ConformanceLevel level, - absl::string_view input_protobuf, - absl::string_view equivalent_text_format); + void RunValidProtobufTest(const std::string& test_name, + ConformanceLevel level, + const std::string& input_protobuf, + const std::string& equivalent_text_format); void RunDelimitedFieldTests(); @@ -87,57 +88,58 @@ class BinaryAndJsonConformanceSuiteImpl { void RunJsonTestsForValue(); void RunJsonTestsForAny(); void RunJsonTestsForUnknownEnumStringValues(); - void RunValidJsonTest(absl::string_view test_name, ConformanceLevel level, - absl::string_view input_json, - absl::string_view equivalent_text_format); - void RunValidJsonTestWithMessage(absl::string_view test_name, + void RunValidJsonTest(const std::string& test_name, ConformanceLevel level, + const std::string& input_json, + const std::string& equivalent_text_format); + void RunValidJsonTestWithMessage(const std::string& test_name, ConformanceLevel level, - absl::string_view input_json, - absl::string_view equivalent_text_forma, + const std::string& input_json, + const std::string& equivalent_text_forma, const Message& prototype); void RunValidJsonTestWithProtobufInput( - absl::string_view test_name, ConformanceLevel level, - const MessageType& input, absl::string_view equivalent_text_format); - void RunValidJsonIgnoreUnknownTest(absl::string_view test_name, + const std::string& test_name, ConformanceLevel level, + const MessageType& input, const std::string& equivalent_text_format); + void RunValidJsonIgnoreUnknownTest(const std::string& test_name, ConformanceLevel level, - absl::string_view input_json, - absl::string_view equivalent_text_format); - void RunValidProtobufTest(absl::string_view test_name, ConformanceLevel level, - absl::string_view input_protobuf, - absl::string_view equivalent_text_format); - void RunValidBinaryProtobufTest(absl::string_view test_name, + const std::string& input_json, + const std::string& equivalent_text_format); + void RunValidProtobufTest(const std::string& test_name, + ConformanceLevel level, + const std::string& input_protobuf, + const std::string& equivalent_text_format); + void RunValidBinaryProtobufTest(const std::string& test_name, ConformanceLevel level, - absl::string_view input_protobuf); - void RunValidBinaryProtobufTest(absl::string_view test_name, + const std::string& input_protobuf); + void RunValidBinaryProtobufTest(const std::string& test_name, ConformanceLevel level, - absl::string_view input_protobuf, - absl::string_view expected_protobuf); - void RunBinaryPerformanceMergeMessageWithField(absl::string_view test_name, - absl::string_view field_proto); + const std::string& input_protobuf, + const std::string& expected_protobuf); + void RunBinaryPerformanceMergeMessageWithField( + const std::string& test_name, const std::string& field_proto); void RunValidProtobufTestWithMessage( - absl::string_view test_name, ConformanceLevel level, const Message* input, - absl::string_view equivalent_text_format); + const std::string& test_name, ConformanceLevel level, + const Message* input, const std::string& equivalent_text_format); typedef std::function Validator; - void RunValidJsonTestWithValidator(absl::string_view test_name, + void RunValidJsonTestWithValidator(const std::string& test_name, ConformanceLevel level, - absl::string_view input_json, + const std::string& input_json, const Validator& validator); - void ExpectParseFailureForJson(absl::string_view test_name, + void ExpectParseFailureForJson(const std::string& test_name, ConformanceLevel level, - absl::string_view input_json); - void ExpectSerializeFailureForJson(absl::string_view test_name, + const std::string& input_json); + void ExpectSerializeFailureForJson(const std::string& test_name, ConformanceLevel level, - absl::string_view text_format); - void ExpectParseFailureForProtoWithProtoVersion(absl::string_view proto, - absl::string_view test_name, + const std::string& text_format); + void ExpectParseFailureForProtoWithProtoVersion(const std::string& proto, + const std::string& test_name, ConformanceLevel level); - void ExpectParseFailureForProto(absl::string_view proto, - absl::string_view test_name, + void ExpectParseFailureForProto(const std::string& proto, + const std::string& test_name, ConformanceLevel level); - void ExpectHardParseFailureForProto(absl::string_view proto, - absl::string_view test_name, + void ExpectHardParseFailureForProto(const std::string& proto, + const std::string& test_name, ConformanceLevel level); void TestPrematureEOFForType(google::protobuf::FieldDescriptor::Type type); void TestIllegalTags(); diff --git a/conformance/conformance_test.cc b/conformance/conformance_test.cc index f91fd0130f..2d7dfcd344 100644 --- a/conformance/conformance_test.cc +++ b/conformance/conformance_test.cc @@ -37,7 +37,7 @@ using std::string; namespace { -static std::string ToOctString(absl::string_view binary_string) { +static std::string ToOctString(const std::string& binary_string) { std::string oct_string; for (size_t i = 0; i < binary_string.size(); i++) { uint8_t c = binary_string.at(i); @@ -98,7 +98,7 @@ ConformanceTestSuite::ConformanceRequestSetting::ConformanceRequestSetting( ConformanceLevel level, conformance::WireFormat input_format, conformance::WireFormat output_format, conformance::TestCategory test_category, const Message& prototype_message, - absl::string_view test_name, absl::string_view input) + const std::string& test_name, const std::string& input) : level_(level), input_format_(input_format), output_format_(output_format), @@ -265,19 +265,19 @@ ConformanceResponse ConformanceTestSuite::TruncateResponse( return debug_response; } -void ConformanceTestSuite::ReportSuccess(absl::string_view test_name) { +void ConformanceTestSuite::ReportSuccess(const std::string& test_name) { if (expected_to_fail_.erase(test_name) != 0) { absl::StrAppendFormat( &output_, "ERROR: test %s is in the failure list, but test succeeded. " "Remove it from the failure list.\n", test_name); - unexpected_succeeding_tests_.insert(std::string(test_name)); + unexpected_succeeding_tests_.insert(test_name); } successes_++; } -void ConformanceTestSuite::ReportFailure(absl::string_view test_name, +void ConformanceTestSuite::ReportFailure(const std::string& test_name, ConformanceLevel level, const ConformanceRequest& request, const ConformanceResponse& response, @@ -289,7 +289,7 @@ void ConformanceTestSuite::ReportFailure(absl::string_view test_name, absl::StrAppendFormat(&output_, "WARNING, test=%s: ", test_name); } else { absl::StrAppendFormat(&output_, "ERROR, test=%s: ", test_name); - unexpected_failing_tests_.insert(std::string(test_name)); + unexpected_failing_tests_.insert(test_name); } absl::StrAppendFormat(&output_, "%s, request=%s, response=%s\n", message, @@ -297,7 +297,7 @@ void ConformanceTestSuite::ReportFailure(absl::string_view test_name, TruncateResponse(response).ShortDebugString()); } -void ConformanceTestSuite::ReportSkip(absl::string_view test_name, +void ConformanceTestSuite::ReportSkip(const std::string& test_name, const ConformanceRequest& request, const ConformanceResponse& response) { if (verbose_) { @@ -305,12 +305,12 @@ void ConformanceTestSuite::ReportSkip(absl::string_view test_name, &output_, "SKIPPED, test=%s request=%s, response=%s\n", test_name, request.ShortDebugString(), response.ShortDebugString()); } - skipped_.insert(std::string(test_name)); + skipped_.insert(test_name); } void ConformanceTestSuite::RunValidInputTest( const ConformanceRequestSetting& setting, - absl::string_view equivalent_text_format) { + const std::string& equivalent_text_format) { std::unique_ptr reference_message(setting.NewTestMessage()); ABSL_CHECK(TextFormat::ParseFromString(equivalent_text_format, reference_message.get())) @@ -323,7 +323,7 @@ void ConformanceTestSuite::RunValidInputTest( void ConformanceTestSuite::RunValidBinaryInputTest( const ConformanceRequestSetting& setting, - absl::string_view equivalent_wire_format, bool require_same_wire_format) { + const std::string& equivalent_wire_format, bool require_same_wire_format) { const ConformanceRequest& request = setting.GetRequest(); ConformanceResponse response; RunTest(setting.GetTestName(), request, &response); @@ -333,12 +333,12 @@ void ConformanceTestSuite::RunValidBinaryInputTest( void ConformanceTestSuite::VerifyResponse( const ConformanceRequestSetting& setting, - absl::string_view equivalent_wire_format, + const std::string& equivalent_wire_format, const ConformanceResponse& response, bool need_report_success, bool require_same_wire_format) { std::unique_ptr test_message(setting.NewTestMessage()); const ConformanceRequest& request = setting.GetRequest(); - const std::string test_name = setting.GetTestName(); + const std::string& test_name = setting.GetTestName(); ConformanceLevel level = setting.GetLevel(); std::unique_ptr reference_message = setting.NewTestMessage(); @@ -379,7 +379,7 @@ void ConformanceTestSuite::VerifyResponse( if (require_same_wire_format) { ABSL_DCHECK_EQ(response.result_case(), ConformanceResponse::kProtobufPayload); - absl::string_view protobuf_payload = response.protobuf_payload(); + const std::string& protobuf_payload = response.protobuf_payload(); check = equivalent_wire_format == protobuf_payload; differences = absl::StrCat("Expect: ", ToOctString(equivalent_wire_format), ", but got: ", ToOctString(protobuf_payload)); @@ -399,10 +399,10 @@ void ConformanceTestSuite::VerifyResponse( } } -void ConformanceTestSuite::RunTest(absl::string_view test_name, +void ConformanceTestSuite::RunTest(const std::string& test_name, const ConformanceRequest& request, ConformanceResponse* response) { - if (test_names_.insert(std::string(test_name)).second == false) { + if (test_names_.insert(test_name).second == false) { ABSL_LOG(FATAL) << "Duplicated test name: " << test_name; } @@ -410,8 +410,7 @@ void ConformanceTestSuite::RunTest(absl::string_view test_name, std::string serialized_response; request.SerializeToString(&serialized_request); - runner_->RunTest(std::string(test_name), serialized_request, - &serialized_response); + runner_->RunTest(test_name, serialized_request, &serialized_response); if (!response->ParseFromString(serialized_response)) { response->Clear(); @@ -444,13 +443,13 @@ std::string ConformanceTestSuite::WireFormatToString(WireFormat wire_format) { return ""; } -void ConformanceTestSuite::AddExpectedFailedTest(absl::string_view test_name) { - expected_to_fail_.insert(std::string(test_name)); +void ConformanceTestSuite::AddExpectedFailedTest(const std::string& test_name) { + expected_to_fail_.insert(test_name); } bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner, std::string* output, - absl::string_view filename, + const std::string& filename, conformance::FailureSet* failure_list) { runner_ = runner; successes_ = 0; @@ -462,9 +461,9 @@ bool ConformanceTestSuite::RunSuite(ConformanceTestRunner* runner, output_ = "\nCONFORMANCE TEST BEGIN ====================================\n\n"; - failure_list_filename_ = std::string(filename); + failure_list_filename_ = filename; expected_to_fail_.clear(); - for (absl::string_view failure : failure_list->failure()) { + for (const std::string& failure : failure_list->failure()) { AddExpectedFailedTest(failure); } RunSuiteImpl(); diff --git a/conformance/conformance_test.h b/conformance/conformance_test.h index ca4d475266..c78f9ea8ab 100644 --- a/conformance/conformance_test.h +++ b/conformance/conformance_test.h @@ -67,7 +67,7 @@ class ForkPipeRunner : public ConformanceTestRunner { static int Run(int argc, char* argv[], const std::vector& suites); - ForkPipeRunner(absl::string_view executable, + ForkPipeRunner(const std::string& executable, const std::vector& executable_args, bool performance) : child_pid_(-1), @@ -75,7 +75,7 @@ class ForkPipeRunner : public ConformanceTestRunner { executable_args_(executable_args), performance_(performance) {} - explicit ForkPipeRunner(absl::string_view executable) + explicit ForkPipeRunner(const std::string& executable) : child_pid_(-1), executable_(executable) {} virtual ~ForkPipeRunner() {} @@ -156,8 +156,8 @@ class ConformanceTestSuite { // By default, this would return --failure_list std::string GetFailureListFlagName() { return failure_list_flag_name_; } - void SetFailureListFlagName(absl::string_view failure_list_flag_name) { - failure_list_flag_name_ = std::string(failure_list_flag_name); + void SetFailureListFlagName(const std::string& failure_list_flag_name) { + failure_list_flag_name_ = failure_list_flag_name; } // Sets the path of the output directory. @@ -171,7 +171,7 @@ class ConformanceTestSuite { // The filename here is *only* used to create/format useful error messages for // how to update the failure list. We do NOT read this file at all. bool RunSuite(ConformanceTestRunner* runner, std::string* output, - absl::string_view filename, + const std::string& filename, conformance::FailureSet* failure_list); protected: @@ -199,8 +199,8 @@ class ConformanceTestSuite { conformance::WireFormat output_format, conformance::TestCategory test_category, const Message& prototype_message, - absl::string_view test_name, - absl::string_view input); + const std::string& test_name, + const std::string& input); virtual ~ConformanceRequestSetting() {} std::unique_ptr NewTestMessage() const; @@ -249,7 +249,7 @@ class ConformanceTestSuite { Message* test_message) = 0; void VerifyResponse(const ConformanceRequestSetting& setting, - absl::string_view equivalent_wire_format, + const std::string& equivalent_wire_format, const conformance::ConformanceResponse& response, bool need_report_success, bool require_same_wire_format); @@ -259,26 +259,26 @@ class ConformanceTestSuite { conformance::ConformanceResponse TruncateResponse( const conformance::ConformanceResponse& response); - void ReportSuccess(absl::string_view test_name); - void ReportFailure(absl::string_view test_name, ConformanceLevel level, + void ReportSuccess(const std::string& test_name); + void ReportFailure(const std::string& test_name, ConformanceLevel level, const conformance::ConformanceRequest& request, const conformance::ConformanceResponse& response, absl::string_view message); - void ReportSkip(absl::string_view test_name, + void ReportSkip(const std::string& test_name, const conformance::ConformanceRequest& request, const conformance::ConformanceResponse& response); void RunValidInputTest(const ConformanceRequestSetting& setting, - absl::string_view equivalent_text_format); + const std::string& equivalent_text_format); void RunValidBinaryInputTest(const ConformanceRequestSetting& setting, - absl::string_view equivalent_wire_format, + const std::string& equivalent_wire_format, bool require_same_wire_format = false); - void RunTest(absl::string_view test_name, + void RunTest(const std::string& test_name, const conformance::ConformanceRequest& request, conformance::ConformanceResponse* response); - void AddExpectedFailedTest(absl::string_view test_name); + void AddExpectedFailedTest(const std::string& test_name); virtual void RunSuiteImpl() = 0; diff --git a/conformance/text_format_conformance_suite.cc b/conformance/text_format_conformance_suite.cc index e5e4e37956..a230fa3d08 100644 --- a/conformance/text_format_conformance_suite.cc +++ b/conformance/text_format_conformance_suite.cc @@ -158,8 +158,8 @@ TextFormatConformanceTestSuiteImpl:: template void TextFormatConformanceTestSuiteImpl::ExpectParseFailure( - absl::string_view test_name, ConformanceLevel level, - absl::string_view input) { + const std::string& test_name, ConformanceLevel level, + const std::string& input) { MessageType 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. @@ -185,17 +185,17 @@ void TextFormatConformanceTestSuiteImpl::ExpectParseFailure( template void TextFormatConformanceTestSuiteImpl::RunValidTextFormatTest( - absl::string_view test_name, ConformanceLevel level, - absl::string_view input_text) { + const std::string& test_name, ConformanceLevel level, + const std::string& input_text) { MessageType prototype; RunValidTextFormatTestWithMessage(test_name, level, input_text, prototype); } template void TextFormatConformanceTestSuiteImpl:: - RunValidTextFormatTestWithMessage(absl::string_view test_name, + RunValidTextFormatTestWithMessage(const std::string& test_name, ConformanceLevel level, - absl::string_view input_text, + const std::string& input_text, const Message& message) { ConformanceRequestSetting setting1( level, conformance::TEXT_FORMAT, conformance::PROTOBUF, @@ -209,10 +209,10 @@ void TextFormatConformanceTestSuiteImpl:: template void TextFormatConformanceTestSuiteImpl:: - RunValidTextFormatTestWithExpected(absl::string_view test_name, + RunValidTextFormatTestWithExpected(const std::string& test_name, ConformanceLevel level, - absl::string_view input_text, - absl::string_view expected_text) { + const std::string& input_text, + const std::string& expected_text) { MessageType prototype; ConformanceRequestSetting setting1( level, conformance::TEXT_FORMAT, conformance::PROTOBUF, @@ -226,7 +226,7 @@ void TextFormatConformanceTestSuiteImpl:: template void TextFormatConformanceTestSuiteImpl< - MessageType>::RunValidUnknownTextFormatTest(absl::string_view test_name, + MessageType>::RunValidUnknownTextFormatTest(const std::string& test_name, const Message& message) { std::string serialized_input; message.SerializeToString(&serialized_input); @@ -836,7 +836,7 @@ void TextFormatConformanceTestSuiteImpl< template void TextFormatConformanceTestSuiteImpl:: TestTextFormatPerformanceMergeMessageWithRepeatedField( - absl::string_view test_type_name, absl::string_view message_field) { + const std::string& test_type_name, const std::string& message_field) { std::string recursive_message = absl::StrCat("recursive_message { ", message_field, " }"); diff --git a/conformance/text_format_conformance_suite.h b/conformance/text_format_conformance_suite.h index bb925b15cb..c64a333b2b 100644 --- a/conformance/text_format_conformance_suite.h +++ b/conformance/text_format_conformance_suite.h @@ -10,7 +10,6 @@ #include -#include "absl/strings/string_view.h" #include "conformance_test.h" #include "google/protobuf/message.h" @@ -55,22 +54,22 @@ class TextFormatConformanceTestSuiteImpl { void RunAnyTests(); void RunTextFormatPerformanceTests(); - void RunValidTextFormatTest(absl::string_view test_name, - ConformanceLevel level, absl::string_view input); - void RunValidTextFormatTestWithExpected(absl::string_view test_name, + void RunValidTextFormatTest(const std::string& test_name, + ConformanceLevel level, const std::string& input); + void RunValidTextFormatTestWithExpected(const std::string& test_name, ConformanceLevel level, - absl::string_view input_text, - absl::string_view expected_text); - void RunValidUnknownTextFormatTest(absl::string_view test_name, + const std::string& input_text, + const std::string& expected_text); + void RunValidUnknownTextFormatTest(const std::string& test_name, const Message& message); - void RunValidTextFormatTestWithMessage(absl::string_view test_name, + void RunValidTextFormatTestWithMessage(const std::string& test_name, ConformanceLevel level, - absl::string_view input_text, + const std::string& input_text, const Message& message); - void ExpectParseFailure(absl::string_view test_name, ConformanceLevel level, - absl::string_view input); + void ExpectParseFailure(const std::string& test_name, ConformanceLevel level, + const std::string& input); void TestTextFormatPerformanceMergeMessageWithRepeatedField( - absl::string_view test_type_name, absl::string_view message_field); + const std::string& test_type_name, const std::string& message_field); TextFormatConformanceTestSuite& suite_; }; diff --git a/src/google/protobuf/compiler/annotation_test_util.cc b/src/google/protobuf/compiler/annotation_test_util.cc index 092bb6f445..5c9136a9e1 100644 --- a/src/google/protobuf/compiler/annotation_test_util.cc +++ b/src/google/protobuf/compiler/annotation_test_util.cc @@ -71,7 +71,7 @@ bool RunProtoCompiler(const std::string& filename, return cli->Run(5, argv) == 0; } -bool DecodeMetadata(absl::string_view path, GeneratedCodeInfo* info) { +bool DecodeMetadata(const std::string& path, GeneratedCodeInfo* info) { std::string data; ABSL_CHECK_OK(File::GetContents(path, &data, true)); io::ArrayInputStream input(data.data(), data.size()); @@ -79,7 +79,7 @@ bool DecodeMetadata(absl::string_view path, GeneratedCodeInfo* info) { } void FindAnnotationsOnPath( - const GeneratedCodeInfo& info, absl::string_view source_file, + const GeneratedCodeInfo& info, const std::string& source_file, const std::vector& path, std::vector* annotations) { for (int i = 0; i < info.annotation_size(); ++i) { @@ -101,7 +101,7 @@ void FindAnnotationsOnPath( } const GeneratedCodeInfo::Annotation* FindAnnotationOnPath( - const GeneratedCodeInfo& info, absl::string_view source_file, + const GeneratedCodeInfo& info, const std::string& source_file, const std::vector& path) { std::vector annotations; FindAnnotationsOnPath(info, source_file, path, &annotations); @@ -112,9 +112,9 @@ const GeneratedCodeInfo::Annotation* FindAnnotationOnPath( } bool AtLeastOneAnnotationMatchesSubstring( - absl::string_view file_content, + const std::string& file_content, const std::vector& annotations, - absl::string_view expected_text, + const std::string& expected_text, absl::optional semantic) { for (std::vector::const_iterator i = annotations.begin(), @@ -133,9 +133,9 @@ bool AtLeastOneAnnotationMatchesSubstring( return false; } -bool AnnotationMatchesSubstring(absl::string_view file_content, +bool AnnotationMatchesSubstring(const std::string& file_content, const GeneratedCodeInfo::Annotation* annotation, - absl::string_view expected_text) { + const std::string& expected_text) { std::vector annotations; annotations.push_back(annotation); return AtLeastOneAnnotationMatchesSubstring(file_content, annotations, diff --git a/src/google/protobuf/compiler/annotation_test_util.h b/src/google/protobuf/compiler/annotation_test_util.h index d6f1170dab..fe0bee8e38 100644 --- a/src/google/protobuf/compiler/annotation_test_util.h +++ b/src/google/protobuf/compiler/annotation_test_util.h @@ -31,7 +31,8 @@ struct ExpectedOutput { std::string file_path; std::string file_content; GeneratedCodeInfo file_info; - explicit ExpectedOutput(absl::string_view file_path) : file_path(file_path) {} + explicit ExpectedOutput(const std::string& file_path) + : file_path(file_path) {} }; // Creates a file with name `filename` and content `data` in temp test @@ -53,13 +54,13 @@ bool RunProtoCompiler(const std::string& filename, const std::string& plugin_specific_args, CommandLineInterface* cli, FileDescriptorProto* file); -bool DecodeMetadata(absl::string_view path, GeneratedCodeInfo* info); +bool DecodeMetadata(const std::string& path, GeneratedCodeInfo* info); // Finds all of the Annotations for a given source file and path. // See Location.path in https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/descriptor.proto for // explanation of what path vector is. void FindAnnotationsOnPath( - const GeneratedCodeInfo& info, absl::string_view source_file, + const GeneratedCodeInfo& info, const std::string& source_file, const std::vector& path, std::vector* annotations); @@ -69,23 +70,23 @@ void FindAnnotationsOnPath( // https://github.com/protocolbuffers/protobuf/blob/main/src/google/protobuf/descriptor.proto for explanation of what path // vector is. const GeneratedCodeInfo::Annotation* FindAnnotationOnPath( - const GeneratedCodeInfo& info, absl::string_view source_file, + const GeneratedCodeInfo& info, const std::string& source_file, const std::vector& path); // Returns true if at least one of the provided annotations covers a given // substring with the given semantic in file_content. bool AtLeastOneAnnotationMatchesSubstring( - absl::string_view file_content, + const std::string& file_content, const std::vector& annotations, - absl::string_view expected_text, + const std::string& expected_text, absl::optional expected_semantic = absl::nullopt); // Returns true if the provided annotation covers a given substring in // file_content. -bool AnnotationMatchesSubstring(absl::string_view file_content, +bool AnnotationMatchesSubstring(const std::string& file_content, const GeneratedCodeInfo::Annotation* annotation, - absl::string_view expected_text); + const std::string& expected_text); // Returns the text spanned by the annotation if the span is valid; otherwise // returns nullopt. diff --git a/src/google/protobuf/compiler/command_line_interface.cc b/src/google/protobuf/compiler/command_line_interface.cc index cc4663a4b8..6508d4b6cc 100644 --- a/src/google/protobuf/compiler/command_line_interface.cc +++ b/src/google/protobuf/compiler/command_line_interface.cc @@ -11,17 +11,32 @@ #include "google/protobuf/compiler/command_line_interface.h" -#include - -#include #include -#include #include #include -#include -#include -#include +#include "absl/algorithm/container.h" +#include "absl/base/attributes.h" +#include "absl/base/log_severity.h" +#include "absl/container/btree_map.h" +#include "absl/container/btree_set.h" +#include "absl/container/flat_hash_map.h" +#include "absl/log/globals.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "absl/types/span.h" +#include "google/protobuf/compiler/versions.h" +#include "google/protobuf/descriptor_database.h" +#include "google/protobuf/descriptor_visitor.h" +#include "google/protobuf/feature_resolver.h" +#include "google/protobuf/io/zero_copy_stream_impl_lite.h" + +#include "google/protobuf/stubs/platform_macros.h" + +#include +#include +#include #ifdef major #undef major #endif @@ -35,6 +50,9 @@ #endif #include +#include +#include + #include // For PATH_MAX #include @@ -48,49 +66,30 @@ #include #endif -#include "absl/algorithm/container.h" -#include "absl/base/attributes.h" -#include "absl/base/log_severity.h" -#include "absl/container/btree_map.h" -#include "absl/container/btree_set.h" -#include "absl/container/flat_hash_map.h" -#include "absl/container/flat_hash_set.h" #include "absl/log/absl_check.h" #include "absl/log/absl_log.h" -#include "absl/log/globals.h" -#include "absl/status/status.h" -#include "absl/status/statusor.h" +#include "absl/container/flat_hash_set.h" #include "absl/strings/match.h" -#include "absl/strings/str_cat.h" #include "absl/strings/str_format.h" #include "absl/strings/str_replace.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/strings/substitute.h" -#include "absl/types/span.h" #include "google/protobuf/compiler/code_generator.h" #include "google/protobuf/compiler/importer.h" #include "google/protobuf/compiler/plugin.pb.h" #include "google/protobuf/compiler/retention.h" #include "google/protobuf/compiler/subprocess.h" -#include "google/protobuf/compiler/versions.h" #include "google/protobuf/compiler/zip_writer.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/descriptor.pb.h" -#include "google/protobuf/descriptor_database.h" -#include "google/protobuf/descriptor_visitor.h" #include "google/protobuf/dynamic_message.h" -#include "google/protobuf/feature_resolver.h" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/io/printer.h" #include "google/protobuf/io/zero_copy_stream_impl.h" -#include "google/protobuf/io/zero_copy_stream_impl_lite.h" #include "google/protobuf/text_format.h" -#include "google/protobuf/stubs/platform_macros.h" - - #ifdef _WIN32 #include "google/protobuf/io/io_win32.h" #endif @@ -132,7 +131,7 @@ static const char* kDefaultDirectDependenciesViolationMsg = // Returns true if the text looks like a Windows-style absolute path, starting // with a drive letter. Example: "C:\foo". TODO: Share this with // copy in importer.cc? -static bool IsWindowsAbsolutePath(absl::string_view text) { +static bool IsWindowsAbsolutePath(const std::string& text) { #if defined(_WIN32) || defined(__CYGWIN__) return text.size() >= 3 && text[1] == ':' && absl::ascii_isalpha(text[0]) && (text[2] == '/' || text[2] == '\\') && text.find_last_of(':') == 1; @@ -168,10 +167,10 @@ void AddTrailingSlash(std::string* path) { } } -bool VerifyDirectoryExists(absl::string_view path) { +bool VerifyDirectoryExists(const std::string& path) { if (path.empty()) return true; - if (access(std::string(path).c_str(), F_OK) == -1) { + if (access(path.c_str(), F_OK) == -1) { std::cerr << path << ": " << strerror(errno) << std::endl; return false; } else { @@ -183,13 +182,13 @@ bool VerifyDirectoryExists(absl::string_view path) { // parent if necessary, and so on. The full file name is actually // (prefix + filename), but we assume |prefix| already exists and only create // directories listed in |filename|. -bool TryCreateParentDirectory(absl::string_view prefix, - absl::string_view filename) { +bool TryCreateParentDirectory(const std::string& prefix, + const std::string& filename) { // Recursively create parent directories to the output file. // On Windows, both '/' and '\' are valid path separators. std::vector parts = absl::StrSplit(filename, absl::ByAnyChar("/\\"), absl::SkipEmpty()); - std::string path_so_far = std::string(prefix); + std::string path_so_far = prefix; for (size_t i = 0; i < parts.size() - 1; ++i) { path_so_far += parts[i]; if (mkdir(path_so_far.c_str(), 0777) != 0) { @@ -298,7 +297,7 @@ std::string PluginName(absl::string_view plugin_prefix, directive.substr(2, directive.size() - 6)); } -bool GetBootstrapParam(absl::string_view parameter) { +bool GetBootstrapParam(const std::string& parameter) { std::vector parts = absl::StrSplit(parameter, ','); for (const auto& part : parts) { if (part == "bootstrap") { @@ -448,11 +447,11 @@ class CommandLineInterface::GeneratorContextImpl : public GeneratorContext { // Write all files in the directory to disk at the given output location, // which must end in a '/'. - bool WriteAllToDisk(absl::string_view prefix); + bool WriteAllToDisk(const std::string& prefix); // Write the contents of this directory to a ZIP-format archive with the // given name. - bool WriteAllToZip(absl::string_view filename); + bool WriteAllToZip(const std::string& filename); // Add a boilerplate META-INF/MANIFEST.MF file as required by the Java JAR // format, unless one has already been written. @@ -487,13 +486,13 @@ class CommandLineInterface::MemoryOutputStream : public io::ZeroCopyOutputStream { public: MemoryOutputStream(GeneratorContextImpl* directory, - absl::string_view filename, bool append_mode); + const std::string& filename, bool append_mode); MemoryOutputStream(GeneratorContextImpl* directory, - absl::string_view filename, - absl::string_view insertion_point); + const std::string& filename, + const std::string& insertion_point); MemoryOutputStream(GeneratorContextImpl* directory, - absl::string_view filename, - absl::string_view insertion_point, + const std::string& filename, + const std::string& insertion_point, const google::protobuf::GeneratedCodeInfo& info); ~MemoryOutputStream() override; @@ -512,14 +511,14 @@ class CommandLineInterface::MemoryOutputStream // insertion_offset and indent_length. We assume that insertions will not // occur within any given annotated span of text. insertion_content must end // with an endline. - void UpdateMetadata(absl::string_view insertion_content, + void UpdateMetadata(const std::string& insertion_content, size_t insertion_offset, size_t insertion_length, size_t indent_length); // Inserts info_to_insert_ into target_info, assuming that the relevant // insertion was made at insertion_offset in file_content with the given // indent_length. insertion_content must end with an endline. - void InsertShiftedInfo(absl::string_view insertion_content, + void InsertShiftedInfo(const std::string& insertion_content, size_t insertion_offset, size_t indent_length, google::protobuf::GeneratedCodeInfo& target_info); @@ -548,7 +547,7 @@ CommandLineInterface::GeneratorContextImpl::GeneratorContextImpl( : parsed_files_(parsed_files), had_error_(false) {} bool CommandLineInterface::GeneratorContextImpl::WriteAllToDisk( - absl::string_view prefix) { + const std::string& prefix) { if (had_error_) { return false; } @@ -558,14 +557,14 @@ bool CommandLineInterface::GeneratorContextImpl::WriteAllToDisk( } for (const auto& pair : files_) { - absl::string_view relative_filename = pair.first; + const std::string& relative_filename = pair.first; const char* data = pair.second.data(); int size = pair.second.size(); if (!TryCreateParentDirectory(prefix, relative_filename)) { return false; } - std::string filename = absl::StrCat(prefix, relative_filename); + std::string filename = prefix + relative_filename; // Create the output file. int file_descriptor; @@ -622,7 +621,7 @@ bool CommandLineInterface::GeneratorContextImpl::WriteAllToDisk( } bool CommandLineInterface::GeneratorContextImpl::WriteAllToZip( - absl::string_view filename) { + const std::string& filename) { if (had_error_) { return false; } @@ -630,8 +629,8 @@ bool CommandLineInterface::GeneratorContextImpl::WriteAllToZip( // Create the output file. int file_descriptor; do { - file_descriptor = open(std::string(filename).c_str(), - O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666); + file_descriptor = + open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_BINARY, 0666); } while (file_descriptor < 0 && errno == EINTR); if (file_descriptor < 0) { @@ -707,7 +706,7 @@ CommandLineInterface::GeneratorContextImpl::OpenForInsertWithGeneratedCodeInfo( // ------------------------------------------------------------------- CommandLineInterface::MemoryOutputStream::MemoryOutputStream( - GeneratorContextImpl* directory, absl::string_view filename, + GeneratorContextImpl* directory, const std::string& filename, bool append_mode) : directory_(directory), filename_(filename), @@ -715,16 +714,16 @@ CommandLineInterface::MemoryOutputStream::MemoryOutputStream( inner_(new io::StringOutputStream(&data_)) {} CommandLineInterface::MemoryOutputStream::MemoryOutputStream( - GeneratorContextImpl* directory, absl::string_view filename, - absl::string_view insertion_point) + GeneratorContextImpl* directory, const std::string& filename, + const std::string& insertion_point) : directory_(directory), filename_(filename), insertion_point_(insertion_point), inner_(new io::StringOutputStream(&data_)) {} CommandLineInterface::MemoryOutputStream::MemoryOutputStream( - GeneratorContextImpl* directory, absl::string_view filename, - absl::string_view insertion_point, const google::protobuf::GeneratedCodeInfo& info) + GeneratorContextImpl* directory, const std::string& filename, + const std::string& insertion_point, const google::protobuf::GeneratedCodeInfo& info) : directory_(directory), filename_(filename), insertion_point_(insertion_point), @@ -732,7 +731,7 @@ CommandLineInterface::MemoryOutputStream::MemoryOutputStream( info_to_insert_(info) {} void CommandLineInterface::MemoryOutputStream::InsertShiftedInfo( - absl::string_view insertion_content, size_t insertion_offset, + const std::string& insertion_content, size_t insertion_offset, size_t indent_length, google::protobuf::GeneratedCodeInfo& target_info) { // Keep track of how much extra data was added for indents before the // current annotation being inserted. `pos` and `source_annotation.begin()` @@ -768,7 +767,7 @@ void CommandLineInterface::MemoryOutputStream::InsertShiftedInfo( } void CommandLineInterface::MemoryOutputStream::UpdateMetadata( - absl::string_view insertion_content, size_t insertion_offset, + const std::string& insertion_content, size_t insertion_offset, size_t insertion_length, size_t indent_length) { auto it = directory_->files_.find(absl::StrCat(filename_, ".pb.meta")); if (it == directory_->files_.end() && info_to_insert_.annotation().empty()) { @@ -964,31 +963,30 @@ CommandLineInterface::CommandLineInterface() CommandLineInterface::~CommandLineInterface() = default; -void CommandLineInterface::RegisterGenerator(absl::string_view flag_name, +void CommandLineInterface::RegisterGenerator(const std::string& flag_name, CodeGenerator* generator, - absl::string_view help_text) { + const std::string& help_text) { GeneratorInfo info; - info.flag_name = std::string(flag_name); + info.flag_name = flag_name; info.generator = generator; - info.help_text = std::string(help_text); + info.help_text = help_text; generators_by_flag_name_[flag_name] = info; } -void CommandLineInterface::RegisterGenerator(absl::string_view flag_name, - absl::string_view option_flag_name, - CodeGenerator* generator, - absl::string_view help_text) { +void CommandLineInterface::RegisterGenerator( + const std::string& flag_name, const std::string& option_flag_name, + CodeGenerator* generator, const std::string& help_text) { GeneratorInfo info; - info.flag_name = std::string(flag_name); - info.option_flag_name = std::string(option_flag_name); + info.flag_name = flag_name; + info.option_flag_name = option_flag_name; info.generator = generator; - info.help_text = std::string(help_text); + info.help_text = help_text; generators_by_flag_name_[flag_name] = info; generators_by_option_name_[option_flag_name] = info; } -void CommandLineInterface::AllowPlugins(absl::string_view exe_name_prefix) { - plugin_prefix_ = std::string(exe_name_prefix); +void CommandLineInterface::AllowPlugins(const std::string& exe_name_prefix) { + plugin_prefix_ = exe_name_prefix; } namespace { @@ -1031,7 +1029,7 @@ bool HasReservedFieldNumber(const FieldDescriptor* field) { namespace { std::unique_ptr -PopulateSingleSimpleDescriptorDatabase(absl::string_view descriptor_set_name); +PopulateSingleSimpleDescriptorDatabase(const std::string& descriptor_set_name); // Indicates whether the field is compatible with the given target type. bool IsFieldCompatible(const FieldDescriptor& field, @@ -1206,7 +1204,7 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) { // Any --descriptor_set_in FileDescriptorSet objects will be used as a // fallback to input_files on command line, so create that db first. if (!descriptor_set_in_names_.empty()) { - for (absl::string_view name : descriptor_set_in_names_) { + for (const std::string& name : descriptor_set_in_names_) { std::unique_ptr database_for_descriptor_set = PopulateSingleSimpleDescriptorDatabase(name); if (!database_for_descriptor_set) { @@ -1358,7 +1356,7 @@ int CommandLineInterface::Run(int argc, const char* const argv[]) { } for (const auto& pair : output_directories) { - absl::string_view location = pair.first; + const std::string& location = pair.first; GeneratorContextImpl* directory = pair.second.get(); if (absl::EndsWith(location, "/")) { if (!directory->WriteAllToDisk(location)) { @@ -1460,10 +1458,10 @@ bool CommandLineInterface::InitializeDiskSourceTree( namespace { std::unique_ptr -PopulateSingleSimpleDescriptorDatabase(absl::string_view descriptor_set_name) { +PopulateSingleSimpleDescriptorDatabase(const std::string& descriptor_set_name) { int fd; do { - fd = open(std::string(descriptor_set_name).c_str(), O_RDONLY | O_BINARY); + fd = open(descriptor_set_name.c_str(), O_RDONLY | O_BINARY); } while (fd < 0 && errno == EINTR); if (fd < 0) { std::cerr << descriptor_set_name << ": " << strerror(ENOENT) << std::endl; @@ -2028,8 +2026,8 @@ bool CommandLineInterface::ParseArgument(const char* arg, std::string* name, } CommandLineInterface::ParseArgumentStatus -CommandLineInterface::InterpretArgument(absl::string_view name, - absl::string_view value) { +CommandLineInterface::InterpretArgument(const std::string& name, + const std::string& value) { if (name.empty()) { // Not a flag. Just a filename. if (value.empty()) { @@ -2048,8 +2046,8 @@ CommandLineInterface::InterpretArgument(absl::string_view name, // On Windows, the shell (typically cmd.exe) does not expand wildcards in // file names (e.g. foo\*.proto), so we do it ourselves. switch (google::protobuf::io::win32::ExpandWildcards( - std::string(value), [this](absl::string_view path) { - this->input_files_.push_back(std::string(path)); + value, [this](const std::string& path) { + this->input_files_.push_back(path); })) { case google::protobuf::io::win32::ExpandWildcardsResult::kSuccess: break; @@ -2067,7 +2065,7 @@ CommandLineInterface::InterpretArgument(absl::string_view name, #else // not _WIN32 // On other platforms than Windows (e.g. Linux, Mac OS) the shell (typically // Bash) expands wildcards. - input_files_.push_back(std::string(value)); + input_files_.push_back(value); #endif // _WIN32 } else if (name == "-I" || name == "--proto_path") { @@ -2135,7 +2133,7 @@ CommandLineInterface::InterpretArgument(absl::string_view name, direct_dependencies_.insert(direct.begin(), direct.end()); } else if (name == "--direct_dependencies_violation_msg") { - direct_dependencies_violation_msg_ = std::string(value); + direct_dependencies_violation_msg_ = value; } else if (name == "--descriptor_set_in") { if (!descriptor_set_in_names_.empty()) { @@ -2176,7 +2174,7 @@ CommandLineInterface::InterpretArgument(absl::string_view name, << std::endl; return PARSE_ARGUMENT_FAIL; } - descriptor_set_out_name_ = std::string(value); + descriptor_set_out_name_ = value; } else if (name == "--dependency_out") { if (!dependency_out_name_.empty()) { @@ -2192,7 +2190,7 @@ CommandLineInterface::InterpretArgument(absl::string_view name, << std::endl; return PARSE_ARGUMENT_FAIL; } - dependency_out_name_ = std::string(value); + dependency_out_name_ = value; } else if (name == "--include_imports") { if (imports_in_descriptor_set_) { @@ -2263,7 +2261,7 @@ CommandLineInterface::InterpretArgument(absl::string_view name, return PARSE_ARGUMENT_FAIL; } - codec_type_ = std::string(value); + codec_type_ = value; } else if (name == "--deterministic_output") { deterministic_output_ = true; @@ -2290,14 +2288,14 @@ CommandLineInterface::InterpretArgument(absl::string_view name, return PARSE_ARGUMENT_FAIL; } - absl::string_view plugin_name; - absl::string_view path; + std::string plugin_name; + std::string path; - auto equals_pos = value.find_first_of('='); - if (equals_pos == value.npos) { + std::string::size_type equals_pos = value.find_first_of('='); + if (equals_pos == std::string::npos) { // Use the basename of the file. - auto slash_pos = value.find_last_of('/'); - if (slash_pos == value.npos) { + std::string::size_type slash_pos = value.find_last_of('/'); + if (slash_pos == std::string::npos) { plugin_name = value; } else { plugin_name = value.substr(slash_pos + 1); @@ -2308,7 +2306,7 @@ CommandLineInterface::InterpretArgument(absl::string_view name, path = value.substr(equals_pos + 1); } - plugins_[plugin_name] = std::string(path); + plugins_[plugin_name] = path; } else if (name == "--print_free_field_numbers") { if (mode_ != MODE_COMPILE) { @@ -2364,7 +2362,7 @@ CommandLineInterface::InterpretArgument(absl::string_view name, << std::endl; return PARSE_ARGUMENT_FAIL; } - edition_defaults_out_name_ = std::string(value); + edition_defaults_out_name_ = value; } else if (name == "--edition_defaults_minimum") { if (edition_defaults_minimum_ != EDITION_UNKNOWN) { std::cerr << name << " may only be passed once." << std::endl; @@ -2398,14 +2396,14 @@ CommandLineInterface::InterpretArgument(absl::string_view name, if (!parameters->empty()) { parameters->append(","); } - parameters->append(std::string(value)); + parameters->append(value); } else if (absl::StartsWith(name, "--") && absl::EndsWith(name, "_opt")) { std::string* parameters = &plugin_parameters_[PluginName(plugin_prefix_, name)]; if (!parameters->empty()) { parameters->append(","); } - parameters->append(std::string(value)); + parameters->append(value); } else { std::cerr << "Unknown flag: " << name << std::endl; return PARSE_ARGUMENT_FAIL; @@ -2420,7 +2418,7 @@ CommandLineInterface::InterpretArgument(absl::string_view name, } OutputDirective directive; - directive.name = std::string(name); + directive.name = name; if (generator_info == nullptr) { directive.generator = nullptr; } else { @@ -2430,12 +2428,12 @@ CommandLineInterface::InterpretArgument(absl::string_view name, // Split value at ':' to separate the generator parameter from the // filename. However, avoid doing this if the colon is part of a valid // Windows-style absolute path. - auto colon_pos = value.find_first_of(':'); - if (colon_pos == value.npos || IsWindowsAbsolutePath(value)) { - directive.output_location = std::string(value); + std::string::size_type colon_pos = value.find_first_of(':'); + if (colon_pos == std::string::npos || IsWindowsAbsolutePath(value)) { + directive.output_location = value; } else { - directive.parameter = std::string(value.substr(0, colon_pos)); - directive.output_location = std::string(value.substr(colon_pos + 1)); + directive.parameter = value.substr(0, colon_pos); + directive.output_location = value.substr(colon_pos + 1); } output_directives_.push_back(directive); @@ -2556,7 +2554,7 @@ Parse PROTO_FILES and generate output based on the options given: } bool CommandLineInterface::EnforceProto3OptionalSupport( - absl::string_view codegen_name, uint64_t supported_features, + const std::string& codegen_name, uint64_t supported_features, const std::vector& parsed_files) const { bool supports_proto3_optional = supported_features & CodeGenerator::FEATURE_PROTO3_OPTIONAL; @@ -2580,7 +2578,7 @@ bool CommandLineInterface::EnforceProto3OptionalSupport( } bool CommandLineInterface::EnforceEditionsSupport( - absl::string_view codegen_name, uint64_t supported_features, + const std::string& codegen_name, uint64_t supported_features, Edition minimum_edition, Edition maximum_edition, const std::vector& parsed_files) const { if (experimental_editions_) { @@ -2696,13 +2694,12 @@ bool CommandLineInterface::GenerateDependencyManifestFile( std::vector output_filenames; for (const auto& pair : output_directories) { - absl::string_view location = pair.first; + const std::string& location = pair.first; GeneratorContextImpl* directory = pair.second.get(); std::vector relative_output_filenames; directory->GetOutputFilenames(&relative_output_filenames); for (size_t i = 0; i < relative_output_filenames.size(); ++i) { - std::string output_filename = - absl::StrCat(location, relative_output_filenames[i]); + std::string output_filename = location + relative_output_filenames[i]; if (output_filename.compare(0, 2, "./") == 0) { output_filename = output_filename.substr(2); } @@ -2747,7 +2744,7 @@ bool CommandLineInterface::GenerateDependencyManifestFile( for (int i = 0; i < file_set.file_size(); ++i) { const FileDescriptorProto& file = file_set.file(i); - absl::string_view virtual_file = file.name(); + const std::string& virtual_file = file.name(); std::string disk_file; if (source_tree && source_tree->VirtualFileToDiskFile(virtual_file, &disk_file)) { @@ -2766,11 +2763,11 @@ bool CommandLineInterface::GenerateDependencyManifestFile( bool CommandLineInterface::GeneratePluginOutput( const std::vector& parsed_files, - absl::string_view plugin_name, absl::string_view parameter, + const std::string& plugin_name, const std::string& parameter, GeneratorContext* generator_context, std::string* error) { CodeGeneratorRequest request; CodeGeneratorResponse response; - std::string processed_parameter = std::string(parameter); + std::string processed_parameter = parameter; bool bootstrap = GetBootstrapParam(processed_parameter); @@ -3098,14 +3095,14 @@ bool CommandLineInterface::WriteEditionDefaults(const DescriptorPool& pool) { } const CommandLineInterface::GeneratorInfo* -CommandLineInterface::FindGeneratorByFlag(absl::string_view name) const { +CommandLineInterface::FindGeneratorByFlag(const std::string& name) const { auto it = generators_by_flag_name_.find(name); if (it == generators_by_flag_name_.end()) return nullptr; return &it->second; } const CommandLineInterface::GeneratorInfo* -CommandLineInterface::FindGeneratorByOption(absl::string_view option) const { +CommandLineInterface::FindGeneratorByOption(const std::string& option) const { auto it = generators_by_option_name_.find(option); if (it == generators_by_option_name_.end()) return nullptr; return &it->second; @@ -3171,10 +3168,10 @@ void GatherOccupiedFieldRanges( // Utility function for PrintFreeFieldNumbers. // Actually prints the formatted free field numbers for given message name and // occupied ranges. -void FormatFreeFieldNumbers(absl::string_view name, +void FormatFreeFieldNumbers(const std::string& name, const absl::btree_set& ranges) { std::string output; - absl::StrAppendFormat(&output, "%-35s free:", name); + absl::StrAppendFormat(&output, "%-35s free:", name.c_str()); int next_free_number = 1; for (const auto& range : ranges) { // This happens when groups re-use parent field numbers, in which @@ -3216,5 +3213,3 @@ void CommandLineInterface::PrintFreeFieldNumbers(const Descriptor* descriptor) { } // namespace compiler } // namespace protobuf } // namespace google - -#include "google/protobuf/port_undef.inc" diff --git a/src/google/protobuf/compiler/command_line_interface.h b/src/google/protobuf/compiler/command_line_interface.h index 73e0c2a238..3a535a455d 100644 --- a/src/google/protobuf/compiler/command_line_interface.h +++ b/src/google/protobuf/compiler/command_line_interface.h @@ -120,8 +120,8 @@ class PROTOC_EXPORT CommandLineInterface { // protoc --foo_out=enable_bar:outdir // The text before the colon is passed to CodeGenerator::Generate() as the // "parameter". - void RegisterGenerator(absl::string_view flag_name, CodeGenerator* generator, - absl::string_view help_text); + void RegisterGenerator(const std::string& flag_name, CodeGenerator* generator, + const std::string& help_text); // Register a code generator for a language. // Besides flag_name you can specify another option_flag_name that could be @@ -131,9 +131,10 @@ class PROTOC_EXPORT CommandLineInterface { // Then you could invoke the compiler with a command like: // protoc --foo_out=enable_bar:outdir --foo_opt=enable_baz // This will pass "enable_bar,enable_baz" as the parameter to the generator. - void RegisterGenerator(absl::string_view flag_name, - absl::string_view option_flag_name, - CodeGenerator* generator, absl::string_view help_text); + void RegisterGenerator(const std::string& flag_name, + const std::string& option_flag_name, + CodeGenerator* generator, + const std::string& help_text); // Enables "plugins". In this mode, if a command-line flag ends with "_out" // but does not match any registered generator, the compiler will attempt to @@ -171,7 +172,7 @@ class PROTOC_EXPORT CommandLineInterface { // protoc --plug_out=enable_bar:outdir --plug_opt=enable_baz // This will pass "enable_bar,enable_baz" as the parameter to the plugin. // - void AllowPlugins(absl::string_view exe_name_prefix); + void AllowPlugins(const std::string& exe_name_prefix); // Run the Protocol Compiler with the given command-line parameters. // Returns the error code which should be returned by main(). @@ -189,9 +190,7 @@ class PROTOC_EXPORT CommandLineInterface { // Provides some text which will be printed when the --version flag is // used. The version of libprotoc will also be printed on the next line // after this text. - void SetVersionInfo(absl::string_view text) { - version_info_ = std::string(text); - } + void SetVersionInfo(const std::string& text) { version_info_ = text; } // Configure protoc to act as if we're in opensource. @@ -225,11 +224,11 @@ class PROTOC_EXPORT CommandLineInterface { // Fails if these files use proto3 optional and the code generator doesn't // support it. This is a permanent check. bool EnforceProto3OptionalSupport( - absl::string_view codegen_name, uint64_t supported_features, + const std::string& codegen_name, uint64_t supported_features, const std::vector& parsed_files) const; bool EnforceEditionsSupport( - absl::string_view codegen_name, uint64_t supported_features, + const std::string& codegen_name, uint64_t supported_features, Edition minimum_edition, Edition maximum_edition, const std::vector& parsed_files) const; @@ -263,8 +262,8 @@ class PROTOC_EXPORT CommandLineInterface { bool ParseArgument(const char* arg, std::string* name, std::string* value); // Interprets arguments parsed with ParseArgument. - ParseArgumentStatus InterpretArgument(absl::string_view name, - absl::string_view value); + ParseArgumentStatus InterpretArgument(const std::string& name, + const std::string& value); // Print the --help text to stderr. void PrintHelpText(); @@ -290,7 +289,7 @@ class PROTOC_EXPORT CommandLineInterface { GeneratorContext* generator_context); bool GeneratePluginOutput( const std::vector& parsed_files, - absl::string_view plugin_name, absl::string_view parameter, + const std::string& plugin_name, const std::string& parameter, GeneratorContext* generator_context, std::string* error); // Implements --encode and --decode. @@ -357,8 +356,8 @@ class PROTOC_EXPORT CommandLineInterface { std::string help_text; }; - const GeneratorInfo* FindGeneratorByFlag(absl::string_view name) const; - const GeneratorInfo* FindGeneratorByOption(absl::string_view option) const; + const GeneratorInfo* FindGeneratorByFlag(const std::string& name) const; + const GeneratorInfo* FindGeneratorByOption(const std::string& option) const; absl::btree_map generators_by_flag_name_; absl::flat_hash_map generators_by_option_name_; diff --git a/src/google/protobuf/compiler/command_line_interface_tester.cc b/src/google/protobuf/compiler/command_line_interface_tester.cc index 997953d075..1586ee1df6 100644 --- a/src/google/protobuf/compiler/command_line_interface_tester.cc +++ b/src/google/protobuf/compiler/command_line_interface_tester.cc @@ -140,10 +140,9 @@ void CommandLineInterfaceTester::ExpectWarningSubstring( #if defined(_WIN32) && !defined(__CYGWIN__) bool CommandLineInterfaceTester::HasAlternateErrorSubstring( - absl::string_view expected_substring) { + const std::string& expected_substring) { EXPECT_NE(0, return_code_); - return absl::string_view(error_text_).find(expected_substring) != - absl::string_view::npos; + return error_text_.find(expected_substring) != std::string::npos; } #endif // _WIN32 && !__CYGWIN__ diff --git a/src/google/protobuf/compiler/command_line_interface_tester.h b/src/google/protobuf/compiler/command_line_interface_tester.h index e3f1983acc..b77dfa32b9 100644 --- a/src/google/protobuf/compiler/command_line_interface_tester.h +++ b/src/google/protobuf/compiler/command_line_interface_tester.h @@ -51,19 +51,19 @@ class CommandLineInterfaceTester : public testing::Test { // Returns the temporary directory created for testing. std::string temp_directory() { return temp_directory_; } - void AllowPlugins(absl::string_view prefix) { cli_.AllowPlugins(prefix); } + void AllowPlugins(const std::string& prefix) { cli_.AllowPlugins(prefix); } - void RegisterGenerator(absl::string_view flag_name, + void RegisterGenerator(const std::string& flag_name, std::unique_ptr generator, - absl::string_view help_text) { + const std::string& help_text) { generators_.emplace_back(std::move(generator)); cli_.RegisterGenerator(flag_name, generators_.back().get(), help_text); } - void RegisterGenerator(absl::string_view flag_name, - absl::string_view option_flag_name, + void RegisterGenerator(const std::string& flag_name, + const std::string& option_flag_name, std::unique_ptr generator, - absl::string_view help_text) { + const std::string& help_text) { generators_.emplace_back(std::move(generator)); cli_.RegisterGenerator(flag_name, option_flag_name, generators_.back().get(), help_text); @@ -119,7 +119,7 @@ class CommandLineInterfaceTester : public testing::Test { #if defined(_WIN32) && !defined(__CYGWIN__) // Returns true if ExpectErrorSubstring(expected_substring) would pass, but // does not fail otherwise. - bool HasAlternateErrorSubstring(absl::string_view expected_substring); + bool HasAlternateErrorSubstring(const std::string& expected_substring); #endif // _WIN32 && !__CYGWIN__ void ExpectFileContent(absl::string_view filename, absl::string_view content); diff --git a/src/google/protobuf/compiler/command_line_interface_unittest.cc b/src/google/protobuf/compiler/command_line_interface_unittest.cc index 16af8d9ee9..99fe927644 100644 --- a/src/google/protobuf/compiler/command_line_interface_unittest.cc +++ b/src/google/protobuf/compiler/command_line_interface_unittest.cc @@ -13,12 +13,21 @@ #include #include +#include +#include + +#include +#include "absl/log/absl_check.h" +#include "absl/strings/escaping.h" +#include "absl/strings/str_cat.h" +#include "absl/types/span.h" +#include "google/protobuf/compiler/command_line_interface_tester.h" +#include "google/protobuf/unittest_features.pb.h" +#include "google/protobuf/unittest_invalid_features.pb.h" + #ifndef _MSC_VER #include #endif - -#include -#include #include #include #include @@ -28,19 +37,13 @@ #include "google/protobuf/testing/file.h" #include "google/protobuf/any.pb.h" #include "google/protobuf/descriptor.pb.h" -#include #include "google/protobuf/testing/googletest.h" #include -#include "absl/log/absl_check.h" -#include "absl/strings/escaping.h" -#include "absl/strings/str_cat.h" #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "absl/strings/substitute.h" -#include "absl/types/span.h" #include "google/protobuf/compiler/code_generator.h" #include "google/protobuf/compiler/command_line_interface.h" -#include "google/protobuf/compiler/command_line_interface_tester.h" #include "google/protobuf/compiler/cpp/names.h" #include "google/protobuf/compiler/mock_code_generator.h" #include "google/protobuf/compiler/plugin.pb.h" @@ -48,9 +51,6 @@ #include "google/protobuf/test_util2.h" #include "google/protobuf/unittest.pb.h" #include "google/protobuf/unittest_custom_options.pb.h" -#include "google/protobuf/unittest_features.pb.h" -#include "google/protobuf/unittest_invalid_features.pb.h" - #ifdef GOOGLE_PROTOBUF_USE_BAZEL_GENERATED_PLUGIN_PATHS // This is needed because of https://github.com/bazelbuild/bazel/issues/19124. @@ -158,29 +158,29 @@ class CommandLineInterfaceTest : public CommandLineInterfaceTester { // generate given these inputs. message_name is the name of the first // message that appeared in the proto file; this is just to make extra // sure that the correct file was parsed. - void ExpectGenerated(absl::string_view generator_name, - absl::string_view parameter, - absl::string_view proto_name, - absl::string_view message_name); - void ExpectGenerated(absl::string_view generator_name, - absl::string_view parameter, - absl::string_view proto_name, - absl::string_view message_name, - absl::string_view output_directory); - void ExpectGeneratedWithMultipleInputs(absl::string_view generator_name, - absl::string_view all_proto_names, - absl::string_view proto_name, - absl::string_view message_name); - void ExpectGeneratedWithInsertions(absl::string_view generator_name, - absl::string_view parameter, - absl::string_view insertions, - absl::string_view proto_name, - absl::string_view message_name); - void CheckGeneratedAnnotations(absl::string_view name, - absl::string_view file); + void ExpectGenerated(const std::string& generator_name, + const std::string& parameter, + const std::string& proto_name, + const std::string& message_name); + void ExpectGenerated(const std::string& generator_name, + const std::string& parameter, + const std::string& proto_name, + const std::string& message_name, + const std::string& output_directory); + void ExpectGeneratedWithMultipleInputs(const std::string& generator_name, + const std::string& all_proto_names, + const std::string& proto_name, + const std::string& message_name); + void ExpectGeneratedWithInsertions(const std::string& generator_name, + const std::string& parameter, + const std::string& insertions, + const std::string& proto_name, + const std::string& message_name); + void CheckGeneratedAnnotations(const std::string& name, + const std::string& file); #if defined(_WIN32) - void ExpectNullCodeGeneratorCalled(absl::string_view parameter); + void ExpectNullCodeGeneratorCalled(const std::string& parameter); #endif // _WIN32 @@ -195,8 +195,8 @@ class CommandLineInterfaceTest : public CommandLineInterfaceTester { // The default code generators support all features. Use this to create a // code generator that omits the given feature(s). - void CreateGeneratorWithMissingFeatures(absl::string_view name, - absl::string_view description, + void CreateGeneratorWithMissingFeatures(const std::string& name, + const std::string& description, uint64_t features) { auto generator = std::make_unique(name); generator->SuppressFeatures(features); @@ -286,49 +286,48 @@ void CommandLineInterfaceTest::RunWithArgs(std::vector args) { // ------------------------------------------------------------------- -void CommandLineInterfaceTest::ExpectGenerated(absl::string_view generator_name, - absl::string_view parameter, - absl::string_view proto_name, - absl::string_view message_name) { +void CommandLineInterfaceTest::ExpectGenerated( + const std::string& generator_name, const std::string& parameter, + const std::string& proto_name, const std::string& message_name) { MockCodeGenerator::ExpectGenerated(generator_name, parameter, "", proto_name, message_name, proto_name, temp_directory()); } void CommandLineInterfaceTest::ExpectGenerated( - absl::string_view generator_name, absl::string_view parameter, - absl::string_view proto_name, absl::string_view message_name, - absl::string_view output_directory) { + const std::string& generator_name, const std::string& parameter, + const std::string& proto_name, const std::string& message_name, + const std::string& output_directory) { MockCodeGenerator::ExpectGenerated( generator_name, parameter, "", proto_name, message_name, proto_name, absl::StrCat(temp_directory(), "/", output_directory)); } void CommandLineInterfaceTest::ExpectGeneratedWithMultipleInputs( - absl::string_view generator_name, absl::string_view all_proto_names, - absl::string_view proto_name, absl::string_view message_name) { + const std::string& generator_name, const std::string& all_proto_names, + const std::string& proto_name, const std::string& message_name) { MockCodeGenerator::ExpectGenerated(generator_name, "", "", proto_name, message_name, all_proto_names, temp_directory()); } void CommandLineInterfaceTest::ExpectGeneratedWithInsertions( - absl::string_view generator_name, absl::string_view parameter, - absl::string_view insertions, absl::string_view proto_name, - absl::string_view message_name) { + const std::string& generator_name, const std::string& parameter, + const std::string& insertions, const std::string& proto_name, + const std::string& message_name) { MockCodeGenerator::ExpectGenerated(generator_name, parameter, insertions, proto_name, message_name, proto_name, temp_directory()); } void CommandLineInterfaceTest::CheckGeneratedAnnotations( - absl::string_view name, absl::string_view file) { + const std::string& name, const std::string& file) { MockCodeGenerator::CheckGeneratedAnnotations(name, file, temp_directory()); } #if defined(_WIN32) void CommandLineInterfaceTest::ExpectNullCodeGeneratorCalled( - absl::string_view parameter) { + const std::string& parameter) { EXPECT_TRUE(null_generator_->called_); EXPECT_EQ(parameter, null_generator_->parameter_); } @@ -4025,14 +4024,14 @@ class EncodeDecodeTest : public testing::TestWithParam { close(duped_stdin_); } - void RedirectStdinFromText(absl::string_view input) { + void RedirectStdinFromText(const std::string& input) { std::string filename = absl::StrCat(TestTempDir(), "/test_stdin"); ABSL_CHECK_OK(File::SetContents(filename, input, true)); ABSL_CHECK(RedirectStdinFromFile(filename)); } - bool RedirectStdinFromFile(absl::string_view filename) { - int fd = open(std::string(filename).c_str(), O_RDONLY); + bool RedirectStdinFromFile(const std::string& filename) { + int fd = open(filename.c_str(), O_RDONLY); if (fd < 0) return false; dup2(fd, STDIN_FILENO); close(fd); @@ -4040,7 +4039,7 @@ class EncodeDecodeTest : public testing::TestWithParam { } // Remove '\r' characters from text. - std::string StripCR(absl::string_view text) { + std::string StripCR(const std::string& text) { std::string result; for (size_t i = 0; i < text.size(); ++i) { @@ -4055,7 +4054,7 @@ class EncodeDecodeTest : public testing::TestWithParam { enum Type { TEXT, BINARY }; enum ReturnCode { SUCCESS, ERROR }; - bool Run(absl::string_view command, bool specify_proto_files = true) { + bool Run(const std::string& command, bool specify_proto_files = true) { std::vector args; args.push_back("protoc"); for (absl::string_view split_piece : @@ -4095,7 +4094,7 @@ class EncodeDecodeTest : public testing::TestWithParam { return result == 0; } - void ExpectStdoutMatchesBinaryFile(absl::string_view filename) { + void ExpectStdoutMatchesBinaryFile(const std::string& filename) { std::string expected_output; ABSL_CHECK_OK( File::GetContents(filename, &expected_output, true)); @@ -4105,7 +4104,7 @@ class EncodeDecodeTest : public testing::TestWithParam { EXPECT_TRUE(captured_stdout_ == expected_output); } - void ExpectStdoutMatchesTextFile(absl::string_view filename) { + void ExpectStdoutMatchesTextFile(const std::string& filename) { std::string expected_output; ABSL_CHECK_OK( File::GetContents(filename, &expected_output, true)); @@ -4113,15 +4112,15 @@ class EncodeDecodeTest : public testing::TestWithParam { ExpectStdoutMatchesText(expected_output); } - void ExpectStdoutMatchesText(absl::string_view expected_text) { + void ExpectStdoutMatchesText(const std::string& expected_text) { EXPECT_EQ(StripCR(expected_text), StripCR(captured_stdout_)); } - void ExpectStderrMatchesText(absl::string_view expected_text) { + void ExpectStderrMatchesText(const std::string& expected_text) { EXPECT_EQ(StripCR(expected_text), StripCR(captured_stderr_)); } - void ExpectStderrContainsText(absl::string_view expected_text) { + void ExpectStderrContainsText(const std::string& expected_text) { EXPECT_NE(StripCR(captured_stderr_).find(StripCR(expected_text)), std::string::npos); } diff --git a/src/google/protobuf/compiler/cpp/BUILD.bazel b/src/google/protobuf/compiler/cpp/BUILD.bazel index ba05453f9a..5e59286ad9 100644 --- a/src/google/protobuf/compiler/cpp/BUILD.bazel +++ b/src/google/protobuf/compiler/cpp/BUILD.bazel @@ -283,7 +283,6 @@ cc_test( "//src/google/protobuf/testing", "//src/google/protobuf/testing:file", "@com_google_absl//absl/log:absl_check", - "@com_google_absl//absl/strings:string_view", "@com_google_googletest//:gtest", "@com_google_googletest//:gtest_main", ], diff --git a/src/google/protobuf/compiler/cpp/bootstrap_unittest.cc b/src/google/protobuf/compiler/cpp/bootstrap_unittest.cc index 307b99e170..5d64a9a889 100644 --- a/src/google/protobuf/compiler/cpp/bootstrap_unittest.cc +++ b/src/google/protobuf/compiler/cpp/bootstrap_unittest.cc @@ -43,9 +43,9 @@ namespace cpp { namespace { std::string FindWithDefault( const absl::flat_hash_map& m, - absl::string_view k, absl::string_view v) { + const std::string& k, const std::string& v) { auto it = m.find(k); - if (it == m.end()) return std::string(v); + if (it == m.end()) return v; return it->second; } @@ -66,8 +66,8 @@ class MockErrorCollector : public MultiFileErrorCollector { class MockGeneratorContext : public GeneratorContext { public: - void ExpectFileMatches(absl::string_view virtual_filename, - absl::string_view physical_filename) { + void ExpectFileMatches(const std::string& virtual_filename, + const std::string& physical_filename) { auto it = files_.find(virtual_filename); ASSERT_TRUE(it != files_.end()) << "Generator failed to generate file: " << virtual_filename; diff --git a/src/google/protobuf/compiler/cpp/message.cc b/src/google/protobuf/compiler/cpp/message.cc index 5572d8dff2..269f1e1f54 100644 --- a/src/google/protobuf/compiler/cpp/message.cc +++ b/src/google/protobuf/compiler/cpp/message.cc @@ -183,7 +183,7 @@ RunMap FindRuns(const std::vector& fields, return runs; } -void EmitNonDefaultCheck(io::Printer* p, absl::string_view prefix, +void EmitNonDefaultCheck(io::Printer* p, const std::string& prefix, const FieldDescriptor* field) { ABSL_CHECK(!HasHasbit(field)); ABSL_CHECK(!field->is_repeated()); @@ -222,7 +222,7 @@ bool ShouldEmitNonDefaultCheck(const FieldDescriptor* field) { // considered non-default (will be sent over the wire), for message types // without true field presence. Should only be called if // !HasHasbit(field). -bool MayEmitIfNonDefaultCheck(io::Printer* p, absl::string_view prefix, +bool MayEmitIfNonDefaultCheck(io::Printer* p, const std::string& prefix, const FieldDescriptor* field) { ABSL_CHECK(!HasHasbit(field)); if (!ShouldEmitNonDefaultCheck(field)) return false; @@ -410,7 +410,7 @@ static int popcnt(uint32_t n) { bool MaybeEmitHaswordsCheck(ChunkIterator it, ChunkIterator end, const Options& options, const std::vector& has_bit_indices, - int cached_has_word_index, absl::string_view from, + int cached_has_word_index, const std::string& from, io::Printer* p) { if (!it->has_hasbit || !IsProfileDriven(options) || std::distance(it, end) < 2 || !it->is_rarely_present) { diff --git a/src/google/protobuf/compiler/cpp/metadata_test.cc b/src/google/protobuf/compiler/cpp/metadata_test.cc index 7928bf6e3c..734d58ffaa 100644 --- a/src/google/protobuf/compiler/cpp/metadata_test.cc +++ b/src/google/protobuf/compiler/cpp/metadata_test.cc @@ -15,7 +15,6 @@ #include "google/protobuf/descriptor.pb.h" #include #include "absl/log/absl_check.h" -#include "absl/strings/string_view.h" #include "google/protobuf/compiler/annotation_test_util.h" #include "google/protobuf/compiler/cpp/helpers.h" @@ -34,7 +33,7 @@ class CppMetadataTest : public ::testing::Test { // code from the previously added file with name `filename`. Returns true on // success. If pb_h is non-null, expects a .pb.h and a .pb.h.meta (copied to // pb_h and pb_h_info respecfively); similarly for proto_h and proto_h_info. - bool CaptureMetadata(absl::string_view filename, FileDescriptorProto* file, + bool CaptureMetadata(const std::string& filename, FileDescriptorProto* file, std::string* pb_h, GeneratedCodeInfo* pb_h_info, std::string* proto_h, GeneratedCodeInfo* proto_h_info, std::string* pb_cc) { @@ -47,8 +46,7 @@ class CppMetadataTest : public ::testing::Test { "annotation_guard_name=guard_name:", ::testing::TempDir()); - const bool result = - atu::RunProtoCompiler(std::string(filename), cpp_out, &cli, file); + const bool result = atu::RunProtoCompiler(filename, cpp_out, &cli, file); if (!result) { return result; diff --git a/src/google/protobuf/compiler/cpp/namespace_printer.cc b/src/google/protobuf/compiler/cpp/namespace_printer.cc index 3681c51569..3531d7c737 100644 --- a/src/google/protobuf/compiler/cpp/namespace_printer.cc +++ b/src/google/protobuf/compiler/cpp/namespace_printer.cc @@ -5,7 +5,6 @@ #include #include "absl/log/die_if_null.h" -#include "absl/strings/string_view.h" #include "absl/strings/substitute.h" #include "google/protobuf/io/printer.h" @@ -19,7 +18,7 @@ NamespacePrinter::NamespacePrinter( : p_(ABSL_DIE_IF_NULL(p)), namespace_components_(std::move(namespace_components)) { // Open the namespace. - for (absl::string_view ns : namespace_components_) { + for (const std::string& ns : namespace_components_) { p_->Print(absl::Substitute("namespace $0 {\n", ns)); } p_->Print("\n"); @@ -27,7 +26,7 @@ NamespacePrinter::NamespacePrinter( NamespacePrinter::~NamespacePrinter() { // Close the namespace. - for (absl::string_view ns : namespace_components_) { + for (const std::string& ns : namespace_components_) { p_->Print(absl::Substitute("} // namespace $0\n", ns)); } } diff --git a/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc b/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc index 03a8ad844e..a6ab5d883c 100644 --- a/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc +++ b/src/google/protobuf/compiler/csharp/csharp_bootstrap_unittest.cc @@ -22,7 +22,6 @@ #include "absl/strings/escaping.h" #include "absl/strings/str_replace.h" #include "absl/strings/str_split.h" -#include "absl/strings/string_view.h" #include "absl/strings/substitute.h" #include "google/protobuf/compiler/csharp/csharp_generator.h" #include "google/protobuf/compiler/importer.h" @@ -53,8 +52,8 @@ class MockErrorCollector : public MultiFileErrorCollector { class MockGeneratorContext : public GeneratorContext { public: - void ExpectFileMatches(absl::string_view virtual_filename, - absl::string_view physical_filename) { + void ExpectFileMatches(const std::string& virtual_filename, + const std::string& physical_filename) { auto it = files_.find(virtual_filename); ASSERT_TRUE(it != files_.end()) << "Generator failed to generate file: " << virtual_filename; diff --git a/src/google/protobuf/compiler/csharp/csharp_field_base.h b/src/google/protobuf/compiler/csharp/csharp_field_base.h index 0ba522dd4d..a8c13ef926 100644 --- a/src/google/protobuf/compiler/csharp/csharp_field_base.h +++ b/src/google/protobuf/compiler/csharp/csharp_field_base.h @@ -59,6 +59,7 @@ class FieldGeneratorBase : public SourceGeneratorBase { void AddDeprecatedFlag(io::Printer* printer); void AddNullCheck(io::Printer* printer); + void AddNullCheck(io::Printer* printer, const std::string& name); void AddPublicMemberAttributes(io::Printer* printer); void SetCommonOneofFieldVariables( diff --git a/src/google/protobuf/compiler/importer.cc b/src/google/protobuf/compiler/importer.cc index b317e9e820..3c4f9ac174 100644 --- a/src/google/protobuf/compiler/importer.cc +++ b/src/google/protobuf/compiler/importer.cc @@ -32,7 +32,6 @@ #include "absl/strings/str_split.h" #include "absl/strings/string_view.h" #include "google/protobuf/compiler/parser.h" -#include "google/protobuf/descriptor.h" #include "google/protobuf/io/io_win32.h" #include "google/protobuf/io/tokenizer.h" #include "google/protobuf/io/zero_copy_stream_impl.h" @@ -73,7 +72,7 @@ MultiFileErrorCollector::~MultiFileErrorCollector() {} class SourceTreeDescriptorDatabase::SingleFileErrorCollector : public io::ErrorCollector { public: - SingleFileErrorCollector(absl::string_view filename, + SingleFileErrorCollector(const std::string& filename, MultiFileErrorCollector* multi_file_error_collector) : filename_(filename), multi_file_error_collector_(multi_file_error_collector), @@ -213,11 +212,11 @@ Importer::Importer(SourceTree* source_tree, Importer::~Importer() {} -const FileDescriptor* Importer::Import(absl::string_view filename) { +const FileDescriptor* Importer::Import(const std::string& filename) { return pool_.FindFileByName(filename); } -void Importer::AddUnusedImportTrackFile(absl::string_view file_name, +void Importer::AddUnusedImportTrackFile(const std::string& file_name, bool is_error) { pool_.AddUnusedImportTrackFile(file_name, is_error); } diff --git a/src/google/protobuf/compiler/importer.h b/src/google/protobuf/compiler/importer.h index 7b41694b95..6bb127a776 100644 --- a/src/google/protobuf/compiler/importer.h +++ b/src/google/protobuf/compiler/importer.h @@ -153,13 +153,13 @@ class PROTOBUF_EXPORT Importer { // you want to see errors for the same files repeatedly, you can use a // separate Importer object to import each one (but use the same // DescriptorPool so that they can be cross-linked). - const FileDescriptor* Import(absl::string_view filename); + const FileDescriptor* Import(const std::string& filename); // The DescriptorPool in which all imported FileDescriptors and their // contents are stored. inline const DescriptorPool* pool() const { return &pool_; } - void AddUnusedImportTrackFile(absl::string_view file_name, + void AddUnusedImportTrackFile(const std::string& file_name, bool is_error = false); void ClearUnusedImportTrackFiles(); diff --git a/src/google/protobuf/compiler/importer_unittest.cc b/src/google/protobuf/compiler/importer_unittest.cc index 704aaa8f9f..67a11c5939 100644 --- a/src/google/protobuf/compiler/importer_unittest.cc +++ b/src/google/protobuf/compiler/importer_unittest.cc @@ -22,7 +22,6 @@ #include "absl/log/absl_check.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" -#include "absl/strings/string_view.h" #include "absl/strings/substitute.h" #include "google/protobuf/descriptor.h" #include "google/protobuf/io/zero_copy_stream_impl.h" @@ -33,7 +32,7 @@ namespace compiler { namespace { -bool FileExists(absl::string_view path) { +bool FileExists(const std::string& path) { return File::Exists(path); } @@ -94,7 +93,7 @@ class ImporterTest : public testing::Test { protected: ImporterTest() : importer_(&source_tree_, &error_collector_) {} - void AddFile(absl::string_view filename, const char* text) { + void AddFile(const std::string& filename, const char* text) { source_tree_.AddFile(filename, text); } @@ -259,15 +258,15 @@ class DiskSourceTreeTest : public testing::Test { } } - void AddFile(absl::string_view filename, const char* contents) { + void AddFile(const std::string& filename, const char* contents) { ABSL_CHECK_OK(File::SetContents(filename, contents, true)); } - void AddSubdir(absl::string_view dirname) { + void AddSubdir(const std::string& dirname) { ABSL_CHECK_OK(File::CreateDir(dirname, 0777)); } - void ExpectFileContents(absl::string_view filename, + void ExpectFileContents(const std::string& filename, const char* expected_contents) { std::unique_ptr input(source_tree_.Open(filename)); @@ -284,8 +283,8 @@ class DiskSourceTreeTest : public testing::Test { EXPECT_EQ(expected_contents, file_contents); } - void ExpectCannotOpenFile(absl::string_view filename, - absl::string_view error_message) { + void ExpectCannotOpenFile(const std::string& filename, + const std::string& error_message) { std::unique_ptr input(source_tree_.Open(filename)); EXPECT_TRUE(input == nullptr); EXPECT_EQ(error_message, source_tree_.GetLastErrorMessage()); diff --git a/src/google/protobuf/compiler/java/context.cc b/src/google/protobuf/compiler/java/context.cc index 1d66fcfbc6..e37afbcb18 100644 --- a/src/google/protobuf/compiler/java/context.cc +++ b/src/google/protobuf/compiler/java/context.cc @@ -16,7 +16,6 @@ #include "google/protobuf/compiler/java/field_common.h" #include "google/protobuf/compiler/java/helpers.h" #include "google/protobuf/compiler/java/name_resolver.h" -#include "google/protobuf/compiler/java/names.h" #include "google/protobuf/descriptor.h" namespace google { @@ -121,10 +120,10 @@ void Context::InitializeFieldGeneratorInfoForFields( std::vector conflict_reason(fields.size()); for (int i = 0; i < fields.size(); ++i) { const FieldDescriptor* field = fields[i]; - const std::string name = CapitalizedFieldName(field); + const std::string& name = CapitalizedFieldName(field); for (int j = i + 1; j < fields.size(); ++j) { const FieldDescriptor* other = fields[j]; - const std::string other_name = CapitalizedFieldName(other); + const std::string& other_name = CapitalizedFieldName(other); if (name == other_name) { is_conflict[i] = is_conflict[j] = true; conflict_reason[i] = conflict_reason[j] = diff --git a/src/google/protobuf/compiler/java/context.h b/src/google/protobuf/compiler/java/context.h index a49f7100ed..993301bbd7 100644 --- a/src/google/protobuf/compiler/java/context.h +++ b/src/google/protobuf/compiler/java/context.h @@ -12,7 +12,6 @@ #include #include "absl/container/flat_hash_map.h" -#include "absl/strings/string_view.h" #include "google/protobuf/compiler/java/helpers.h" #include "google/protobuf/compiler/java/options.h" #include "google/protobuf/port.h" @@ -88,7 +87,7 @@ class Context { template void MaybePrintGeneratedAnnotation(Context* context, io::Printer* printer, Descriptor* descriptor, bool immutable, - absl::string_view suffix = "") { + const std::string& suffix = "") { if (IsOwnFile(descriptor, immutable)) { PrintGeneratedAnnotation(printer, '$', context->options().annotate_code @@ -98,6 +97,7 @@ void MaybePrintGeneratedAnnotation(Context* context, io::Printer* printer, } } + } // namespace java } // namespace compiler } // namespace protobuf diff --git a/src/google/protobuf/compiler/java/doc_comment.cc b/src/google/protobuf/compiler/java/doc_comment.cc index ceaabc9d7d..2e194dd59d 100644 --- a/src/google/protobuf/compiler/java/doc_comment.cc +++ b/src/google/protobuf/compiler/java/doc_comment.cc @@ -29,7 +29,7 @@ namespace protobuf { namespace compiler { namespace java { -std::string EscapeJavadoc(absl::string_view input) { +std::string EscapeJavadoc(const std::string& input) { std::string result; result.reserve(input.size() * 2); @@ -87,7 +87,7 @@ std::string EscapeJavadoc(absl::string_view input) { return result; } -static std::string EscapeKdoc(absl::string_view input) { +static std::string EscapeKdoc(const std::string& input) { std::string result; result.reserve(input.size() * 2); @@ -189,8 +189,8 @@ static void WriteDocCommentBody(io::Printer* printer, } } -static std::string FirstLineOf(absl::string_view value) { - std::string result = std::string(value); +static std::string FirstLineOf(const std::string& value) { + std::string result = value; std::string::size_type pos = result.find_first_of('\n'); if (pos != std::string::npos) { diff --git a/src/google/protobuf/compiler/java/doc_comment.h b/src/google/protobuf/compiler/java/doc_comment.h index 41c4d3126a..0820b16aeb 100644 --- a/src/google/protobuf/compiler/java/doc_comment.h +++ b/src/google/protobuf/compiler/java/doc_comment.h @@ -12,7 +12,6 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_JAVA_DOC_COMMENT_H__ #define GOOGLE_PROTOBUF_COMPILER_JAVA_DOC_COMMENT_H__ -#include "absl/strings/string_view.h" #include "google/protobuf/compiler/java/options.h" #include "google/protobuf/descriptor.h" @@ -72,7 +71,7 @@ void WriteMethodDocComment(io::Printer* printer, const MethodDescriptor* method, // Exposed for testing only. // Also called by proto1-Java code generator. -PROTOC_EXPORT std::string EscapeJavadoc(absl::string_view input); +PROTOC_EXPORT std::string EscapeJavadoc(const std::string& input); } // namespace java } // namespace compiler diff --git a/src/google/protobuf/compiler/java/file.cc b/src/google/protobuf/compiler/java/file.cc index bfbbc2c714..6995513bd1 100644 --- a/src/google/protobuf/compiler/java/file.cc +++ b/src/google/protobuf/compiler/java/file.cc @@ -108,7 +108,7 @@ bool CollectExtensions(const Message& message, FieldDescriptorSet* extensions) { void CollectExtensions(const FileDescriptorProto& file_proto, const DescriptorPool& alternate_pool, FieldDescriptorSet* extensions, - absl::string_view file_data) { + const std::string& file_data) { if (!CollectExtensions(file_proto, extensions)) { // There are unknown fields in the file_proto, which are probably // extensions. We need to parse the data into a dynamic message based on the @@ -513,10 +513,10 @@ void FileGenerator::GenerateDescriptorInitializationCodeForImmutable( template static void GenerateSibling( - absl::string_view package_dir, absl::string_view java_package, + const std::string& package_dir, const std::string& java_package, const DescriptorClass* descriptor, GeneratorContext* context, std::vector* file_list, bool annotate_code, - std::vector* annotation_list, absl::string_view name_suffix, + std::vector* annotation_list, const std::string& name_suffix, GeneratorClass* generator, bool opensource_runtime, void (GeneratorClass::*pfn)(io::Printer* printer)) { std::string filename = @@ -561,7 +561,7 @@ static void GenerateSibling( } void FileGenerator::GenerateSiblings( - absl::string_view package_dir, GeneratorContext* context, + const std::string& package_dir, GeneratorContext* context, std::vector* file_list, std::vector* annotation_list) { if (MultipleJavaFiles(file_, immutable_api_)) { @@ -625,15 +625,14 @@ void FileGenerator::GenerateKotlin(io::Printer* printer) { } void FileGenerator::GenerateKotlinSiblings( - absl::string_view package_dir, GeneratorContext* context, + const std::string& package_dir, GeneratorContext* context, std::vector* file_list, std::vector* annotation_list) { for (int i = 0; i < file_->message_type_count(); i++) { const Descriptor* descriptor = file_->message_type(i); MessageGenerator* generator = message_generators_[i].get(); - auto open_file = [context](absl::string_view filename) { - return std::unique_ptr( - context->Open(std::string(filename))); + auto open_file = [context](const std::string& filename) { + return std::unique_ptr(context->Open(filename)); }; std::string filename = absl::StrCat(package_dir, descriptor->name(), "Kt.kt"); diff --git a/src/google/protobuf/compiler/java/file.h b/src/google/protobuf/compiler/java/file.h index 35242e4a4b..7d995ee33c 100644 --- a/src/google/protobuf/compiler/java/file.h +++ b/src/google/protobuf/compiler/java/file.h @@ -16,7 +16,6 @@ #include #include -#include "absl/strings/string_view.h" #include "google/protobuf/compiler/java/options.h" #include "google/protobuf/port.h" @@ -61,7 +60,7 @@ class FileGenerator { std::string GetKotlinClassname(); void GenerateKotlin(io::Printer* printer); - void GenerateKotlinSiblings(absl::string_view package_dir, + void GenerateKotlinSiblings(const std::string& package_dir, GeneratorContext* generator_context, std::vector* file_list, std::vector* annotation_list); @@ -69,7 +68,7 @@ class FileGenerator { // If we aren't putting everything into one file, this will write all the // files other than the outer file (i.e. one for each message, enum, and // service type). - void GenerateSiblings(absl::string_view package_dir, + void GenerateSiblings(const std::string& package_dir, GeneratorContext* generator_context, std::vector* file_list, std::vector* annotation_list); diff --git a/src/google/protobuf/compiler/java/full/message_field.cc b/src/google/protobuf/compiler/java/full/message_field.cc index a3ace3224e..54ae8dea17 100644 --- a/src/google/protobuf/compiler/java/full/message_field.cc +++ b/src/google/protobuf/compiler/java/full/message_field.cc @@ -15,7 +15,6 @@ #include "absl/log/absl_check.h" #include "absl/strings/str_cat.h" -#include "absl/strings/string_view.h" #include "google/protobuf/compiler/java/context.h" #include "google/protobuf/compiler/java/doc_comment.h" #include "google/protobuf/compiler/java/field_common.h" diff --git a/src/google/protobuf/compiler/java/helpers.cc b/src/google/protobuf/compiler/java/helpers.cc index ced31519a7..8deb2dcec3 100644 --- a/src/google/protobuf/compiler/java/helpers.cc +++ b/src/google/protobuf/compiler/java/helpers.cc @@ -181,7 +181,7 @@ bool IsForbiddenKotlin(absl::string_view field_name) { return kKotlinForbiddenNames.contains(field_name); } -std::string EscapeKotlinKeywords(absl::string_view name) { +std::string EscapeKotlinKeywords(std::string name) { std::vector escaped_packages; std::vector packages = absl::StrSplit(name, "."); // NOLINT for (absl::string_view package : packages) { @@ -211,7 +211,7 @@ std::string FileClassName(const FileDescriptor* file, bool immutable) { return ClassNameResolver().GetFileClassName(file, immutable); } -std::string JavaPackageToDir(absl::string_view package_name) { +std::string JavaPackageToDir(std::string package_name) { std::string package_dir = absl::StrReplaceAll(package_name, {{".", "/"}}); if (!package_dir.empty()) absl::StrAppend(&package_dir, "/"); return package_dir; diff --git a/src/google/protobuf/compiler/java/helpers.h b/src/google/protobuf/compiler/java/helpers.h index 19dbb5dd7a..d99e085a65 100644 --- a/src/google/protobuf/compiler/java/helpers.h +++ b/src/google/protobuf/compiler/java/helpers.h @@ -85,10 +85,10 @@ std::string FileJavaPackage(const FileDescriptor* file, bool immutable, Options options = {}); // Returns output directory for the given package name. -std::string JavaPackageToDir(absl::string_view package_name); +std::string JavaPackageToDir(std::string package_name); // Returns the name with Kotlin keywords enclosed in backticks -std::string EscapeKotlinKeywords(absl::string_view name); +std::string EscapeKotlinKeywords(std::string name); // Comma-separate list of option-specified interfaces implemented by the // Message, to follow the "implements" declaration of the Message definition. diff --git a/src/google/protobuf/compiler/java/shared_code_generator.cc b/src/google/protobuf/compiler/java/shared_code_generator.cc index f4ee26ed2c..d2bb9a5dd8 100644 --- a/src/google/protobuf/compiler/java/shared_code_generator.cc +++ b/src/google/protobuf/compiler/java/shared_code_generator.cc @@ -13,7 +13,6 @@ #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" -#include "absl/strings/string_view.h" #include "google/protobuf/compiler/code_generator.h" #include "google/protobuf/compiler/java/helpers.h" #include "google/protobuf/compiler/java/name_resolver.h" @@ -190,7 +189,7 @@ void SharedCodeGenerator::GenerateDescriptors(io::Printer* printer) { " new com.google.protobuf.Descriptors.FileDescriptor[] {\n"); for (int i = 0; i < dependencies.size(); i++) { - absl::string_view dependency = dependencies[i].second; + const std::string& dependency = dependencies[i].second; printer->Print(" $dependency$.getDescriptor(),\n", "dependency", dependency); } diff --git a/src/google/protobuf/compiler/objectivec/field.cc b/src/google/protobuf/compiler/objectivec/field.cc index d9de5b04b7..c60158afb5 100644 --- a/src/google/protobuf/compiler/objectivec/field.cc +++ b/src/google/protobuf/compiler/objectivec/field.cc @@ -50,10 +50,10 @@ void SetCommonFieldVariables( UnCamelCaseFieldName(camel_case_name, descriptor)); const bool needs_custom_name = (raw_field_name != un_camel_case_name); - const std::string classname = ClassName(descriptor->containing_type()); + const std::string& classname = ClassName(descriptor->containing_type()); (*variables)["classname"] = classname; (*variables)["name"] = camel_case_name; - const std::string capitalized_name = FieldNameCapitalized(descriptor); + const std::string& capitalized_name = FieldNameCapitalized(descriptor); (*variables)["capitalized_name"] = capitalized_name; (*variables)["raw_field_name"] = raw_field_name; (*variables)["field_number_name"] = @@ -137,7 +137,8 @@ bool HasNonZeroDefaultValue(const FieldDescriptor* field) { case FieldDescriptor::CPPTYPE_BOOL: return field->default_value_bool(); case FieldDescriptor::CPPTYPE_STRING: { - return !field->default_value_string().empty(); + const std::string& default_string = field->default_value_string(); + return !default_string.empty(); } case FieldDescriptor::CPPTYPE_ENUM: // The default value for an enum field is the first enum value, so there diff --git a/src/google/protobuf/compiler/objectivec/field.h b/src/google/protobuf/compiler/objectivec/field.h index c583cf3b2b..06e08e1f0a 100644 --- a/src/google/protobuf/compiler/objectivec/field.h +++ b/src/google/protobuf/compiler/objectivec/field.h @@ -75,8 +75,8 @@ class FieldGenerator { } bool needs_textformat_name_support() const { - return absl::StrContains(variable("fieldflags"), - "GPBFieldTextFormatNameCustom"); + const std::string& field_flags = variable("fieldflags"); + return absl::StrContains(field_flags, "GPBFieldTextFormatNameCustom"); } std::string generated_objc_name() const { return variable("name"); } std::string raw_field_name() const { return variable("raw_field_name"); } diff --git a/src/google/protobuf/compiler/objectivec/import_writer.cc b/src/google/protobuf/compiler/objectivec/import_writer.cc index aacd4717a1..85641dc9a9 100644 --- a/src/google/protobuf/compiler/objectivec/import_writer.cc +++ b/src/google/protobuf/compiler/objectivec/import_writer.cc @@ -97,9 +97,9 @@ bool ProtoFrameworkCollector::ConsumeLine(absl::string_view line, } // namespace ImportWriter::ImportWriter( - absl::string_view generate_for_named_framework, - absl::string_view named_framework_to_proto_path_mappings_path, - absl::string_view runtime_import_prefix, bool for_bundled_proto) + const std::string& generate_for_named_framework, + const std::string& named_framework_to_proto_path_mappings_path, + const std::string& runtime_import_prefix, bool for_bundled_proto) : generate_for_named_framework_(generate_for_named_framework), named_framework_to_proto_path_mappings_path_( named_framework_to_proto_path_mappings_path), @@ -108,7 +108,7 @@ ImportWriter::ImportWriter( need_to_parse_mapping_file_(true) {} void ImportWriter::AddFile(const FileDescriptor* file, - absl::string_view header_extension) { + const std::string& header_extension) { if (IsProtobufLibraryBundledProtoFile(file)) { // The imports of the WKTs are only needed within the library itself, // in other cases, they get skipped because the generated code already @@ -135,11 +135,11 @@ void ImportWriter::AddFile(const FileDescriptor* file, return; } - other_imports_.push_back(absl::StrCat(FilePath(file), header_extension)); + other_imports_.push_back(FilePath(file) + header_extension); } -void ImportWriter::AddRuntimeImport(absl::string_view header_name) { - protobuf_imports_.push_back(std::string(header_name)); +void ImportWriter::AddRuntimeImport(const std::string& header_name) { + protobuf_imports_.push_back(header_name); } std::string ImportWriter::ModuleForFile(const FileDescriptor* file) { diff --git a/src/google/protobuf/compiler/objectivec/import_writer.h b/src/google/protobuf/compiler/objectivec/import_writer.h index 16e2960cf8..bff1fd03cb 100644 --- a/src/google/protobuf/compiler/objectivec/import_writer.h +++ b/src/google/protobuf/compiler/objectivec/import_writer.h @@ -12,7 +12,6 @@ #include #include "absl/container/flat_hash_map.h" -#include "absl/strings/string_view.h" #include "google/protobuf/descriptor.h" namespace google { @@ -24,13 +23,14 @@ namespace objectivec { // import statements. class ImportWriter { public: - ImportWriter(absl::string_view generate_for_named_framework, - absl::string_view named_framework_to_proto_path_mappings_path, - absl::string_view runtime_import_prefix, bool for_bundled_proto); + ImportWriter(const std::string& generate_for_named_framework, + const std::string& named_framework_to_proto_path_mappings_path, + const std::string& runtime_import_prefix, + bool for_bundled_proto); ~ImportWriter() = default; - void AddFile(const FileDescriptor* file, absl::string_view header_extension); - void AddRuntimeImport(absl::string_view header_name); + void AddFile(const FileDescriptor* file, const std::string& header_extension); + void AddRuntimeImport(const std::string& header_name); // This can return an empty string if there is no module for the file. It also // does not handle bundled proto files. std::string ModuleForFile(const FileDescriptor* file); diff --git a/src/google/protobuf/compiler/objectivec/message.cc b/src/google/protobuf/compiler/objectivec/message.cc index 974ab15bb2..cde92f60d0 100644 --- a/src/google/protobuf/compiler/objectivec/message.cc +++ b/src/google/protobuf/compiler/objectivec/message.cc @@ -192,7 +192,7 @@ const FieldDescriptor** SortFieldsByStorageSize(const Descriptor* descriptor) { } // namespace -MessageGenerator::MessageGenerator(absl::string_view file_description_name, +MessageGenerator::MessageGenerator(const std::string& file_description_name, const Descriptor* descriptor, const GenerationOptions& generation_options) : file_description_name_(file_description_name), diff --git a/src/google/protobuf/compiler/objectivec/message.h b/src/google/protobuf/compiler/objectivec/message.h index 2f9b97c738..b87ad569ed 100644 --- a/src/google/protobuf/compiler/objectivec/message.h +++ b/src/google/protobuf/compiler/objectivec/message.h @@ -15,7 +15,6 @@ #include "absl/container/btree_set.h" #include "absl/container/flat_hash_set.h" -#include "absl/strings/string_view.h" #include "google/protobuf/compiler/objectivec/field.h" #include "google/protobuf/compiler/objectivec/oneof.h" #include "google/protobuf/compiler/objectivec/options.h" @@ -31,7 +30,7 @@ class ExtensionGenerator; class MessageGenerator { public: - MessageGenerator(absl::string_view file_description_name, + MessageGenerator(const std::string& file_description_name, const Descriptor* descriptor, const GenerationOptions& generation_options); ~MessageGenerator() = default; diff --git a/src/google/protobuf/compiler/objectivec/tf_decode_data.cc b/src/google/protobuf/compiler/objectivec/tf_decode_data.cc index 76b10be667..8eade5d17a 100644 --- a/src/google/protobuf/compiler/objectivec/tf_decode_data.cc +++ b/src/google/protobuf/compiler/objectivec/tf_decode_data.cc @@ -16,8 +16,6 @@ #include "absl/strings/ascii.h" #include "absl/strings/escaping.h" #include "absl/strings/match.h" -#include "absl/strings/str_cat.h" -#include "absl/strings/string_view.h" #include "google/protobuf/io/coded_stream.h" #include "google/protobuf/io/zero_copy_stream_impl.h" @@ -138,18 +136,19 @@ bool DecodeDataBuilder::AddCharacter(char desired, char input) { // If decode data can't be generated, a directive for the raw string // is used instead. -std::string DirectDecodeString(absl::string_view str) { - return absl::StrCat(absl::string_view("\0", 1), // Marker for full string. - str, // - absl::string_view("\0", 1) // End of string. - ); +std::string DirectDecodeString(const std::string& str) { + std::string result; + result += (char)'\0'; // Marker for full string. + result += str; + result += (char)'\0'; // End of string. + return result; } } // namespace void TextFormatDecodeData::AddString(int32_t key, - absl::string_view input_for_decode, - absl::string_view desired_output) { + const std::string& input_for_decode, + const std::string& desired_output) { for (std::vector::const_iterator i = entries_.begin(); i != entries_.end(); ++i) { ABSL_CHECK(i->first != key) @@ -158,8 +157,8 @@ void TextFormatDecodeData::AddString(int32_t key, << "\", desired: \"" << desired_output << "\"."; } - std::string data = TextFormatDecodeData::DecodeDataForString(input_for_decode, - desired_output); + const std::string& data = TextFormatDecodeData::DecodeDataForString( + input_for_decode, desired_output); entries_.push_back(DataEntry(key, data)); } @@ -184,7 +183,7 @@ std::string TextFormatDecodeData::Data() const { // static std::string TextFormatDecodeData::DecodeDataForString( - absl::string_view input_for_decode, absl::string_view desired_output) { + const std::string& input_for_decode, const std::string& desired_output) { ABSL_CHECK(!input_for_decode.empty() && !desired_output.empty()) << "error: got empty string for making TextFormat data, input: \"" << input_for_decode << "\", desired: \"" << desired_output << "\"."; diff --git a/src/google/protobuf/compiler/objectivec/tf_decode_data.h b/src/google/protobuf/compiler/objectivec/tf_decode_data.h index b9eda2bd26..1e7932afa2 100644 --- a/src/google/protobuf/compiler/objectivec/tf_decode_data.h +++ b/src/google/protobuf/compiler/objectivec/tf_decode_data.h @@ -14,8 +14,6 @@ #include #include -#include "absl/strings/string_view.h" - // Must be included last #include "google/protobuf/port_def.inc" @@ -37,13 +35,13 @@ class PROTOC_EXPORT TextFormatDecodeData { TextFormatDecodeData(const TextFormatDecodeData&) = delete; TextFormatDecodeData& operator=(const TextFormatDecodeData&) = delete; - void AddString(int32_t key, absl::string_view input_for_decode, - absl::string_view desired_output); + void AddString(int32_t key, const std::string& input_for_decode, + const std::string& desired_output); size_t num_entries() const { return entries_.size(); } std::string Data() const; - static std::string DecodeDataForString(absl::string_view input_for_decode, - absl::string_view desired_output); + static std::string DecodeDataForString(const std::string& input_for_decode, + const std::string& desired_output); private: typedef std::pair DataEntry; diff --git a/src/google/protobuf/compiler/parser.cc b/src/google/protobuf/compiler/parser.cc index 29f9db5612..bc17e7a70a 100644 --- a/src/google/protobuf/compiler/parser.cc +++ b/src/google/protobuf/compiler/parser.cc @@ -485,7 +485,7 @@ void Parser::LocationRecorder::RecordLegacyLocation( } void Parser::LocationRecorder::RecordLegacyImportLocation( - const Message* descriptor, absl::string_view name) { + const Message* descriptor, const std::string& name) { if (parser_->source_location_table_ != nullptr) { parser_->source_location_table_->AddImport( descriptor, name, location_->span(0), location_->span(1)); @@ -2641,9 +2641,9 @@ void SourceLocationTable::Add( } void SourceLocationTable::AddImport(const Message* descriptor, - absl::string_view name, int line, + const std::string& name, int line, int column) { - import_location_map_[std::make_pair(descriptor, std::string(name))] = + import_location_map_[std::make_pair(descriptor, name)] = std::make_pair(line, column); } diff --git a/src/google/protobuf/compiler/parser.h b/src/google/protobuf/compiler/parser.h index 21a55924f0..f1e709d1bc 100644 --- a/src/google/protobuf/compiler/parser.h +++ b/src/google/protobuf/compiler/parser.h @@ -286,7 +286,7 @@ class PROTOBUF_EXPORT Parser final { const Message* descriptor, DescriptorPool::ErrorCollector::ErrorLocation location); void RecordLegacyImportLocation(const Message* descriptor, - absl::string_view name); + const std::string& name); // Returns the number of path components in the recorder's current location. int CurrentPathSize() const; @@ -605,7 +605,7 @@ class PROTOBUF_EXPORT SourceLocationTable { void Add(const Message* descriptor, DescriptorPool::ErrorCollector::ErrorLocation location, int line, int column); - void AddImport(const Message* descriptor, absl::string_view name, int line, + void AddImport(const Message* descriptor, const std::string& name, int line, int column); // Clears the contents of the table. diff --git a/src/google/protobuf/compiler/parser_unittest.cc b/src/google/protobuf/compiler/parser_unittest.cc index e81bad220f..f9b8f32317 100644 --- a/src/google/protobuf/compiler/parser_unittest.cc +++ b/src/google/protobuf/compiler/parser_unittest.cc @@ -28,7 +28,6 @@ #include "absl/memory/memory.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_join.h" -#include "absl/strings/string_view.h" #include "absl/strings/substitute.h" #include "google/protobuf/compiler/retention.h" #include "google/protobuf/test_util2.h" @@ -3178,19 +3177,19 @@ class SourceInfoTest : public ParserTest { } bool HasSpan(char start_marker, char end_marker, - const Message& descriptor_proto, absl::string_view field_name) { + const Message& descriptor_proto, const std::string& field_name) { return HasSpan(start_marker, end_marker, descriptor_proto, field_name, -1); } bool HasSpan(char start_marker, char end_marker, - const Message& descriptor_proto, absl::string_view field_name, + const Message& descriptor_proto, const std::string& field_name, int index) { return HasSpan(start_marker, end_marker, descriptor_proto, field_name, index, nullptr, nullptr, nullptr); } bool HasSpan(char start_marker, char end_marker, - const Message& descriptor_proto, absl::string_view field_name, + const Message& descriptor_proto, const std::string& field_name, int index, const char* expected_leading_comments, const char* expected_trailing_comments, const char* expected_leading_detached_comments) { @@ -3213,7 +3212,7 @@ class SourceInfoTest : public ParserTest { nullptr, nullptr, nullptr); } - bool HasSpan(const Message& descriptor_proto, absl::string_view field_name) { + bool HasSpan(const Message& descriptor_proto, const std::string& field_name) { return HasSpan('\0', '\0', descriptor_proto, field_name, -1); } diff --git a/src/google/protobuf/compiler/php/names.cc b/src/google/protobuf/compiler/php/names.cc index 2be667c80f..135b55b94e 100644 --- a/src/google/protobuf/compiler/php/names.cc +++ b/src/google/protobuf/compiler/php/names.cc @@ -49,7 +49,7 @@ bool IsReservedName(absl::string_view name) { return false; } -std::string ReservedNamePrefix(absl::string_view classname, +std::string ReservedNamePrefix(const std::string& classname, const FileDescriptor* file) { if (IsReservedName(classname)) { if (file->package() == "google.protobuf") { @@ -65,11 +65,11 @@ std::string ReservedNamePrefix(absl::string_view classname, namespace { template -std::string ClassNamePrefixImpl(absl::string_view classname, +std::string ClassNamePrefixImpl(const std::string& classname, const DescriptorType* desc) { - absl::string_view prefix = desc->file()->options().php_class_prefix(); + const std::string& prefix = (desc->file()->options()).php_class_prefix(); if (!prefix.empty()) { - return std::string(prefix); + return prefix; } return ReservedNamePrefix(classname, desc->file()); @@ -94,11 +94,11 @@ std::string GeneratedClassNameImpl(const ServiceDescriptor* desc) { } // namespace -std::string ClassNamePrefix(absl::string_view classname, +std::string ClassNamePrefix(const std::string& classname, const Descriptor* desc) { return ClassNamePrefixImpl(classname, desc); } -std::string ClassNamePrefix(absl::string_view classname, +std::string ClassNamePrefix(const std::string& classname, const EnumDescriptor* desc) { return ClassNamePrefixImpl(classname, desc); } diff --git a/src/google/protobuf/compiler/php/names.h b/src/google/protobuf/compiler/php/names.h index 81785ec858..76220f8f2b 100644 --- a/src/google/protobuf/compiler/php/names.h +++ b/src/google/protobuf/compiler/php/names.h @@ -8,10 +8,11 @@ #ifndef GOOGLE_PROTOBUF_COMPILER_PHP_NAMES_H__ #define GOOGLE_PROTOBUF_COMPILER_PHP_NAMES_H__ +#include "google/protobuf/descriptor.h" + #include #include "absl/strings/string_view.h" -#include "google/protobuf/descriptor.h" #include "google/protobuf/port_def.inc" namespace google { @@ -23,13 +24,13 @@ namespace php { PROTOC_EXPORT bool IsReservedName(absl::string_view name); // A prefix to stick in front of reserved names to avoid clashes. -PROTOC_EXPORT std::string ReservedNamePrefix(absl::string_view classname, +PROTOC_EXPORT std::string ReservedNamePrefix(const std::string& classname, const FileDescriptor* file); // A prefix to stick in front of all class names. -PROTOC_EXPORT std::string ClassNamePrefix(absl::string_view classname, +PROTOC_EXPORT std::string ClassNamePrefix(const std::string& classname, const Descriptor* desc); -PROTOC_EXPORT std::string ClassNamePrefix(absl::string_view classname, +PROTOC_EXPORT std::string ClassNamePrefix(const std::string& classname, const EnumDescriptor* desc); // To skip reserved keywords in php, some generated classname are prefixed. diff --git a/src/google/protobuf/compiler/php/php_generator.cc b/src/google/protobuf/compiler/php/php_generator.cc index 02acebcf68..006d6debd5 100644 --- a/src/google/protobuf/compiler/php/php_generator.cc +++ b/src/google/protobuf/compiler/php/php_generator.cc @@ -494,7 +494,7 @@ void Outdent(io::Printer* printer) { printer->Outdent(); } -std::string BinaryToPhpString(absl::string_view src) { +std::string BinaryToPhpString(const std::string& src) { std::string dest; size_t i; unsigned char symbol[16] = { diff --git a/src/google/protobuf/compiler/python/pyi_generator.cc b/src/google/protobuf/compiler/python/pyi_generator.cc index e1843f3f9e..7f7bfeda08 100644 --- a/src/google/protobuf/compiler/python/pyi_generator.cc +++ b/src/google/protobuf/compiler/python/pyi_generator.cc @@ -71,7 +71,7 @@ struct ImportModules { }; // Checks whether a descriptor name matches a well-known type. -bool IsWellKnownType(absl::string_view name) { +bool IsWellKnownType(const std::string& name) { // LINT.IfChange(wktbases) return (name == "google.protobuf.Any" || name == "google.protobuf.Duration" || @@ -132,7 +132,7 @@ void CheckImportModules(const Descriptor* descriptor, void PyiGenerator::PrintImportForDescriptor( const FileDescriptor& desc, absl::flat_hash_set* seen_aliases, bool* has_importlib) const { - absl::string_view filename = desc.name(); + const std::string& filename = desc.name(); std::string module_name_owned = StrippedModuleName(filename); absl::string_view module_name(module_name_owned); size_t last_dot_pos = module_name.rfind('.'); @@ -282,9 +282,9 @@ printer_->Print("\n"); // Annotate wrapper for debugging purposes // Print a message after Annotate to see what is annotated. template -void PyiGenerator::Annotate(absl::string_view label, +void PyiGenerator::Annotate(const std::string& label, const DescriptorT* descriptor) const { - printer_->Annotate(label, descriptor); +printer_->Annotate(label.c_str(), descriptor); } void PyiGenerator::PrintEnum(const EnumDescriptor& enum_descriptor) const { diff --git a/src/google/protobuf/compiler/python/pyi_generator.h b/src/google/protobuf/compiler/python/pyi_generator.h index 9202acd14b..a015880b8e 100644 --- a/src/google/protobuf/compiler/python/pyi_generator.h +++ b/src/google/protobuf/compiler/python/pyi_generator.h @@ -17,7 +17,6 @@ #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" -#include "absl/strings/string_view.h" #include "absl/synchronization/mutex.h" #include "google/protobuf/compiler/code_generator.h" @@ -67,7 +66,7 @@ class PROTOC_EXPORT PyiGenerator : public google::protobuf::compiler::CodeGenera absl::flat_hash_set* seen_aliases, bool* has_importlib) const; template - void Annotate(absl::string_view label, const DescriptorT* descriptor) const; + void Annotate(const std::string& label, const DescriptorT* descriptor) const; void PrintImports() const; void PrintTopLevelEnums() const; void PrintEnum(const EnumDescriptor& enum_descriptor) const; diff --git a/src/google/protobuf/compiler/subprocess.cc b/src/google/protobuf/compiler/subprocess.cc index f7c4ee96c6..8162df2df5 100644 --- a/src/google/protobuf/compiler/subprocess.cc +++ b/src/google/protobuf/compiler/subprocess.cc @@ -24,7 +24,6 @@ #include "absl/log/absl_log.h" #include "absl/strings/escaping.h" #include "absl/strings/str_cat.h" -#include "absl/strings/string_view.h" #include "absl/strings/substitute.h" #include "google/protobuf/io/io_win32.h" #include "google/protobuf/message.h" @@ -57,7 +56,7 @@ Subprocess::~Subprocess() { } } -void Subprocess::Start(absl::string_view program, SearchMode search_mode) { +void Subprocess::Start(const std::string& program, SearchMode search_mode) { // Create the pipes. HANDLE stdin_pipe_read; HANDLE stdin_pipe_write; @@ -98,8 +97,7 @@ void Subprocess::Start(absl::string_view program, SearchMode search_mode) { // get wide string version of program as the path may contain non-ascii characters std::wstring wprogram; - if (!io::win32::strings::utf8_to_wcs(std::string(program).c_str(), - &wprogram)) { + if (!io::win32::strings::utf8_to_wcs(program.c_str(), &wprogram)) { ABSL_LOG(FATAL) << "utf8_to_wcs: " << Win32ErrorMessage(GetLastError()); } @@ -300,7 +298,7 @@ char* portable_strdup(const char* s) { } } // namespace -void Subprocess::Start(absl::string_view program, SearchMode search_mode) { +void Subprocess::Start(const std::string& program, SearchMode search_mode) { // Note that we assume that there are no other threads, thus we don't have to // do crazy stuff like using socket pairs or avoiding libc locks. @@ -311,7 +309,7 @@ void Subprocess::Start(absl::string_view program, SearchMode search_mode) { ABSL_CHECK(pipe(stdin_pipe) != -1); ABSL_CHECK(pipe(stdout_pipe) != -1); - char* argv[2] = {portable_strdup(std::string(program).c_str()), nullptr}; + char* argv[2] = {portable_strdup(program.c_str()), nullptr}; child_pid_ = fork(); if (child_pid_ == -1) { diff --git a/src/google/protobuf/compiler/subprocess.h b/src/google/protobuf/compiler/subprocess.h index 770d4c58fb..3a8e3e01db 100644 --- a/src/google/protobuf/compiler/subprocess.h +++ b/src/google/protobuf/compiler/subprocess.h @@ -21,7 +21,6 @@ #endif // !_WIN32 #include -#include "absl/strings/string_view.h" #include "google/protobuf/port.h" // Must be included last. @@ -47,7 +46,7 @@ class PROTOC_EXPORT Subprocess { // Start the subprocess. Currently we don't provide a way to specify // arguments as protoc plugins don't have any. - void Start(absl::string_view program, SearchMode search_mode); + void Start(const std::string& program, SearchMode search_mode); // Serialize the input message and pipe it to the subprocess's stdin, then // close the pipe. Meanwhile, read from the subprocess's stdout and parse diff --git a/src/google/protobuf/compiler/zip_writer.cc b/src/google/protobuf/compiler/zip_writer.cc index 92b3363e0e..8cbb9b7422 100644 --- a/src/google/protobuf/compiler/zip_writer.cc +++ b/src/google/protobuf/compiler/zip_writer.cc @@ -14,7 +14,6 @@ #include -#include "absl/strings/string_view.h" #include "google/protobuf/io/coded_stream.h" namespace google { @@ -70,7 +69,7 @@ static const uint32_t kCRC32Table[256] = { 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d}; -static uint32_t ComputeCRC32(absl::string_view buf) { +static uint32_t ComputeCRC32(const std::string& buf) { uint32_t x = ~0U; for (int i = 0; i < buf.size(); ++i) { unsigned char c = buf[i]; @@ -90,10 +89,11 @@ ZipWriter::ZipWriter(io::ZeroCopyOutputStream* raw_output) : raw_output_(raw_output) {} ZipWriter::~ZipWriter() {} -bool ZipWriter::Write(absl::string_view filename, absl::string_view contents) { +bool ZipWriter::Write(const std::string& filename, + const std::string& contents) { FileInfo info; - info.name = std::string(filename); + info.name = filename; uint16_t filename_size = filename.size(); info.offset = raw_output_->ByteCount(); info.size = contents.size(); @@ -127,7 +127,7 @@ bool ZipWriter::WriteDirectory() { // write central directory io::CodedOutputStream output(raw_output_); for (int i = 0; i < num_entries; ++i) { - absl::string_view filename = files_[i].name; + const std::string& filename = files_[i].name; uint16_t filename_size = filename.size(); uint32_t crc32 = files_[i].crc32; uint32_t size = files_[i].size; diff --git a/src/google/protobuf/compiler/zip_writer.h b/src/google/protobuf/compiler/zip_writer.h index 7665d1c9fe..0e8705b32a 100644 --- a/src/google/protobuf/compiler/zip_writer.h +++ b/src/google/protobuf/compiler/zip_writer.h @@ -13,7 +13,6 @@ #include #include "google/protobuf/stubs/common.h" -#include "absl/strings/string_view.h" #include "google/protobuf/io/zero_copy_stream.h" namespace google { @@ -25,7 +24,7 @@ class ZipWriter { ZipWriter(io::ZeroCopyOutputStream* raw_output); ~ZipWriter(); - bool Write(absl::string_view filename, absl::string_view contents); + bool Write(const std::string& filename, const std::string& contents); bool WriteDirectory(); private: diff --git a/src/google/protobuf/descriptor.cc b/src/google/protobuf/descriptor.cc index 07bf8d967d..1619d34daa 100644 --- a/src/google/protobuf/descriptor.cc +++ b/src/google/protobuf/descriptor.cc @@ -94,7 +94,7 @@ using ::google::protobuf::internal::DownCast; const int kPackageLimit = 100; -std::string ToCamelCase(absl::string_view input, bool lower_first) { +std::string ToCamelCase(const std::string& input, bool lower_first) { bool capitalize_next = !lower_first; std::string result; result.reserve(input.size()); @@ -118,7 +118,7 @@ std::string ToCamelCase(absl::string_view input, bool lower_first) { return result; } -std::string ToJsonName(absl::string_view input) { +std::string ToJsonName(const std::string& input) { bool capitalize_next = false; std::string result; result.reserve(input.size()); @@ -425,7 +425,7 @@ class FlatAllocatorImpl { // It will dedup the strings when possible. // The resulting array contains `name` at index 0, `full_name` at index 1 // and the other 3 indices are specified in the result. - void PlanFieldNames(absl::string_view name, + void PlanFieldNames(const std::string& name, const std::string* opt_json_name) { ABSL_CHECK(!has_allocated()); @@ -443,7 +443,7 @@ class FlatAllocatorImpl { } } - std::string lowercase_name = std::string(name); + std::string lowercase_name = name; absl::AsciiStrToLower(&lowercase_name); std::string camelcase_name = ToCamelCase(name, /* lower_first = */ true); @@ -465,13 +465,13 @@ class FlatAllocatorImpl { int camelcase_index; int json_index; }; - FieldNamesResult AllocateFieldNames(absl::string_view name, - absl::string_view scope, + FieldNamesResult AllocateFieldNames(const std::string& name, + const std::string& scope, const std::string* opt_json_name) { ABSL_CHECK(has_allocated()); std::string full_name = - scope.empty() ? std::string(name) : absl::StrCat(scope, ".", name); + scope.empty() ? name : absl::StrCat(scope, ".", name); // Fast path for snake_case names, which follow the style guide. if (opt_json_name == nullptr) { @@ -490,7 +490,7 @@ class FlatAllocatorImpl { } std::vector names; - names.push_back(std::string(name)); + names.push_back(name); names.push_back(std::move(full_name)); const auto push_name = [&](std::string new_name) { @@ -507,7 +507,7 @@ class FlatAllocatorImpl { FieldNamesResult result{nullptr, 0, 0, 0}; - std::string lowercase_name = std::string(name); + std::string lowercase_name = name; absl::AsciiStrToLower(&lowercase_name); result.lowercase_index = push_name(std::move(lowercase_name)); result.camelcase_index = @@ -547,8 +547,8 @@ class FlatAllocatorImpl { static bool IsLowerOrDigit(char c) { return IsLower(c) || IsDigit(c); } enum class FieldNameCase { kAllLower, kSnakeCase, kOther }; - FieldNameCase GetFieldNameCase(absl::string_view name) { - if (!name.empty() && !IsLower(name[0])) return FieldNameCase::kOther; + FieldNameCase GetFieldNameCase(const std::string& name) { + if (!IsLower(name[0])) return FieldNameCase::kOther; FieldNameCase best = FieldNameCase::kAllLower; for (char c : name) { if (IsLowerOrDigit(c)) { @@ -835,7 +835,7 @@ const int FieldDescriptor::kLastReservedNumber; namespace { -std::string EnumValueToPascalCase(absl::string_view input) { +std::string EnumValueToPascalCase(const std::string& input) { bool next_upper = true; std::string result; result.reserve(input.size()); @@ -1082,7 +1082,7 @@ absl::flat_hash_set* NewAllowedProto3Extendee() { // Only extensions to descriptor options are allowed. We use name comparison // instead of comparing the descriptor directly because the extensions may be // defined in a different pool. -bool AllowedExtendeeInProto3(absl::string_view name) { +bool AllowedExtendeeInProto3(const std::string& name) { static auto allowed_proto3_extendees = internal::OnShutdownDelete(NewAllowedProto3Extendee()); return allowed_proto3_extendees->find(name) != @@ -3257,7 +3257,7 @@ bool FormatLineOptions(int depth, const Message& options, std::string prefix(depth * 2, ' '); std::vector all_options; if (RetrieveOptions(depth, options, pool, &all_options)) { - for (absl::string_view option : all_options) { + for (const std::string& option : all_options) { absl::SubstituteAndAppend(output, "$0option $1;\n", prefix, option); } } @@ -3275,7 +3275,7 @@ static std::string GetLegacySyntaxName(Edition edition) { class SourceLocationCommentPrinter { public: template - SourceLocationCommentPrinter(const DescType* desc, absl::string_view prefix, + SourceLocationCommentPrinter(const DescType* desc, const std::string& prefix, const DebugStringOptions& options) : options_(options), prefix_(prefix) { // Perform the SourceLocation lookup only if we're including user comments, @@ -3285,7 +3285,7 @@ class SourceLocationCommentPrinter { } SourceLocationCommentPrinter(const FileDescriptor* file, const std::vector& path, - absl::string_view prefix, + const std::string& prefix, const DebugStringOptions& options) : options_(options), prefix_(prefix) { // Perform the SourceLocation lookup only if we're including user comments, @@ -3296,7 +3296,7 @@ class SourceLocationCommentPrinter { void AddPreComment(std::string* output) { if (have_source_loc_) { // Detached leading comments. - for (absl::string_view leading_detached_comment : + for (const std::string& leading_detached_comment : source_loc_.leading_detached_comments) { absl::StrAppend(output, FormatComment(leading_detached_comment), "\n"); } @@ -3314,9 +3314,9 @@ class SourceLocationCommentPrinter { // Format comment such that each line becomes a full-line C++-style comment in // the DebugString() output. - std::string FormatComment(absl::string_view comment_text) { - absl::string_view stripped_comment = - absl::StripAsciiWhitespace(comment_text); + std::string FormatComment(const std::string& comment_text) { + std::string stripped_comment = comment_text; + absl::StripAsciiWhitespace(&stripped_comment); std::string output; for (absl::string_view line : absl::StrSplit(stripped_comment, '\n')) { absl::SubstituteAndAppend(&output, "$0// $1\n", prefix_, line); @@ -4219,10 +4219,10 @@ class DescriptorBuilder { // The `const char*` overload should only be used for string literal messages // where this is a frustrating amount of overhead and there is no harm in // directly using the literal. - void AddError(absl::string_view element_name, const Message& descriptor, + void AddError(const std::string& element_name, const Message& descriptor, DescriptorPool::ErrorCollector::ErrorLocation location, absl::FunctionRef make_error); - void AddError(absl::string_view element_name, const Message& descriptor, + void AddError(const std::string& element_name, const Message& descriptor, DescriptorPool::ErrorCollector::ErrorLocation location, const char* error); void AddRecursiveImportError(const FileDescriptorProto& proto, int from_here); @@ -4232,14 +4232,14 @@ class DescriptorBuilder { // Adds an error indicating that undefined_symbol was not defined. Must // only be called after LookupSymbol() fails. void AddNotDefinedError( - absl::string_view element_name, const Message& descriptor, + const std::string& element_name, const Message& descriptor, DescriptorPool::ErrorCollector::ErrorLocation location, - absl::string_view undefined_symbol); + const std::string& undefined_symbol); - void AddWarning(absl::string_view element_name, const Message& descriptor, + void AddWarning(const std::string& element_name, const Message& descriptor, DescriptorPool::ErrorCollector::ErrorLocation location, absl::FunctionRef make_error); - void AddWarning(absl::string_view element_name, const Message& descriptor, + void AddWarning(const std::string& element_name, const Message& descriptor, DescriptorPool::ErrorCollector::ErrorLocation location, const char* error); @@ -4256,16 +4256,16 @@ class DescriptorBuilder { // - Search the pool's underlay if not found in tables_. // - Insure that the resulting Symbol is from one of the file's declared // dependencies. - Symbol FindSymbol(absl::string_view name, bool build_it = true); + Symbol FindSymbol(const std::string& name, bool build_it = true); // Like FindSymbol() but does not require that the symbol is in one of the // file's declared dependencies. - Symbol FindSymbolNotEnforcingDeps(absl::string_view name, + Symbol FindSymbolNotEnforcingDeps(const std::string& name, bool build_it = true); // This implements the body of FindSymbolNotEnforcingDeps(). Symbol FindSymbolNotEnforcingDepsHelper(const DescriptorPool* pool, - absl::string_view name, + const std::string& name, bool build_it = true); // Like FindSymbol(), but looks up the name relative to some other symbol @@ -4283,7 +4283,7 @@ class DescriptorBuilder { // if it believes that's all it could refer to. The caller should always // check that it receives the type of symbol it was expecting. enum ResolveMode { LOOKUP_ALL, LOOKUP_TYPES }; - Symbol LookupSymbol(absl::string_view name, absl::string_view relative_to, + Symbol LookupSymbol(const std::string& name, const std::string& relative_to, DescriptorPool::PlaceholderType placeholder_type = DescriptorPool::PLACEHOLDER_MESSAGE, ResolveMode resolve_mode = LOOKUP_ALL, @@ -4291,28 +4291,28 @@ class DescriptorBuilder { // Like LookupSymbol() but will not return a placeholder even if // AllowUnknownDependencies() has been used. - Symbol LookupSymbolNoPlaceholder(absl::string_view name, - absl::string_view relative_to, + Symbol LookupSymbolNoPlaceholder(const std::string& name, + const std::string& relative_to, ResolveMode resolve_mode = LOOKUP_ALL, bool build_it = true); // Calls tables_->AddSymbol() and records an error if it fails. Returns // true if successful or false if failed, though most callers can ignore // the return value since an error has already been recorded. - bool AddSymbol(absl::string_view full_name, const void* parent, - absl::string_view name, const Message& proto, Symbol symbol); + bool AddSymbol(const std::string& full_name, const void* parent, + const std::string& name, const Message& proto, Symbol symbol); // Like AddSymbol(), but succeeds if the symbol is already defined as long // as the existing definition is also a package (because it's OK to define // the same package in two different files). Also adds all parents of the // package to the symbol table (e.g. AddPackage("foo.bar", ...) will add // "foo.bar" and "foo" to the table). - void AddPackage(absl::string_view name, const Message& proto, - FileDescriptor* file, bool top_level); + void AddPackage(const std::string& name, const Message& proto, + FileDescriptor* file); // Checks that the symbol name contains only alphanumeric characters and // underscores. Records an error otherwise. - void ValidateSymbolName(absl::string_view name, absl::string_view full_name, + void ValidateSymbolName(const std::string& name, const std::string& full_name, const Message& proto); // Allocates a copy of orig_options in tables_ and stores it in the @@ -4365,8 +4365,8 @@ class DescriptorBuilder { // Allocates an array of two strings, the first one is a copy of // `proto_name`, and the second one is the full name. Full proto name is // "scope.proto_name" if scope is non-empty and "proto_name" otherwise. - const std::string* AllocateNameStrings(absl::string_view scope, - absl::string_view proto_name, + const std::string* AllocateNameStrings(const std::string& scope, + const std::string& proto_name, internal::FlatAllocator& alloc); // These methods all have the same signature for the sake of the BUILD_ARRAY @@ -4411,7 +4411,7 @@ class DescriptorBuilder { void CheckFieldJsonNameUniqueness(const DescriptorProto& proto, const Descriptor* result); - void CheckFieldJsonNameUniqueness(absl::string_view message_name, + void CheckFieldJsonNameUniqueness(const std::string& message_name, const DescriptorProto& message, const Descriptor* descriptor, bool use_custom_names); @@ -4510,7 +4510,7 @@ class DescriptorBuilder { std::vector::const_iterator intermediate_fields_end, const FieldDescriptor* innermost_field, - absl::string_view debug_msg_name, + const std::string& debug_msg_name, const UnknownFieldSet& unknown_fields); // Validates the value for the option field of the currently interpreted @@ -4641,7 +4641,7 @@ class DescriptorBuilder { void ValidateExtensionRangeOptions(const DescriptorProto& proto, const Descriptor& message); void ValidateExtensionDeclaration( - absl::string_view full_name, + const std::string& full_name, const RepeatedPtrField& declarations, const DescriptorProto_ExtensionRange& proto, absl::flat_hash_set& full_name_set); @@ -4780,7 +4780,7 @@ DescriptorBuilder::DescriptorBuilder( DescriptorBuilder::~DescriptorBuilder() = default; PROTOBUF_NOINLINE void DescriptorBuilder::AddError( - absl::string_view element_name, const Message& descriptor, + const std::string& element_name, const Message& descriptor, DescriptorPool::ErrorCollector::ErrorLocation location, absl::FunctionRef make_error) { std::string error = make_error(); @@ -4798,15 +4798,15 @@ PROTOBUF_NOINLINE void DescriptorBuilder::AddError( } PROTOBUF_NOINLINE void DescriptorBuilder::AddError( - absl::string_view element_name, const Message& descriptor, + const std::string& element_name, const Message& descriptor, DescriptorPool::ErrorCollector::ErrorLocation location, const char* error) { AddError(element_name, descriptor, location, [error] { return error; }); } PROTOBUF_NOINLINE void DescriptorBuilder::AddNotDefinedError( - absl::string_view element_name, const Message& descriptor, + const std::string& element_name, const Message& descriptor, DescriptorPool::ErrorCollector::ErrorLocation location, - absl::string_view undefined_symbol) { + const std::string& undefined_symbol) { if (possible_undeclared_dependency_ == nullptr && undefine_resolved_name_.empty()) { AddError(element_name, descriptor, location, [&] { @@ -4840,7 +4840,7 @@ PROTOBUF_NOINLINE void DescriptorBuilder::AddNotDefinedError( } PROTOBUF_NOINLINE void DescriptorBuilder::AddWarning( - absl::string_view element_name, const Message& descriptor, + const std::string& element_name, const Message& descriptor, DescriptorPool::ErrorCollector::ErrorLocation location, absl::FunctionRef make_error) { std::string error = make_error(); @@ -4853,7 +4853,7 @@ PROTOBUF_NOINLINE void DescriptorBuilder::AddWarning( } PROTOBUF_NOINLINE void DescriptorBuilder::AddWarning( - absl::string_view element_name, const Message& descriptor, + const std::string& element_name, const Message& descriptor, DescriptorPool::ErrorCollector::ErrorLocation location, const char* error) { AddWarning(element_name, descriptor, location, [error]() -> std::string { return error; }); @@ -4874,7 +4874,7 @@ void DescriptorBuilder::RecordPublicDependencies(const FileDescriptor* file) { } Symbol DescriptorBuilder::FindSymbolNotEnforcingDepsHelper( - const DescriptorPool* pool, absl::string_view name, bool build_it) { + const DescriptorPool* pool, const std::string& name, bool build_it) { // If we are looking at an underlay, we must lock its mutex_, since we are // accessing the underlay's tables_ directly. absl::MutexLockMaybe lock((pool == pool_) ? nullptr : pool->mutex_); @@ -4902,7 +4902,7 @@ Symbol DescriptorBuilder::FindSymbolNotEnforcingDepsHelper( return result; } -Symbol DescriptorBuilder::FindSymbolNotEnforcingDeps(absl::string_view name, +Symbol DescriptorBuilder::FindSymbolNotEnforcingDeps(const std::string& name, bool build_it) { Symbol result = FindSymbolNotEnforcingDepsHelper(pool_, name, build_it); // Only find symbols which were defined in this file or one of its @@ -4914,7 +4914,7 @@ Symbol DescriptorBuilder::FindSymbolNotEnforcingDeps(absl::string_view name, return result; } -Symbol DescriptorBuilder::FindSymbol(absl::string_view name, bool build_it) { +Symbol DescriptorBuilder::FindSymbol(const std::string& name, bool build_it) { Symbol result = FindSymbolNotEnforcingDeps(name, build_it); if (result.IsNull()) return result; @@ -4947,12 +4947,12 @@ Symbol DescriptorBuilder::FindSymbol(absl::string_view name, bool build_it) { } possible_undeclared_dependency_ = file; - possible_undeclared_dependency_name_ = std::string(name); + possible_undeclared_dependency_name_ = name; return Symbol(); } Symbol DescriptorBuilder::LookupSymbolNoPlaceholder( - absl::string_view name, absl::string_view relative_to, + const std::string& name, const std::string& relative_to, ResolveMode resolve_mode, bool build_it) { possible_undeclared_dependency_ = nullptr; undefine_resolved_name_.clear(); @@ -4973,9 +4973,9 @@ Symbol DescriptorBuilder::LookupSymbolNoPlaceholder( // } // So, we look for just "Foo" first, then look for "Bar.baz" within it if // found. - auto name_dot_pos = name.find_first_of('.'); - absl::string_view first_part_of_name; - if (name_dot_pos == name.npos) { + std::string::size_type name_dot_pos = name.find_first_of('.'); + std::string first_part_of_name; + if (name_dot_pos == std::string::npos) { first_part_of_name = name; } else { first_part_of_name = name.substr(0, name_dot_pos); @@ -4995,14 +4995,14 @@ Symbol DescriptorBuilder::LookupSymbolNoPlaceholder( // Append ".first_part_of_name" and try to find. std::string::size_type old_size = scope_to_try.size(); scope_to_try.append(1, '.'); - scope_to_try.append(std::string(first_part_of_name)); + scope_to_try.append(first_part_of_name); Symbol result = FindSymbol(scope_to_try, build_it); if (!result.IsNull()) { if (first_part_of_name.size() < name.size()) { // name is a compound symbol, of which we only found the first part. // Now try to look up the rest of it. if (result.IsAggregate()) { - scope_to_try.append(std::string(name), first_part_of_name.size(), + scope_to_try.append(name, first_part_of_name.size(), name.size() - first_part_of_name.size()); result = FindSymbol(scope_to_try, build_it); if (result.IsNull()) { @@ -5027,7 +5027,7 @@ Symbol DescriptorBuilder::LookupSymbolNoPlaceholder( } Symbol DescriptorBuilder::LookupSymbol( - absl::string_view name, absl::string_view relative_to, + const std::string& name, const std::string& relative_to, DescriptorPool::PlaceholderType placeholder_type, ResolveMode resolve_mode, bool build_it) { Symbol result = @@ -5224,8 +5224,8 @@ FileDescriptor* DescriptorPool::NewPlaceholderFileWithMutexHeld( return placeholder; } -bool DescriptorBuilder::AddSymbol(absl::string_view full_name, - const void* parent, absl::string_view name, +bool DescriptorBuilder::AddSymbol(const std::string& full_name, + const void* parent, const std::string& name, const Message& proto, Symbol symbol) { // If the caller passed nullptr for the parent, the symbol is at file scope. // Use its file as the parent instead. @@ -5253,8 +5253,8 @@ bool DescriptorBuilder::AddSymbol(absl::string_view full_name, } else { const FileDescriptor* other_file = tables_->FindSymbol(full_name).GetFile(); if (other_file == file_) { - auto dot_pos = full_name.find_last_of('.'); - if (dot_pos == full_name.npos) { + std::string::size_type dot_pos = full_name.find_last_of('.'); + if (dot_pos == std::string::npos) { AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, [&] { return absl::StrCat("\"", full_name, "\" is already defined."); }); @@ -5277,8 +5277,8 @@ bool DescriptorBuilder::AddSymbol(absl::string_view full_name, } } -void DescriptorBuilder::AddPackage(absl::string_view name, const Message& proto, - FileDescriptor* file, bool top_level) { +void DescriptorBuilder::AddPackage(const std::string& name, + const Message& proto, FileDescriptor* file) { if (absl::StrContains(name, '\0')) { AddError(name, proto, DescriptorPool::ErrorCollector::NAME, [&] { return absl::StrCat("\"", name, "\" contains null character."); @@ -5289,8 +5289,7 @@ void DescriptorBuilder::AddPackage(absl::string_view name, const Message& proto, Symbol existing_symbol = tables_->FindSymbol(name); // It's OK to redefine a package. if (existing_symbol.IsNull()) { - if (top_level) { - ABSL_DCHECK_EQ(name, file->package()); + if (name.data() == file->package().data()) { // It is the toplevel package name, so insert the descriptor directly. tables_->AddSymbol(file->package(), Symbol(file)); } else { @@ -5302,13 +5301,13 @@ void DescriptorBuilder::AddPackage(absl::string_view name, const Message& proto, tables_->AddSymbol(name, Symbol(package)); } // Also add parent package, if any. - auto dot_pos = name.find_last_of('.'); - if (dot_pos == name.npos) { + std::string::size_type dot_pos = name.find_last_of('.'); + if (dot_pos == std::string::npos) { // No parents. ValidateSymbolName(name, name, proto); } else { // Has parent. - AddPackage(name.substr(0, dot_pos), proto, file, false); + AddPackage(name.substr(0, dot_pos), proto, file); ValidateSymbolName(name.substr(dot_pos + 1), name, proto); } } else if (!existing_symbol.IsPackage()) { @@ -5324,8 +5323,8 @@ void DescriptorBuilder::AddPackage(absl::string_view name, const Message& proto, } } -void DescriptorBuilder::ValidateSymbolName(absl::string_view name, - absl::string_view full_name, +void DescriptorBuilder::ValidateSymbolName(const std::string& name, + const std::string& full_name, const Message& proto) { if (name.empty()) { AddError(full_name, proto, DescriptorPool::ErrorCollector::NAME, @@ -5950,7 +5949,7 @@ FileDescriptor* DescriptorBuilder::BuildFileImpl( "Exceeds Maximum Package Depth"); return nullptr; } - AddPackage(result->package(), proto, result, true); + AddPackage(result->package(), proto, result); } // Make sure all dependencies are loaded. @@ -6226,7 +6225,7 @@ FileDescriptor* DescriptorBuilder::BuildFileImpl( const std::string* DescriptorBuilder::AllocateNameStrings( - absl::string_view scope, absl::string_view proto_name, + const std::string& scope, const std::string& proto_name, internal::FlatAllocator& alloc) { if (scope.empty()) { return alloc.AllocateStrings(proto_name, proto_name); @@ -6262,7 +6261,7 @@ void DescriptorBuilder::BuildMessage(const DescriptorProto& proto, const Descriptor* parent, Descriptor* result, internal::FlatAllocator& alloc) { - absl::string_view scope = + const std::string& scope = (parent == nullptr) ? file_->package() : parent->full_name(); result->all_names_ = AllocateNameStrings(scope, proto.name(), alloc); ValidateSymbolName(proto.name(), result->full_name(), proto); @@ -6345,7 +6344,7 @@ void DescriptorBuilder::BuildMessage(const DescriptorProto& proto, } absl::flat_hash_set reserved_name_set; - for (absl::string_view name : proto.reserved_name()) { + for (const std::string& name : proto.reserved_name()) { if (!reserved_name_set.insert(name).second) { AddError(name, proto, DescriptorPool::ErrorCollector::NAME, [&] { return absl::Substitute("Field name \"$0\" is reserved multiple times.", @@ -6467,7 +6466,7 @@ bool JsonNameLooksLikeExtension(std::string name) { } // namespace void DescriptorBuilder::CheckFieldJsonNameUniqueness( - absl::string_view message_name, const DescriptorProto& message, + const std::string& message_name, const DescriptorProto& message, const Descriptor* descriptor, bool use_custom_names) { absl::flat_hash_map name_to_field; for (const FieldDescriptorProto& field : message.field()) { @@ -6531,7 +6530,7 @@ void DescriptorBuilder::BuildFieldOrExtension(const FieldDescriptorProto& proto, FieldDescriptor* result, bool is_extension, internal::FlatAllocator& alloc) { - absl::string_view scope = + const std::string& scope = (parent == nullptr) ? file_->package() : parent->full_name(); // We allocate all names in a single array, and dedup them. @@ -6967,7 +6966,7 @@ void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto, const Descriptor* parent, EnumDescriptor* result, internal::FlatAllocator& alloc) { - absl::string_view scope = + const std::string& scope = (parent == nullptr) ? file_->package() : parent->full_name(); result->all_names_ = AllocateNameStrings(scope, proto.name(), alloc); @@ -7037,7 +7036,7 @@ void DescriptorBuilder::BuildEnum(const EnumDescriptorProto& proto, } absl::flat_hash_set reserved_name_set; - for (absl::string_view name : proto.reserved_name()) { + for (const std::string& name : proto.reserved_name()) { if (!reserved_name_set.insert(name).second) { AddError(name, proto, DescriptorPool::ErrorCollector::NAME, [&] { return absl::Substitute("Enum value \"$0\" is reserved multiple times.", @@ -7454,7 +7453,7 @@ void DescriptorBuilder::CrossLinkField(FieldDescriptor* field, << proto; // Save the symbol names for later for lookup, and allocate the once // object needed for the accessors. - absl::string_view name = proto.type_name(); + const std::string& name = proto.type_name(); int name_sizes = static_cast(name.size() + 1 + proto.default_value().size() + 1); @@ -7464,8 +7463,7 @@ void DescriptorBuilder::CrossLinkField(FieldDescriptor* field, absl::once_flag{}; char* names = reinterpret_cast(field->type_once_ + 1); - memcpy(names, name.data(), name.size()); - names[name.size()] = 0; + memcpy(names, name.c_str(), name.size() + 1); memcpy(names + name.size() + 1, proto.default_value().c_str(), proto.default_value().size() + 1); @@ -8286,7 +8284,7 @@ absl::optional ValidateSymbolForDeclaration( void DescriptorBuilder::ValidateExtensionDeclaration( - absl::string_view full_name, + const std::string& full_name, const RepeatedPtrField& declarations, const DescriptorProto_ExtensionRange& proto, absl::flat_hash_set& full_name_set) { @@ -8766,7 +8764,7 @@ bool DescriptorBuilder::OptionInterpreter::InterpretSingleOption( for (int i = 0; i < uninterpreted_option_->name_size(); ++i) { builder_->undefine_resolved_name_.clear(); - absl::string_view name_part = uninterpreted_option_->name(i).name_part(); + const std::string& name_part = uninterpreted_option_->name(i).name_part(); if (!debug_msg_name.empty()) { absl::StrAppend(&debug_msg_name, "."); } @@ -9049,7 +9047,7 @@ bool DescriptorBuilder::OptionInterpreter::ExamineIfOptionIsSet( std::vector::const_iterator intermediate_fields_iter, std::vector::const_iterator intermediate_fields_end, - const FieldDescriptor* innermost_field, absl::string_view debug_msg_name, + const FieldDescriptor* innermost_field, const std::string& debug_msg_name, const UnknownFieldSet& unknown_fields) { // We do linear searches of the UnknownFieldSet and its sub-groups. This // should be fine since it's unlikely that any one options structure will @@ -9296,7 +9294,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( }); } const EnumDescriptor* enum_type = option_field->enum_type(); - absl::string_view value_name = uninterpreted_option_->identifier_value(); + const std::string& value_name = uninterpreted_option_->identifier_value(); const EnumValueDescriptor* enum_value = nullptr; if (enum_type->file()->pool() != DescriptorPool::generated_pool()) { @@ -9305,7 +9303,7 @@ bool DescriptorBuilder::OptionInterpreter::SetOptionValue( std::string fully_qualified_name = enum_type->full_name(); fully_qualified_name.resize(fully_qualified_name.size() - enum_type->name().size()); - absl::StrAppend(&fully_qualified_name, value_name); + fully_qualified_name += value_name; // Search for the enum value's descriptor in the builder's pool. Note // that we use DescriptorBuilder::FindSymbolNotEnforcingDeps(), not diff --git a/src/google/protobuf/io/coded_stream.cc b/src/google/protobuf/io/coded_stream.cc index 34b9fa10fe..a9297e116f 100644 --- a/src/google/protobuf/io/coded_stream.cc +++ b/src/google/protobuf/io/coded_stream.cc @@ -962,17 +962,17 @@ uint8_t* EpsCopyOutputStream::WriteCord(const absl::Cord& cord, uint8_t* ptr) { } } -uint8_t* EpsCopyOutputStream::WriteStringMaybeAliasedOutline( - uint32_t num, absl::string_view s, uint8_t* ptr) { +uint8_t* EpsCopyOutputStream::WriteStringMaybeAliasedOutline(uint32_t num, + const std::string& s, + uint8_t* ptr) { ptr = EnsureSpace(ptr); uint32_t size = s.size(); ptr = WriteLengthDelim(num, size, ptr); return WriteRawMaybeAliased(s.data(), size, ptr); } -uint8_t* EpsCopyOutputStream::WriteStringOutline(uint32_t num, - const std::string& s, - uint8_t* ptr) { +uint8_t* EpsCopyOutputStream::WriteStringOutline(uint32_t num, const std::string& s, + uint8_t* ptr) { ptr = EnsureSpace(ptr); uint32_t size = s.size(); ptr = WriteLengthDelim(num, size, ptr); @@ -1004,8 +1004,8 @@ uint8_t* CodedOutputStream::WriteCordToArray(const absl::Cord& cord, } -uint8_t* CodedOutputStream::WriteStringWithSizeToArray(absl::string_view str, - uint8_t* target) { +uint8_t* CodedOutputStream::WriteStringWithSizeToArray(const std::string& str, + uint8_t* target) { ABSL_DCHECK_LE(str.size(), std::numeric_limits::max()); target = WriteVarint32ToArray(str.size(), target); return WriteStringToArray(str, target); diff --git a/src/google/protobuf/io/coded_stream.h b/src/google/protobuf/io/coded_stream.h index de2a333f5c..4a5ca80cf8 100644 --- a/src/google/protobuf/io/coded_stream.h +++ b/src/google/protobuf/io/coded_stream.h @@ -689,7 +689,7 @@ class PROTOBUF_EXPORT EpsCopyOutputStream { #ifndef NDEBUG PROTOBUF_NOINLINE #endif - uint8_t* WriteStringMaybeAliased(uint32_t num, absl::string_view s, + uint8_t* WriteStringMaybeAliased(uint32_t num, const std::string& s, uint8_t* ptr) { std::ptrdiff_t size = s.size(); if (PROTOBUF_PREDICT_FALSE( @@ -701,7 +701,7 @@ class PROTOBUF_EXPORT EpsCopyOutputStream { std::memcpy(ptr, s.data(), size); return ptr + size; } - uint8_t* WriteBytesMaybeAliased(uint32_t num, absl::string_view s, + uint8_t* WriteBytesMaybeAliased(uint32_t num, const std::string& s, uint8_t* ptr) { return WriteStringMaybeAliased(num, s, ptr); } @@ -860,7 +860,7 @@ class PROTOBUF_EXPORT EpsCopyOutputStream { uint8_t* WriteAliasedRaw(const void* data, int size, uint8_t* ptr); - uint8_t* WriteStringMaybeAliasedOutline(uint32_t num, absl::string_view s, + uint8_t* WriteStringMaybeAliasedOutline(uint32_t num, const std::string& s, uint8_t* ptr); uint8_t* WriteStringOutline(uint32_t num, const std::string& s, uint8_t* ptr); uint8_t* WriteStringOutline(uint32_t num, absl::string_view s, uint8_t* ptr); @@ -1113,11 +1113,11 @@ class PROTOBUF_EXPORT CodedOutputStream { uint8_t* target); // Equivalent to WriteRaw(str.data(), str.size()). - void WriteString(absl::string_view str); + void WriteString(const std::string& str); // Like WriteString() but writing directly to the target array. - static uint8_t* WriteStringToArray(absl::string_view str, uint8_t* target); + static uint8_t* WriteStringToArray(const std::string& str, uint8_t* target); // Write the varint-encoded size of str followed by str. - static uint8_t* WriteStringWithSizeToArray(absl::string_view str, + static uint8_t* WriteStringWithSizeToArray(const std::string& str, uint8_t* target); // Like WriteString() but writes a Cord. @@ -1778,7 +1778,7 @@ inline size_t CodedOutputStream::VarintSize32SignExtendedPlusOne( } #undef PROTOBUF_CODED_STREAM_H_PREFER_BSR -inline void CodedOutputStream::WriteString(absl::string_view str) { +inline void CodedOutputStream::WriteString(const std::string& str) { WriteRaw(str.data(), static_cast(str.size())); } @@ -1793,7 +1793,7 @@ inline uint8_t* CodedOutputStream::WriteRawToArray(const void* data, int size, return target + size; } -inline uint8_t* CodedOutputStream::WriteStringToArray(absl::string_view str, +inline uint8_t* CodedOutputStream::WriteStringToArray(const std::string& str, uint8_t* target) { return WriteRawToArray(str.data(), static_cast(str.size()), target); } diff --git a/src/google/protobuf/json/internal/descriptor_traits.h b/src/google/protobuf/json/internal/descriptor_traits.h index 838ed9ebc2..609a956d5e 100644 --- a/src/google/protobuf/json/internal/descriptor_traits.h +++ b/src/google/protobuf/json/internal/descriptor_traits.h @@ -296,7 +296,7 @@ struct Proto2Descriptor { // Like WithFieldType, but using dynamic lookup by type URL. template static absl::Status WithDynamicType(const Desc& desc, - absl::string_view type_url, F body) { + const std::string& type_url, F body) { size_t slash = type_url.rfind('/'); if (slash == absl::string_view::npos || slash == 0) { return absl::InvalidArgumentError(absl::StrCat( @@ -498,7 +498,7 @@ struct Proto3Type { template static absl::Status WithDynamicType(const Desc& desc, - absl::string_view type_url, F body) { + const std::string& type_url, F body) { auto dyn_desc = desc.pool()->FindMessage(type_url); RETURN_IF_ERROR(dyn_desc.status()); return body(**dyn_desc); diff --git a/src/google/protobuf/json/internal/parser.cc b/src/google/protobuf/json/internal/parser.cc index c97cfc20a0..ae4954d75e 100644 --- a/src/google/protobuf/json/internal/parser.cc +++ b/src/google/protobuf/json/internal/parser.cc @@ -1297,7 +1297,7 @@ absl::Status JsonStringToMessage(absl::string_view input, Message* message, } absl::Status JsonToBinaryStream(google::protobuf::util::TypeResolver* resolver, - absl::string_view type_url, + const std::string& type_url, io::ZeroCopyInputStream* json_input, io::ZeroCopyOutputStream* binary_output, json_internal::ParseOptions options) { @@ -1360,5 +1360,3 @@ absl::Status JsonToBinaryStream(google::protobuf::util::TypeResolver* resolver, } // namespace json_internal } // namespace protobuf } // namespace google - -#include "google/protobuf/port_undef.inc" diff --git a/src/google/protobuf/json/internal/parser.h b/src/google/protobuf/json/internal/parser.h index f502859f48..a8a43b28bf 100644 --- a/src/google/protobuf/json/internal/parser.h +++ b/src/google/protobuf/json/internal/parser.h @@ -25,7 +25,7 @@ absl::Status JsonStringToMessage(absl::string_view input, Message* message, // Internal version of google::protobuf::util::JsonToBinaryStream; see json_util.h for // details. absl::Status JsonToBinaryStream(google::protobuf::util::TypeResolver* resolver, - absl::string_view type_url, + const std::string& type_url, io::ZeroCopyInputStream* json_input, io::ZeroCopyOutputStream* binary_output, json_internal::ParseOptions options); diff --git a/src/google/protobuf/json/internal/parser_traits.h b/src/google/protobuf/json/internal/parser_traits.h index 97c1ae63be..9d2745b1a2 100644 --- a/src/google/protobuf/json/internal/parser_traits.h +++ b/src/google/protobuf/json/internal/parser_traits.h @@ -117,7 +117,7 @@ struct ParseProto2Descriptor : Proto2Descriptor { // // Body should have a signature `absl::Status(const Desc&, Msg&)`. template - static absl::Status NewDynamic(Field f, absl::string_view type_url, Msg& msg, + static absl::Status NewDynamic(Field f, const std::string& type_url, Msg& msg, F body) { RecordAsSeen(f, msg); return WithDynamicType( @@ -263,7 +263,7 @@ struct ParseProto3Type : Proto3Type { } template - static absl::Status NewDynamic(Field f, absl::string_view type_url, Msg& msg, + static absl::Status NewDynamic(Field f, const std::string& type_url, Msg& msg, F body) { RecordAsSeen(f, msg); return WithDynamicType( diff --git a/src/google/protobuf/json/internal/unparser.cc b/src/google/protobuf/json/internal/unparser.cc index d66e2d0e97..33e4505d13 100644 --- a/src/google/protobuf/json/internal/unparser.cc +++ b/src/google/protobuf/json/internal/unparser.cc @@ -846,7 +846,7 @@ absl::Status MessageToJsonString(const Message& message, std::string* output, } absl::Status BinaryToJsonStream(google::protobuf::util::TypeResolver* resolver, - absl::string_view type_url, + const std::string& type_url, io::ZeroCopyInputStream* binary_input, io::ZeroCopyOutputStream* json_output, json_internal::WriterOptions options) { @@ -905,5 +905,3 @@ absl::Status BinaryToJsonStream(google::protobuf::util::TypeResolver* resolver, } // namespace json_internal } // namespace protobuf } // namespace google - -#include "google/protobuf/port_undef.inc" diff --git a/src/google/protobuf/json/internal/unparser.h b/src/google/protobuf/json/internal/unparser.h index 07b0ace588..5353d7181e 100644 --- a/src/google/protobuf/json/internal/unparser.h +++ b/src/google/protobuf/json/internal/unparser.h @@ -25,7 +25,7 @@ absl::Status MessageToJsonString(const Message& message, std::string* output, // Internal version of google::protobuf::util::BinaryToJsonStream; see json_util.h for // details. absl::Status BinaryToJsonStream(google::protobuf::util::TypeResolver* resolver, - absl::string_view type_url, + const std::string& type_url, io::ZeroCopyInputStream* binary_input, io::ZeroCopyOutputStream* json_output, json_internal::WriterOptions options); diff --git a/src/google/protobuf/json/json.cc b/src/google/protobuf/json/json.cc index c392c7a70a..cd8743d151 100644 --- a/src/google/protobuf/json/json.cc +++ b/src/google/protobuf/json/json.cc @@ -25,7 +25,7 @@ namespace protobuf { namespace json { absl::Status BinaryToJsonStream(google::protobuf::util::TypeResolver* resolver, - absl::string_view type_url, + const std::string& type_url, io::ZeroCopyInputStream* binary_input, io::ZeroCopyOutputStream* json_output, const PrintOptions& options) { @@ -45,8 +45,8 @@ absl::Status BinaryToJsonStream(google::protobuf::util::TypeResolver* resolver, } absl::Status BinaryToJsonString(google::protobuf::util::TypeResolver* resolver, - absl::string_view type_url, - absl::string_view binary_input, + const std::string& type_url, + const std::string& binary_input, std::string* json_output, const PrintOptions& options) { io::ArrayInputStream input_stream(binary_input.data(), binary_input.size()); @@ -56,7 +56,7 @@ absl::Status BinaryToJsonString(google::protobuf::util::TypeResolver* resolver, } absl::Status JsonToBinaryStream(google::protobuf::util::TypeResolver* resolver, - absl::string_view type_url, + const std::string& type_url, io::ZeroCopyInputStream* json_input, io::ZeroCopyOutputStream* binary_output, const ParseOptions& options) { @@ -72,7 +72,7 @@ absl::Status JsonToBinaryStream(google::protobuf::util::TypeResolver* resolver, } absl::Status JsonToBinaryString(google::protobuf::util::TypeResolver* resolver, - absl::string_view type_url, + const std::string& type_url, absl::string_view json_input, std::string* binary_output, const ParseOptions& options) { @@ -112,5 +112,3 @@ absl::Status JsonStringToMessage(absl::string_view input, Message* message, } // namespace json } // namespace protobuf } // namespace google - -#include "google/protobuf/port_undef.inc" diff --git a/src/google/protobuf/json/json.h b/src/google/protobuf/json/json.h index 432d9270ec..c025a2a5a8 100644 --- a/src/google/protobuf/json/json.h +++ b/src/google/protobuf/json/json.h @@ -94,12 +94,12 @@ inline absl::Status JsonStringToMessage(absl::string_view input, // Please note that non-OK statuses are not a stable output of this API and // subject to change without notice. PROTOBUF_EXPORT absl::Status BinaryToJsonStream( - google::protobuf::util::TypeResolver* resolver, absl::string_view type_url, + google::protobuf::util::TypeResolver* resolver, const std::string& type_url, io::ZeroCopyInputStream* binary_input, io::ZeroCopyOutputStream* json_output, const PrintOptions& options); inline absl::Status BinaryToJsonStream(google::protobuf::util::TypeResolver* resolver, - absl::string_view type_url, + const std::string& type_url, io::ZeroCopyInputStream* binary_input, io::ZeroCopyOutputStream* json_output) { return BinaryToJsonStream(resolver, type_url, binary_input, json_output, @@ -107,13 +107,13 @@ inline absl::Status BinaryToJsonStream(google::protobuf::util::TypeResolver* res } PROTOBUF_EXPORT absl::Status BinaryToJsonString( - google::protobuf::util::TypeResolver* resolver, absl::string_view type_url, - absl::string_view binary_input, std::string* json_output, + google::protobuf::util::TypeResolver* resolver, const std::string& type_url, + const std::string& binary_input, std::string* json_output, const PrintOptions& options); inline absl::Status BinaryToJsonString(google::protobuf::util::TypeResolver* resolver, - absl::string_view type_url, - absl::string_view binary_input, + const std::string& type_url, + const std::string& binary_input, std::string* json_output) { return BinaryToJsonString(resolver, type_url, binary_input, json_output, PrintOptions()); @@ -128,12 +128,12 @@ inline absl::Status BinaryToJsonString(google::protobuf::util::TypeResolver* res // Please note that non-OK statuses are not a stable output of this API and // subject to change without notice. PROTOBUF_EXPORT absl::Status JsonToBinaryStream( - google::protobuf::util::TypeResolver* resolver, absl::string_view type_url, + google::protobuf::util::TypeResolver* resolver, const std::string& type_url, io::ZeroCopyInputStream* json_input, io::ZeroCopyOutputStream* binary_output, const ParseOptions& options); inline absl::Status JsonToBinaryStream( - google::protobuf::util::TypeResolver* resolver, absl::string_view type_url, + google::protobuf::util::TypeResolver* resolver, const std::string& type_url, io::ZeroCopyInputStream* json_input, io::ZeroCopyOutputStream* binary_output) { return JsonToBinaryStream(resolver, type_url, json_input, binary_output, @@ -141,12 +141,12 @@ inline absl::Status JsonToBinaryStream( } PROTOBUF_EXPORT absl::Status JsonToBinaryString( - google::protobuf::util::TypeResolver* resolver, absl::string_view type_url, + google::protobuf::util::TypeResolver* resolver, const std::string& type_url, absl::string_view json_input, std::string* binary_output, const ParseOptions& options); inline absl::Status JsonToBinaryString(google::protobuf::util::TypeResolver* resolver, - absl::string_view type_url, + const std::string& type_url, absl::string_view json_input, std::string* binary_output) { return JsonToBinaryString(resolver, type_url, json_input, binary_output, diff --git a/src/google/protobuf/testing/file.cc b/src/google/protobuf/testing/file.cc index 0efc7c96f0..277e0f23d4 100644 --- a/src/google/protobuf/testing/file.cc +++ b/src/google/protobuf/testing/file.cc @@ -51,14 +51,14 @@ using google::protobuf::io::win32::mkdir; using google::protobuf::io::win32::stat; #endif -bool File::Exists(absl::string_view name) { - return access(std::string(name).c_str(), F_OK) == 0; +bool File::Exists(const std::string& name) { + return access(name.c_str(), F_OK) == 0; } -absl::Status File::ReadFileToString(absl::string_view name, std::string* output, - bool text_mode) { +absl::Status File::ReadFileToString(const std::string& name, + std::string* output, bool text_mode) { char buffer[1024]; - FILE* file = fopen(std::string(name).c_str(), text_mode ? "rt" : "rb"); + FILE* file = fopen(name.c_str(), text_mode ? "rt" : "rb"); if (file == nullptr) return absl::NotFoundError("Could not open file"); while (true) { @@ -73,13 +73,13 @@ absl::Status File::ReadFileToString(absl::string_view name, std::string* output, return absl::OkStatus(); } -void File::ReadFileToStringOrDie(absl::string_view name, std::string* output) { +void File::ReadFileToStringOrDie(const std::string& name, std::string* output) { ABSL_CHECK_OK(ReadFileToString(name, output)) << "Could not read: " << name; } absl::Status File::WriteStringToFile(absl::string_view contents, - absl::string_view name) { - FILE* file = fopen(std::string(name).c_str(), "wb"); + const std::string& name) { + FILE* file = fopen(name.c_str(), "wb"); if (file == nullptr) { return absl::InternalError( absl::StrCat("fopen(", name, ", \"wb\"): ", strerror(errno))); @@ -98,8 +98,8 @@ absl::Status File::WriteStringToFile(absl::string_view contents, } void File::WriteStringToFileOrDie(absl::string_view contents, - absl::string_view name) { - FILE* file = fopen(std::string(name).c_str(), "wb"); + const std::string& name) { + FILE* file = fopen(name.c_str(), "wb"); ABSL_CHECK(file != nullptr) << "fopen(" << name << ", \"wb\"): " << strerror(errno); ABSL_CHECK_EQ(fwrite(contents.data(), 1, contents.size(), file), @@ -109,17 +109,17 @@ void File::WriteStringToFileOrDie(absl::string_view contents, << "fclose(" << name << "): " << strerror(errno); } -absl::Status File::CreateDir(absl::string_view name, int mode) { +absl::Status File::CreateDir(const std::string& name, int mode) { if (!name.empty()) { ABSL_CHECK(name[name.size() - 1] != '.'); } - if (mkdir(std::string(name).c_str(), mode) != 0) { + if (mkdir(name.c_str(), mode) != 0) { return absl::InternalError("Failed to create directory"); } return absl::OkStatus(); } -absl::Status File::RecursivelyCreateDir(absl::string_view path, int mode) { +absl::Status File::RecursivelyCreateDir(const std::string& path, int mode) { if (CreateDir(path, mode).ok()) return absl::OkStatus(); if (Exists(path)) return absl::AlreadyExistsError("Path already exists"); @@ -134,11 +134,9 @@ absl::Status File::RecursivelyCreateDir(absl::string_view path, int mode) { return CreateDir(path, mode); } -void File::DeleteRecursively(absl::string_view name_view, void* dummy1, +void File::DeleteRecursively(const std::string& name, void* dummy1, void* dummy2) { - if (name_view.empty()) return; - - std::string name(name_view); + if (name.empty()) return; // We don't care too much about error checking here since this is only used // in tests to delete temporary directories that are under /tmp anyway. @@ -150,7 +148,7 @@ void File::DeleteRecursively(absl::string_view name_view, void* dummy1, FindFirstFileA(absl::StrCat(name, "/*").c_str(), &find_data); if (find_handle == INVALID_HANDLE_VALUE) { // Just delete it, whatever it is. - DeleteFileA(std::string(name).c_str()); + DeleteFileA(name.c_str()); RemoveDirectoryA(name.c_str()); return; } @@ -198,8 +196,8 @@ void File::DeleteRecursively(absl::string_view name_view, void* dummy1, #endif } -bool File::ChangeWorkingDirectory(absl::string_view new_working_directory) { - return chdir(std::string(new_working_directory).c_str()) == 0; +bool File::ChangeWorkingDirectory(const std::string& new_working_directory) { + return chdir(new_working_directory.c_str()) == 0; } } // namespace protobuf diff --git a/src/google/protobuf/testing/file.h b/src/google/protobuf/testing/file.h index 63e708b0d8..74dfdbf98a 100644 --- a/src/google/protobuf/testing/file.h +++ b/src/google/protobuf/testing/file.h @@ -28,55 +28,55 @@ class File { File& operator=(const File&) = delete; // Check if the file exists. - static bool Exists(absl::string_view name); + static bool Exists(const std::string& name); // Read an entire file to a string. Return true if successful, false // otherwise. - static absl::Status ReadFileToString(absl::string_view name, + static absl::Status ReadFileToString(const std::string& name, std::string* output, bool text_mode = false); // Same as above, but crash on failure. - static void ReadFileToStringOrDie(absl::string_view name, + static void ReadFileToStringOrDie(const std::string& name, std::string* output); // Create a file and write a string to it. static absl::Status WriteStringToFile(absl::string_view contents, - absl::string_view name); + const std::string& name); // Same as above, but crash on failure. static void WriteStringToFileOrDie(absl::string_view contents, - absl::string_view name); + const std::string& name); // Create a directory. - static absl::Status CreateDir(absl::string_view name, int mode); + static absl::Status CreateDir(const std::string& name, int mode); // Create a directory and all parent directories if necessary. - static absl::Status RecursivelyCreateDir(absl::string_view path, int mode); + static absl::Status RecursivelyCreateDir(const std::string& path, int mode); // If "name" is a file, we delete it. If it is a directory, we // call DeleteRecursively() for each file or directory (other than // dot and double-dot) within it, and then delete the directory itself. // The "dummy" parameters have a meaning in the original version of this // method but they are not used anywhere in protocol buffers. - static void DeleteRecursively(absl::string_view name, void* dummy1, + static void DeleteRecursively(const std::string& name, void* dummy1, void* dummy2); // Change working directory to given directory. - static bool ChangeWorkingDirectory(absl::string_view new_working_directory); + static bool ChangeWorkingDirectory(const std::string& new_working_directory); - static absl::Status GetContents(absl::string_view name, std::string* output, + static absl::Status GetContents(const std::string& name, std::string* output, bool /*is_default*/) { return ReadFileToString(name, output); } - static absl::Status GetContentsAsText(absl::string_view name, + static absl::Status GetContentsAsText(const std::string& name, std::string* output, bool /*is_default*/) { return ReadFileToString(name, output, true); } - static absl::Status SetContents(absl::string_view name, + static absl::Status SetContents(const std::string& name, absl::string_view contents, bool /*is_default*/) { return WriteStringToFile(contents, name); diff --git a/src/google/protobuf/util/message_differencer.cc b/src/google/protobuf/util/message_differencer.cc index e4305d38f2..258c0e9bec 100644 --- a/src/google/protobuf/util/message_differencer.cc +++ b/src/google/protobuf/util/message_differencer.cc @@ -2234,8 +2234,8 @@ void MessageDifferencer::StreamReporter::PrintUnknownFieldValue( printer_->PrintRaw(output); } -void MessageDifferencer::StreamReporter::Print(absl::string_view str) { - printer_->Print(str); +void MessageDifferencer::StreamReporter::Print(const std::string& str) { + printer_->Print(str.c_str()); } void MessageDifferencer::StreamReporter::PrintMapKey( @@ -2382,5 +2382,3 @@ MessageDifferencer::CreateMultipleFieldsMapKeyComparator( } // namespace util } // namespace protobuf } // namespace google - -#include "google/protobuf/port_undef.inc" diff --git a/src/google/protobuf/util/message_differencer.h b/src/google/protobuf/util/message_differencer.h index 841e5131c9..1cfd600e44 100644 --- a/src/google/protobuf/util/message_differencer.h +++ b/src/google/protobuf/util/message_differencer.h @@ -30,7 +30,6 @@ #include "absl/container/flat_hash_map.h" #include "absl/container/flat_hash_set.h" #include "absl/log/absl_check.h" -#include "absl/strings/string_view.h" #include "google/protobuf/descriptor.h" // FieldDescriptor #include "google/protobuf/message.h" // Message #include "google/protobuf/text_format.h" @@ -729,7 +728,7 @@ class PROTOBUF_EXPORT MessageDifferencer { virtual void PrintUnknownFieldValue(const UnknownField* unknown_field); // Just print a string - void Print(absl::string_view str); + void Print(const std::string& str); private: // helper function for PrintPath that contains logic for printing maps