diff --git a/p2p/base/port.cc b/p2p/base/port.cc index f864150969..a061688b72 100644 --- a/p2p/base/port.cc +++ b/p2p/base/port.cc @@ -19,6 +19,7 @@ #include "absl/algorithm/container.h" #include "absl/strings/match.h" +#include "absl/strings/string_view.h" #include "p2p/base/connection.h" #include "p2p/base/port_allocator.h" #include "rtc_base/checks.h" @@ -301,7 +302,7 @@ bool Port::MaybeObfuscateAddress(Candidate* c, auto copy = *c; auto weak_ptr = weak_factory_.GetWeakPtr(); auto callback = [weak_ptr, copy, is_final](const rtc::IPAddress& addr, - const std::string& name) mutable { + absl::string_view name) mutable { RTC_DCHECK(copy.address().ipaddr() == addr); rtc::SocketAddress hostname_address(name, copy.address().port()); // In Port and Connection, we need the IP address information to diff --git a/rtc_base/BUILD.gn b/rtc_base/BUILD.gn index 1db186c0fc..e09b62f936 100644 --- a/rtc_base/BUILD.gn +++ b/rtc_base/BUILD.gn @@ -96,6 +96,7 @@ rtc_library("rtc_base_approved") { absl_deps = [ "//third_party/abseil-cpp/absl/base:core_headers", "//third_party/abseil-cpp/absl/numeric:bits", + "//third_party/abseil-cpp/absl/strings", "//third_party/abseil-cpp/absl/types:optional", ] public_deps = [] # no-presubmit-check TODO(webrtc:8603) @@ -683,6 +684,7 @@ rtc_library("rtc_json") { # expected to be when building json outside of the standalone build. defines += [ "WEBRTC_EXTERNAL_JSON" ] } + absl_deps = [ "//third_party/abseil-cpp/absl/strings" ] } rtc_library("net_helpers") { @@ -730,6 +732,7 @@ rtc_library("ip_address") { if (is_win) { deps += [ ":win32" ] } + absl_deps = [ "//third_party/abseil-cpp/absl/strings" ] } rtc_library("socket_address") { @@ -751,6 +754,7 @@ rtc_library("socket_address") { if (is_win) { deps += [ ":win32" ] } + absl_deps = [ "//third_party/abseil-cpp/absl/strings" ] } rtc_library("null_socket_server") { @@ -795,6 +799,7 @@ rtc_library("threading") { absl_deps = [ "//third_party/abseil-cpp/absl/algorithm:container", "//third_party/abseil-cpp/absl/base:core_headers", + "//third_party/abseil-cpp/absl/strings", ] deps = [ ":async_resolver_interface", @@ -1233,6 +1238,7 @@ rtc_library("rtc_base_tests_utils") { absl_deps = [ "//third_party/abseil-cpp/absl/algorithm:container", "//third_party/abseil-cpp/absl/memory", + "//third_party/abseil-cpp/absl/strings", ] } @@ -1326,7 +1332,10 @@ if (rtc_include_tests) { "third_party/sigslot", "//testing/gtest", ] - absl_deps = [ "//third_party/abseil-cpp/absl/memory" ] + absl_deps = [ + "//third_party/abseil-cpp/absl/memory", + "//third_party/abseil-cpp/absl/strings", + ] } rtc_library("rtc_base_approved_unittests") { diff --git a/rtc_base/boringssl_certificate.cc b/rtc_base/boringssl_certificate.cc index 99b2ab3e24..a866224496 100644 --- a/rtc_base/boringssl_certificate.cc +++ b/rtc_base/boringssl_certificate.cc @@ -10,6 +10,8 @@ #include "rtc_base/boringssl_certificate.h" +#include "absl/strings/string_view.h" + #if defined(WEBRTC_WIN) // Must be included first before openssl headers. #include "rtc_base/win32.h" // NOLINT @@ -116,7 +118,7 @@ bool AddSHA256SignatureAlgorithm(CBB* cbb, KeyType key_type) { } // Adds an X.509 Common Name to `cbb`. -bool AddCommonName(CBB* cbb, const std::string& common_name) { +bool AddCommonName(CBB* cbb, absl::string_view common_name) { // See RFC 4519. static const uint8_t kCommonName[] = {0x55, 0x04, 0x03}; @@ -138,7 +140,7 @@ bool AddCommonName(CBB* cbb, const std::string& common_name) { !CBB_add_bytes(&type, kCommonName, sizeof(kCommonName)) || !CBB_add_asn1(&attr, &value, CBS_ASN1_UTF8STRING) || !CBB_add_bytes(&value, - reinterpret_cast(common_name.c_str()), + reinterpret_cast(common_name.data()), common_name.size()) || !CBB_flush(cbb)) { return false; @@ -275,7 +277,7 @@ std::unique_ptr BoringSSLCertificate::Generate( } std::unique_ptr BoringSSLCertificate::FromPEMString( - const std::string& pem_string) { + absl::string_view pem_string) { std::string der; if (!SSLIdentity::PemToDer(kPemTypeCertificate, pem_string, &der)) { return nullptr; @@ -340,7 +342,7 @@ bool BoringSSLCertificate::GetSignatureDigestAlgorithm( return false; } -bool BoringSSLCertificate::ComputeDigest(const std::string& algorithm, +bool BoringSSLCertificate::ComputeDigest(absl::string_view algorithm, unsigned char* digest, size_t size, size_t* length) const { @@ -348,7 +350,7 @@ bool BoringSSLCertificate::ComputeDigest(const std::string& algorithm, } bool BoringSSLCertificate::ComputeDigest(const CRYPTO_BUFFER* cert_buffer, - const std::string& algorithm, + absl::string_view algorithm, unsigned char* digest, size_t size, size_t* length) { diff --git a/rtc_base/boringssl_certificate.h b/rtc_base/boringssl_certificate.h index 8b4577a17c..bd331686b7 100644 --- a/rtc_base/boringssl_certificate.h +++ b/rtc_base/boringssl_certificate.h @@ -18,6 +18,7 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/buffer.h" #include "rtc_base/ssl_certificate.h" #include "rtc_base/ssl_identity.h" @@ -38,7 +39,7 @@ class BoringSSLCertificate final : public SSLCertificate { OpenSSLKeyPair* key_pair, const SSLIdentityParams& params); static std::unique_ptr FromPEMString( - const std::string& pem_string); + absl::string_view pem_string); ~BoringSSLCertificate() override; @@ -55,14 +56,14 @@ class BoringSSLCertificate final : public SSLCertificate { bool operator!=(const BoringSSLCertificate& other) const; // Compute the digest of the certificate given `algorithm`. - bool ComputeDigest(const std::string& algorithm, + bool ComputeDigest(absl::string_view algorithm, unsigned char* digest, size_t size, size_t* length) const override; // Compute the digest of a certificate as a CRYPTO_BUFFER. static bool ComputeDigest(const CRYPTO_BUFFER* cert_buffer, - const std::string& algorithm, + absl::string_view algorithm, unsigned char* digest, size_t size, size_t* length); diff --git a/rtc_base/boringssl_identity.cc b/rtc_base/boringssl_identity.cc index d22c8ce529..a61524a679 100644 --- a/rtc_base/boringssl_identity.cc +++ b/rtc_base/boringssl_identity.cc @@ -22,6 +22,7 @@ #include #include "absl/memory/memory.h" +#include "absl/strings/string_view.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" #include "rtc_base/numerics/safe_conversions.h" @@ -67,12 +68,12 @@ std::unique_ptr BoringSSLIdentity::CreateInternal( // static std::unique_ptr BoringSSLIdentity::CreateWithExpiration( - const std::string& common_name, + absl::string_view common_name, const KeyParams& key_params, time_t certificate_lifetime) { SSLIdentityParams params; params.key_params = key_params; - params.common_name = common_name; + params.common_name = std::string(common_name); time_t now = time(nullptr); params.not_before = now + kCertificateWindowInSeconds; params.not_after = now + certificate_lifetime; @@ -87,8 +88,8 @@ std::unique_ptr BoringSSLIdentity::CreateForTest( } std::unique_ptr BoringSSLIdentity::CreateFromPEMStrings( - const std::string& private_key, - const std::string& certificate) { + absl::string_view private_key, + absl::string_view certificate) { std::unique_ptr cert( BoringSSLCertificate::FromPEMString(certificate)); if (!cert) { @@ -108,8 +109,8 @@ std::unique_ptr BoringSSLIdentity::CreateFromPEMStrings( } std::unique_ptr BoringSSLIdentity::CreateFromPEMChainStrings( - const std::string& private_key, - const std::string& certificate_chain) { + absl::string_view private_key, + absl::string_view certificate_chain) { bssl::UniquePtr bio( BIO_new_mem_buf(certificate_chain.data(), rtc::dchecked_cast(certificate_chain.size()))); diff --git a/rtc_base/boringssl_identity.h b/rtc_base/boringssl_identity.h index e322afaba0..ffc8812af2 100644 --- a/rtc_base/boringssl_identity.h +++ b/rtc_base/boringssl_identity.h @@ -17,6 +17,7 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/boringssl_certificate.h" #include "rtc_base/openssl_key_pair.h" #include "rtc_base/ssl_certificate.h" @@ -30,17 +31,17 @@ namespace rtc { class BoringSSLIdentity final : public SSLIdentity { public: static std::unique_ptr CreateWithExpiration( - const std::string& common_name, + absl::string_view common_name, const KeyParams& key_params, time_t certificate_lifetime); static std::unique_ptr CreateForTest( const SSLIdentityParams& params); static std::unique_ptr CreateFromPEMStrings( - const std::string& private_key, - const std::string& certificate); + absl::string_view private_key, + absl::string_view certificate); static std::unique_ptr CreateFromPEMChainStrings( - const std::string& private_key, - const std::string& certificate_chain); + absl::string_view private_key, + absl::string_view certificate_chain); ~BoringSSLIdentity() override; BoringSSLIdentity(const BoringSSLIdentity&) = delete; diff --git a/rtc_base/byte_buffer.h b/rtc_base/byte_buffer.h index d2dda3c8e1..9bcbb838aa 100644 --- a/rtc_base/byte_buffer.h +++ b/rtc_base/byte_buffer.h @@ -16,6 +16,7 @@ #include +#include "absl/strings/string_view.h" #include "rtc_base/buffer.h" #include "rtc_base/byte_order.h" @@ -72,8 +73,8 @@ class ByteBufferWriterT { char last_byte = static_cast(val); WriteBytes(&last_byte, 1); } - void WriteString(const std::string& val) { - WriteBytes(val.c_str(), val.size()); + void WriteString(absl::string_view val) { + WriteBytes(val.data(), val.size()); } void WriteBytes(const char* val, size_t len) { buffer_.AppendData(val, len); } diff --git a/rtc_base/checks.cc b/rtc_base/checks.cc index 239ea9f0da..d6974d722f 100644 --- a/rtc_base/checks.cc +++ b/rtc_base/checks.cc @@ -15,6 +15,8 @@ #include #include +#include "absl/strings/string_view.h" + #if defined(WEBRTC_ANDROID) #define RTC_LOG_TAG_ANDROID "rtc" #include // NOLINT @@ -37,13 +39,14 @@ namespace { -RTC_NORETURN void WriteFatalLogAndAbort(const std::string& output) { - const char* output_c = output.c_str(); +RTC_NORETURN void WriteFatalLogAndAbort(absl::string_view output) { #if defined(WEBRTC_ANDROID) - __android_log_print(ANDROID_LOG_ERROR, RTC_LOG_TAG_ANDROID, "%s\n", output_c); + std::string output_str = std::string(output); + __android_log_print(ANDROID_LOG_ERROR, RTC_LOG_TAG_ANDROID, "%s\n", + output_str.c_str()); #endif fflush(stdout); - fprintf(stderr, "%s", output_c); + fwrite(output.data(), output.size(), 1, stderr); fflush(stderr); #if defined(WEBRTC_WIN) DebugBreak(); diff --git a/rtc_base/crc32.h b/rtc_base/crc32.h index ca8578d69c..93376a5a12 100644 --- a/rtc_base/crc32.h +++ b/rtc_base/crc32.h @@ -16,6 +16,8 @@ #include +#include "absl/strings/string_view.h" + namespace rtc { // Updates a CRC32 checksum with `len` bytes from `buf`. `initial` holds the @@ -26,8 +28,8 @@ uint32_t UpdateCrc32(uint32_t initial, const void* buf, size_t len); inline uint32_t ComputeCrc32(const void* buf, size_t len) { return UpdateCrc32(0, buf, len); } -inline uint32_t ComputeCrc32(const std::string& str) { - return ComputeCrc32(str.c_str(), str.size()); +inline uint32_t ComputeCrc32(absl::string_view str) { + return ComputeCrc32(str.data(), str.size()); } } // namespace rtc diff --git a/rtc_base/experiments/BUILD.gn b/rtc_base/experiments/BUILD.gn index b9d24ca6cc..5788484025 100644 --- a/rtc_base/experiments/BUILD.gn +++ b/rtc_base/experiments/BUILD.gn @@ -157,7 +157,10 @@ rtc_library("encoder_info_settings") { "../../api/video_codecs:video_codecs_api", "../../system_wrappers:field_trial", ] - absl_deps = [ "//third_party/abseil-cpp/absl/types:optional" ] + absl_deps = [ + "//third_party/abseil-cpp/absl/strings", + "//third_party/abseil-cpp/absl/types:optional", + ] } rtc_library("rtt_mult_experiment") { @@ -296,6 +299,9 @@ if (rtc_include_tests && !build_with_chromium) { "../../test:test_main", "../../test:test_support", ] - absl_deps = [ "//third_party/abseil-cpp/absl/types:optional" ] + absl_deps = [ + "//third_party/abseil-cpp/absl/strings", + "//third_party/abseil-cpp/absl/types:optional", + ] } } diff --git a/rtc_base/experiments/encoder_info_settings.cc b/rtc_base/experiments/encoder_info_settings.cc index b39c68468f..a74eb50a43 100644 --- a/rtc_base/experiments/encoder_info_settings.cc +++ b/rtc_base/experiments/encoder_info_settings.cc @@ -12,6 +12,7 @@ #include +#include "absl/strings/string_view.h" #include "rtc_base/experiments/field_trial_list.h" #include "rtc_base/logging.h" #include "system_wrappers/include/field_trial.h" @@ -155,7 +156,7 @@ EncoderInfoSettings::GetSinglecastBitrateLimitForResolutionWhenQpIsUntrusted( } } -EncoderInfoSettings::EncoderInfoSettings(std::string name) +EncoderInfoSettings::EncoderInfoSettings(absl::string_view name) : requested_resolution_alignment_("requested_resolution_alignment"), apply_alignment_to_all_simulcast_layers_( "apply_alignment_to_all_simulcast_layers") { @@ -174,14 +175,15 @@ EncoderInfoSettings::EncoderInfoSettings(std::string name) [](BitrateLimit* b) { return &b->max_bitrate_bps; })}, {}); - if (field_trial::FindFullName(name).empty()) { + std::string name_str = std::string(name); + if (field_trial::FindFullName(name_str).empty()) { // Encoder name not found, use common string applying to all encoders. - name = "WebRTC-GetEncoderInfoOverride"; + name_str = "WebRTC-GetEncoderInfoOverride"; } ParseFieldTrial({&bitrate_limits, &requested_resolution_alignment_, &apply_alignment_to_all_simulcast_layers_}, - field_trial::FindFullName(name)); + field_trial::FindFullName(name_str)); resolution_bitrate_limits_ = ToResolutionBitrateLimits(bitrate_limits.Get()); } diff --git a/rtc_base/experiments/encoder_info_settings.h b/rtc_base/experiments/encoder_info_settings.h index e4dc459fcf..d450697f47 100644 --- a/rtc_base/experiments/encoder_info_settings.h +++ b/rtc_base/experiments/encoder_info_settings.h @@ -14,6 +14,7 @@ #include #include +#include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "api/video_codecs/video_encoder.h" #include "rtc_base/experiments/field_trial_parser.h" @@ -58,7 +59,7 @@ class EncoderInfoSettings { resolution_bitrate_limits); protected: - explicit EncoderInfoSettings(std::string name); + explicit EncoderInfoSettings(absl::string_view name); private: FieldTrialOptional requested_resolution_alignment_; diff --git a/rtc_base/experiments/field_trial_list.cc b/rtc_base/experiments/field_trial_list.cc index ac3fd88f49..72cd79f2d2 100644 --- a/rtc_base/experiments/field_trial_list.cc +++ b/rtc_base/experiments/field_trial_list.cc @@ -9,9 +9,11 @@ */ #include "rtc_base/experiments/field_trial_list.h" +#include "absl/strings/string_view.h" + namespace webrtc { -FieldTrialListBase::FieldTrialListBase(std::string key) +FieldTrialListBase::FieldTrialListBase(absl::string_view key) : FieldTrialParameterInterface(key), failed_(false), parse_got_called_(false) {} diff --git a/rtc_base/experiments/field_trial_list.h b/rtc_base/experiments/field_trial_list.h index 00425be7b9..7b9f0d9dfc 100644 --- a/rtc_base/experiments/field_trial_list.h +++ b/rtc_base/experiments/field_trial_list.h @@ -15,6 +15,7 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/experiments/field_trial_parser.h" #include "rtc_base/string_encode.h" @@ -36,7 +37,7 @@ namespace webrtc { class FieldTrialListBase : public FieldTrialParameterInterface { protected: friend class FieldTrialListWrapper; - explicit FieldTrialListBase(std::string key); + explicit FieldTrialListBase(absl::string_view key); bool Failed() const; bool Used() const; @@ -52,8 +53,8 @@ class FieldTrialListBase : public FieldTrialParameterInterface { template class FieldTrialList : public FieldTrialListBase { public: - explicit FieldTrialList(std::string key) : FieldTrialList(key, {}) {} - FieldTrialList(std::string key, std::initializer_list default_values) + explicit FieldTrialList(absl::string_view key) : FieldTrialList(key, {}) {} + FieldTrialList(absl::string_view key, std::initializer_list default_values) : FieldTrialListBase(key), values_(default_values) {} std::vector Get() const { return values_; } @@ -132,7 +133,7 @@ struct LambdaTypeTraits { template struct TypedFieldTrialListWrapper : FieldTrialListWrapper { public: - TypedFieldTrialListWrapper(std::string key, + TypedFieldTrialListWrapper(absl::string_view key, std::function sink) : list_(key), sink_(sink) {} @@ -151,7 +152,8 @@ struct TypedFieldTrialListWrapper : FieldTrialListWrapper { template > -FieldTrialListWrapper* FieldTrialStructMember(std::string key, F accessor) { +FieldTrialListWrapper* FieldTrialStructMember(absl::string_view key, + F accessor) { return new field_trial_list_impl::TypedFieldTrialListWrapper< typename Traits::ret>(key, [accessor](void* s, typename Traits::ret t) { *accessor(static_cast(s)) = t; diff --git a/rtc_base/experiments/field_trial_list_unittest.cc b/rtc_base/experiments/field_trial_list_unittest.cc index 6d5e212eea..221a3c6929 100644 --- a/rtc_base/experiments/field_trial_list_unittest.cc +++ b/rtc_base/experiments/field_trial_list_unittest.cc @@ -10,6 +10,7 @@ #include "rtc_base/experiments/field_trial_list.h" +#include "absl/strings/string_view.h" #include "rtc_base/gunit.h" #include "test/gmock.h" @@ -25,7 +26,8 @@ struct Garment { // Only needed for testing. Garment() = default; - Garment(int p, std::string c, bool g) : price(p), color(c), has_glitter(g) {} + Garment(int p, absl::string_view c, bool g) + : price(p), color(c), has_glitter(g) {} bool operator==(const Garment& other) const { return price == other.price && color == other.color && diff --git a/rtc_base/experiments/field_trial_parser.cc b/rtc_base/experiments/field_trial_parser.cc index 952250b767..78d5489f5e 100644 --- a/rtc_base/experiments/field_trial_parser.cc +++ b/rtc_base/experiments/field_trial_parser.cc @@ -23,7 +23,8 @@ namespace webrtc { -FieldTrialParameterInterface::FieldTrialParameterInterface(std::string key) +FieldTrialParameterInterface::FieldTrialParameterInterface( + absl::string_view key) : key_(key) {} FieldTrialParameterInterface::~FieldTrialParameterInterface() { RTC_DCHECK(used_) << "Field trial parameter with key: '" << key_ @@ -111,7 +112,7 @@ void ParseFieldTrial( } template <> -absl::optional ParseTypedParameter(std::string str) { +absl::optional ParseTypedParameter(absl::string_view str) { if (str == "true" || str == "1") { return true; } else if (str == "false" || str == "0") { @@ -121,10 +122,10 @@ absl::optional ParseTypedParameter(std::string str) { } template <> -absl::optional ParseTypedParameter(std::string str) { +absl::optional ParseTypedParameter(absl::string_view str) { double value; char unit[2]{0, 0}; - if (sscanf(str.c_str(), "%lf%1s", &value, unit) >= 1) { + if (sscanf(std::string(str).c_str(), "%lf%1s", &value, unit) >= 1) { if (unit[0] == '%') return value / 100; return value; @@ -134,9 +135,9 @@ absl::optional ParseTypedParameter(std::string str) { } template <> -absl::optional ParseTypedParameter(std::string str) { +absl::optional ParseTypedParameter(absl::string_view str) { int64_t value; - if (sscanf(str.c_str(), "%" SCNd64, &value) == 1) { + if (sscanf(std::string(str).c_str(), "%" SCNd64, &value) == 1) { if (rtc::IsValueInRangeForNumericType(value)) { return static_cast(value); } @@ -145,9 +146,9 @@ absl::optional ParseTypedParameter(std::string str) { } template <> -absl::optional ParseTypedParameter(std::string str) { +absl::optional ParseTypedParameter(absl::string_view str) { int64_t value; - if (sscanf(str.c_str(), "%" SCNd64, &value) == 1) { + if (sscanf(std::string(str).c_str(), "%" SCNd64, &value) == 1) { if (rtc::IsValueInRangeForNumericType(value)) { return static_cast(value); } @@ -156,34 +157,36 @@ absl::optional ParseTypedParameter(std::string str) { } template <> -absl::optional ParseTypedParameter(std::string str) { - return std::move(str); +absl::optional ParseTypedParameter( + absl::string_view str) { + return std::string(str); } template <> absl::optional> ParseTypedParameter>( - std::string str) { + absl::string_view str) { return ParseOptionalParameter(str); } template <> absl::optional> ParseTypedParameter>( - std::string str) { + absl::string_view str) { return ParseOptionalParameter(str); } template <> absl::optional> -ParseTypedParameter>(std::string str) { +ParseTypedParameter>(absl::string_view str) { return ParseOptionalParameter(str); } template <> absl::optional> -ParseTypedParameter>(std::string str) { +ParseTypedParameter>(absl::string_view str) { return ParseOptionalParameter(str); } -FieldTrialFlag::FieldTrialFlag(std::string key) : FieldTrialFlag(key, false) {} +FieldTrialFlag::FieldTrialFlag(absl::string_view key) + : FieldTrialFlag(key, false) {} -FieldTrialFlag::FieldTrialFlag(std::string key, bool default_value) +FieldTrialFlag::FieldTrialFlag(absl::string_view key, bool default_value) : FieldTrialParameterInterface(key), value_(default_value) {} bool FieldTrialFlag::Get() const { @@ -208,7 +211,7 @@ bool FieldTrialFlag::Parse(absl::optional str_value) { } AbstractFieldTrialEnum::AbstractFieldTrialEnum( - std::string key, + absl::string_view key, int default_value, std::map mapping) : FieldTrialParameterInterface(key), diff --git a/rtc_base/experiments/field_trial_parser.h b/rtc_base/experiments/field_trial_parser.h index bd11eea20a..822895e70b 100644 --- a/rtc_base/experiments/field_trial_parser.h +++ b/rtc_base/experiments/field_trial_parser.h @@ -46,7 +46,7 @@ class FieldTrialParameterInterface { FieldTrialParameterInterface(const FieldTrialParameterInterface&) = default; FieldTrialParameterInterface& operator=(const FieldTrialParameterInterface&) = default; - explicit FieldTrialParameterInterface(std::string key); + explicit FieldTrialParameterInterface(absl::string_view key); friend void ParseFieldTrial( std::initializer_list fields, absl::string_view trial_string); @@ -71,14 +71,14 @@ void ParseFieldTrial( // Specialize this in code file for custom types. Should return absl::nullopt if // the given string cannot be properly parsed. template -absl::optional ParseTypedParameter(std::string); +absl::optional ParseTypedParameter(absl::string_view); // This class uses the ParseTypedParameter function to implement a parameter // implementation with an enforced default value. template class FieldTrialParameter : public FieldTrialParameterInterface { public: - FieldTrialParameter(std::string key, T default_value) + FieldTrialParameter(absl::string_view key, T default_value) : FieldTrialParameterInterface(key), value_(default_value) {} T Get() const { return value_; } operator T() const { return Get(); } @@ -108,7 +108,7 @@ class FieldTrialParameter : public FieldTrialParameterInterface { template class FieldTrialConstrained : public FieldTrialParameterInterface { public: - FieldTrialConstrained(std::string key, + FieldTrialConstrained(absl::string_view key, T default_value, absl::optional lower_limit, absl::optional upper_limit) @@ -141,7 +141,7 @@ class FieldTrialConstrained : public FieldTrialParameterInterface { class AbstractFieldTrialEnum : public FieldTrialParameterInterface { public: - AbstractFieldTrialEnum(std::string key, + AbstractFieldTrialEnum(absl::string_view key, int default_value, std::map mapping); ~AbstractFieldTrialEnum() override; @@ -162,7 +162,7 @@ class AbstractFieldTrialEnum : public FieldTrialParameterInterface { template class FieldTrialEnum : public AbstractFieldTrialEnum { public: - FieldTrialEnum(std::string key, + FieldTrialEnum(absl::string_view key, T default_value, std::map mapping) : AbstractFieldTrialEnum(key, @@ -185,9 +185,9 @@ class FieldTrialEnum : public AbstractFieldTrialEnum { template class FieldTrialOptional : public FieldTrialParameterInterface { public: - explicit FieldTrialOptional(std::string key) + explicit FieldTrialOptional(absl::string_view key) : FieldTrialParameterInterface(key) {} - FieldTrialOptional(std::string key, absl::optional default_value) + FieldTrialOptional(absl::string_view key, absl::optional default_value) : FieldTrialParameterInterface(key), value_(default_value) {} absl::optional GetOptional() const { return value_; } const T& Value() const { return value_.value(); } @@ -217,8 +217,8 @@ class FieldTrialOptional : public FieldTrialParameterInterface { // explicit value is provided, the flag evaluates to true. class FieldTrialFlag : public FieldTrialParameterInterface { public: - explicit FieldTrialFlag(std::string key); - FieldTrialFlag(std::string key, bool default_value); + explicit FieldTrialFlag(absl::string_view key); + FieldTrialFlag(absl::string_view key, bool default_value); bool Get() const; explicit operator bool() const; @@ -230,7 +230,8 @@ class FieldTrialFlag : public FieldTrialParameterInterface { }; template -absl::optional> ParseOptionalParameter(std::string str) { +absl::optional> ParseOptionalParameter( + absl::string_view str) { if (str.empty()) return absl::optional(); auto parsed = ParseTypedParameter(str); @@ -240,28 +241,29 @@ absl::optional> ParseOptionalParameter(std::string str) { } template <> -absl::optional ParseTypedParameter(std::string str); +absl::optional ParseTypedParameter(absl::string_view str); template <> -absl::optional ParseTypedParameter(std::string str); +absl::optional ParseTypedParameter(absl::string_view str); template <> -absl::optional ParseTypedParameter(std::string str); +absl::optional ParseTypedParameter(absl::string_view str); template <> -absl::optional ParseTypedParameter(std::string str); +absl::optional ParseTypedParameter(absl::string_view str); template <> -absl::optional ParseTypedParameter(std::string str); +absl::optional ParseTypedParameter( + absl::string_view str); template <> absl::optional> ParseTypedParameter>( - std::string str); + absl::string_view str); template <> absl::optional> ParseTypedParameter>( - std::string str); + absl::string_view str); template <> absl::optional> -ParseTypedParameter>(std::string str); +ParseTypedParameter>(absl::string_view str); template <> absl::optional> -ParseTypedParameter>(std::string str); +ParseTypedParameter>(absl::string_view str); // Accepts true, false, else parsed with sscanf %i, true if != 0. extern template class FieldTrialParameter; diff --git a/rtc_base/experiments/field_trial_parser_unittest.cc b/rtc_base/experiments/field_trial_parser_unittest.cc index d36b3c7d95..9916edee97 100644 --- a/rtc_base/experiments/field_trial_parser_unittest.cc +++ b/rtc_base/experiments/field_trial_parser_unittest.cc @@ -9,6 +9,7 @@ */ #include "rtc_base/experiments/field_trial_parser.h" +#include "absl/strings/string_view.h" #include "rtc_base/experiments/field_trial_list.h" #include "rtc_base/gunit.h" #include "system_wrappers/include/field_trial.h" @@ -28,7 +29,7 @@ struct DummyExperiment { FieldTrialParameter hash = FieldTrialParameter("h", "a80"); - explicit DummyExperiment(std::string field_trial) { + explicit DummyExperiment(absl::string_view field_trial) { ParseFieldTrial({&enabled, &factor, &retries, &size, &ping, &hash}, field_trial); } diff --git a/rtc_base/experiments/field_trial_units.cc b/rtc_base/experiments/field_trial_units.cc index 5aceab76a0..92af46a9e3 100644 --- a/rtc_base/experiments/field_trial_units.cc +++ b/rtc_base/experiments/field_trial_units.cc @@ -14,6 +14,7 @@ #include #include +#include "absl/strings/string_view.h" #include "absl/types/optional.h" // Large enough to fit "seconds", the longest supported unit name. @@ -28,7 +29,7 @@ struct ValueWithUnit { std::string unit; }; -absl::optional ParseValueWithUnit(std::string str) { +absl::optional ParseValueWithUnit(absl::string_view str) { if (str == "inf") { return ValueWithUnit{std::numeric_limits::infinity(), ""}; } else if (str == "-inf") { @@ -37,8 +38,8 @@ absl::optional ParseValueWithUnit(std::string str) { double double_val; char unit_char[RTC_TRIAL_UNIT_SIZE]; unit_char[0] = 0; - if (sscanf(str.c_str(), "%lf%" RTC_TRIAL_UNIT_LENGTH_STR "s", &double_val, - unit_char) >= 1) { + if (sscanf(std::string(str).c_str(), "%lf%" RTC_TRIAL_UNIT_LENGTH_STR "s", + &double_val, unit_char) >= 1) { return ValueWithUnit{double_val, unit_char}; } } @@ -47,7 +48,7 @@ absl::optional ParseValueWithUnit(std::string str) { } // namespace template <> -absl::optional ParseTypedParameter(std::string str) { +absl::optional ParseTypedParameter(absl::string_view str) { absl::optional result = ParseValueWithUnit(str); if (result) { if (result->unit.empty() || result->unit == "kbps") { @@ -60,7 +61,7 @@ absl::optional ParseTypedParameter(std::string str) { } template <> -absl::optional ParseTypedParameter(std::string str) { +absl::optional ParseTypedParameter(absl::string_view str) { absl::optional result = ParseValueWithUnit(str); if (result) { if (result->unit.empty() || result->unit == "bytes") @@ -70,7 +71,8 @@ absl::optional ParseTypedParameter(std::string str) { } template <> -absl::optional ParseTypedParameter(std::string str) { +absl::optional ParseTypedParameter( + absl::string_view str) { absl::optional result = ParseValueWithUnit(str); if (result) { if (result->unit == "s" || result->unit == "seconds") { @@ -86,17 +88,17 @@ absl::optional ParseTypedParameter(std::string str) { template <> absl::optional> -ParseTypedParameter>(std::string str) { +ParseTypedParameter>(absl::string_view str) { return ParseOptionalParameter(str); } template <> absl::optional> -ParseTypedParameter>(std::string str) { +ParseTypedParameter>(absl::string_view str) { return ParseOptionalParameter(str); } template <> absl::optional> -ParseTypedParameter>(std::string str) { +ParseTypedParameter>(absl::string_view str) { return ParseOptionalParameter(str); } diff --git a/rtc_base/experiments/field_trial_units.h b/rtc_base/experiments/field_trial_units.h index d85b2f04ba..408367c031 100644 --- a/rtc_base/experiments/field_trial_units.h +++ b/rtc_base/experiments/field_trial_units.h @@ -10,6 +10,7 @@ #ifndef RTC_BASE_EXPERIMENTS_FIELD_TRIAL_UNITS_H_ #define RTC_BASE_EXPERIMENTS_FIELD_TRIAL_UNITS_H_ +#include "absl/strings/string_view.h" #include "api/units/data_rate.h" #include "api/units/data_size.h" #include "api/units/time_delta.h" @@ -18,11 +19,11 @@ namespace webrtc { template <> -absl::optional ParseTypedParameter(std::string str); +absl::optional ParseTypedParameter(absl::string_view str); template <> -absl::optional ParseTypedParameter(std::string str); +absl::optional ParseTypedParameter(absl::string_view str); template <> -absl::optional ParseTypedParameter(std::string str); +absl::optional ParseTypedParameter(absl::string_view str); extern template class FieldTrialParameter; extern template class FieldTrialParameter; diff --git a/rtc_base/experiments/field_trial_units_unittest.cc b/rtc_base/experiments/field_trial_units_unittest.cc index 1f46d6f9ee..8996663d8e 100644 --- a/rtc_base/experiments/field_trial_units_unittest.cc +++ b/rtc_base/experiments/field_trial_units_unittest.cc @@ -11,6 +11,7 @@ #include +#include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "rtc_base/experiments/field_trial_parser.h" #include "test/gtest.h" @@ -25,7 +26,7 @@ struct DummyExperiment { FieldTrialOptional max_buffer = FieldTrialOptional("b", absl::nullopt); - explicit DummyExperiment(std::string field_trial) { + explicit DummyExperiment(absl::string_view field_trial) { ParseFieldTrial({&target_rate, &max_buffer, &period}, field_trial); } }; diff --git a/rtc_base/experiments/struct_parameters_parser.cc b/rtc_base/experiments/struct_parameters_parser.cc index d62eb6f1ea..011df3eaba 100644 --- a/rtc_base/experiments/struct_parameters_parser.cc +++ b/rtc_base/experiments/struct_parameters_parser.cc @@ -11,13 +11,14 @@ #include +#include "absl/strings/string_view.h" #include "rtc_base/logging.h" namespace webrtc { namespace { size_t FindOrEnd(absl::string_view str, size_t start, char delimiter) { size_t pos = str.find(delimiter, start); - pos = (pos == std::string::npos) ? str.length() : pos; + pos = (pos == absl::string_view::npos) ? str.length() : pos; return pos; } } // namespace diff --git a/rtc_base/fake_ssl_identity.cc b/rtc_base/fake_ssl_identity.cc index 87ede73985..73c843a2e7 100644 --- a/rtc_base/fake_ssl_identity.cc +++ b/rtc_base/fake_ssl_identity.cc @@ -14,12 +14,13 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/checks.h" #include "rtc_base/message_digest.h" namespace rtc { -FakeSSLCertificate::FakeSSLCertificate(const std::string& pem_string) +FakeSSLCertificate::FakeSSLCertificate(absl::string_view pem_string) : pem_string_(pem_string), digest_algorithm_(DIGEST_SHA_1), expiration_time_(-1) {} @@ -51,8 +52,8 @@ void FakeSSLCertificate::SetCertificateExpirationTime(int64_t expiration_time) { expiration_time_ = expiration_time; } -void FakeSSLCertificate::set_digest_algorithm(const std::string& algorithm) { - digest_algorithm_ = algorithm; +void FakeSSLCertificate::set_digest_algorithm(absl::string_view algorithm) { + digest_algorithm_ = std::string(algorithm); } bool FakeSSLCertificate::GetSignatureDigestAlgorithm( @@ -61,7 +62,7 @@ bool FakeSSLCertificate::GetSignatureDigestAlgorithm( return true; } -bool FakeSSLCertificate::ComputeDigest(const std::string& algorithm, +bool FakeSSLCertificate::ComputeDigest(absl::string_view algorithm, unsigned char* digest, size_t size, size_t* length) const { @@ -70,7 +71,7 @@ bool FakeSSLCertificate::ComputeDigest(const std::string& algorithm, return (*length != 0); } -FakeSSLIdentity::FakeSSLIdentity(const std::string& pem_string) +FakeSSLIdentity::FakeSSLIdentity(absl::string_view pem_string) : FakeSSLIdentity(FakeSSLCertificate(pem_string)) {} FakeSSLIdentity::FakeSSLIdentity(const std::vector& pem_strings) { diff --git a/rtc_base/fake_ssl_identity.h b/rtc_base/fake_ssl_identity.h index 512baba9fb..2b4ae2e57a 100644 --- a/rtc_base/fake_ssl_identity.h +++ b/rtc_base/fake_ssl_identity.h @@ -14,6 +14,7 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/ssl_certificate.h" #include "rtc_base/ssl_identity.h" @@ -23,7 +24,7 @@ class FakeSSLCertificate : public SSLCertificate { public: // SHA-1 is the default digest algorithm because it is available in all build // configurations used for unit testing. - explicit FakeSSLCertificate(const std::string& pem_string); + explicit FakeSSLCertificate(absl::string_view pem_string); FakeSSLCertificate(const FakeSSLCertificate&); ~FakeSSLCertificate() override; @@ -34,14 +35,14 @@ class FakeSSLCertificate : public SSLCertificate { void ToDER(Buffer* der_buffer) const override; int64_t CertificateExpirationTime() const override; bool GetSignatureDigestAlgorithm(std::string* algorithm) const override; - bool ComputeDigest(const std::string& algorithm, + bool ComputeDigest(absl::string_view algorithm, unsigned char* digest, size_t size, size_t* length) const override; void SetCertificateExpirationTime(int64_t expiration_time); - void set_digest_algorithm(const std::string& algorithm); + void set_digest_algorithm(absl::string_view algorithm); private: std::string pem_string_; @@ -52,7 +53,7 @@ class FakeSSLCertificate : public SSLCertificate { class FakeSSLIdentity : public SSLIdentity { public: - explicit FakeSSLIdentity(const std::string& pem_string); + explicit FakeSSLIdentity(absl::string_view pem_string); // For a certificate chain. explicit FakeSSLIdentity(const std::vector& pem_strings); explicit FakeSSLIdentity(const FakeSSLCertificate& cert); diff --git a/rtc_base/file_rotating_stream.cc b/rtc_base/file_rotating_stream.cc index 5a004a937b..c529b5b1b4 100644 --- a/rtc_base/file_rotating_stream.cc +++ b/rtc_base/file_rotating_stream.cc @@ -14,6 +14,8 @@ #include #include +#include "absl/strings/string_view.h" + #if defined(WEBRTC_WIN) #include @@ -29,6 +31,7 @@ #include "absl/types/optional.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" +#include "rtc_base/strings/string_builder.h" // Note: We use fprintf for logging in the write paths of this stream to avoid // infinite loops when logging. @@ -39,54 +42,58 @@ namespace { const char kCallSessionLogPrefix[] = "webrtc_log"; -std::string AddTrailingPathDelimiterIfNeeded(std::string directory); +std::string AddTrailingPathDelimiterIfNeeded(absl::string_view directory); // `dir` must have a trailing delimiter. `prefix` must not include wild card // characters. -std::vector GetFilesWithPrefix(const std::string& directory, - const std::string& prefix); -bool DeleteFile(const std::string& file); -bool MoveFile(const std::string& old_file, const std::string& new_file); -bool IsFile(const std::string& file); -bool IsFolder(const std::string& file); -absl::optional GetFileSize(const std::string& file); +std::vector GetFilesWithPrefix(absl::string_view directory, + absl::string_view prefix); +bool DeleteFile(absl::string_view file); +bool MoveFile(absl::string_view old_file, absl::string_view new_file); +bool IsFile(absl::string_view file); +bool IsFolder(absl::string_view file); +absl::optional GetFileSize(absl::string_view file); #if defined(WEBRTC_WIN) -std::string AddTrailingPathDelimiterIfNeeded(std::string directory) { +std::string AddTrailingPathDelimiterIfNeeded(absl::string_view directory) { if (absl::EndsWith(directory, "\\")) { - return directory; + return std::string(directory); } - return directory + "\\"; + return std::string(directory) + "\\"; } -std::vector GetFilesWithPrefix(const std::string& directory, - const std::string& prefix) { +std::vector GetFilesWithPrefix(absl::string_view directory, + absl::string_view prefix) { RTC_DCHECK(absl::EndsWith(directory, "\\")); WIN32_FIND_DATAW data; HANDLE handle; - handle = ::FindFirstFileW(ToUtf16(directory + prefix + '*').c_str(), &data); + StringBuilder pattern_builder{directory}; + pattern_builder << prefix << "*"; + handle = ::FindFirstFileW(ToUtf16(pattern_builder.str()).c_str(), &data); if (handle == INVALID_HANDLE_VALUE) return {}; std::vector file_list; do { - file_list.emplace_back(directory + ToUtf8(data.cFileName)); + StringBuilder file_builder{directory}; + file_builder << ToUtf8(data.cFileName); + file_list.emplace_back(file_builder.Release()); } while (::FindNextFileW(handle, &data) == TRUE); ::FindClose(handle); return file_list; } -bool DeleteFile(const std::string& file) { +bool DeleteFile(absl::string_view file) { return ::DeleteFileW(ToUtf16(file).c_str()) != 0; } -bool MoveFile(const std::string& old_file, const std::string& new_file) { +bool MoveFile(absl::string_view old_file, absl::string_view new_file) { return ::MoveFileW(ToUtf16(old_file).c_str(), ToUtf16(new_file).c_str()) != 0; } -bool IsFile(const std::string& file) { +bool IsFile(absl::string_view file) { WIN32_FILE_ATTRIBUTE_DATA data = {0}; if (0 == ::GetFileAttributesExW(ToUtf16(file).c_str(), GetFileExInfoStandard, &data)) @@ -94,7 +101,7 @@ bool IsFile(const std::string& file) { return (data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0; } -bool IsFolder(const std::string& file) { +bool IsFolder(absl::string_view file) { WIN32_FILE_ATTRIBUTE_DATA data = {0}; if (0 == ::GetFileAttributesExW(ToUtf16(file).c_str(), GetFileExInfoStandard, &data)) @@ -103,7 +110,7 @@ bool IsFolder(const std::string& file) { FILE_ATTRIBUTE_DIRECTORY; } -absl::optional GetFileSize(const std::string& file) { +absl::optional GetFileSize(absl::string_view file) { WIN32_FILE_ATTRIBUTE_DATA data = {0}; if (::GetFileAttributesExW(ToUtf16(file).c_str(), GetFileExInfoStandard, &data) == 0) @@ -113,55 +120,57 @@ absl::optional GetFileSize(const std::string& file) { #else // defined(WEBRTC_WIN) -std::string AddTrailingPathDelimiterIfNeeded(std::string directory) { +std::string AddTrailingPathDelimiterIfNeeded(absl::string_view directory) { if (absl::EndsWith(directory, "/")) { - return directory; + return std::string(directory); } - return directory + "/"; + return std::string(directory) + "/"; } -std::vector GetFilesWithPrefix(const std::string& directory, - const std::string& prefix) { +std::vector GetFilesWithPrefix(absl::string_view directory, + absl::string_view prefix) { RTC_DCHECK(absl::EndsWith(directory, "/")); - DIR* dir = ::opendir(directory.c_str()); + std::string directory_str = std::string(directory); + DIR* dir = ::opendir(directory_str.c_str()); if (dir == nullptr) return {}; std::vector file_list; for (struct dirent* dirent = ::readdir(dir); dirent; dirent = ::readdir(dir)) { std::string name = dirent->d_name; - if (name.compare(0, prefix.size(), prefix) == 0) { - file_list.emplace_back(directory + name); + if (name.compare(0, prefix.size(), prefix.data(), prefix.size()) == 0) { + file_list.emplace_back(directory_str + name); } } ::closedir(dir); return file_list; } -bool DeleteFile(const std::string& file) { - return ::unlink(file.c_str()) == 0; +bool DeleteFile(absl::string_view file) { + return ::unlink(std::string(file).c_str()) == 0; } -bool MoveFile(const std::string& old_file, const std::string& new_file) { - return ::rename(old_file.c_str(), new_file.c_str()) == 0; +bool MoveFile(absl::string_view old_file, absl::string_view new_file) { + return ::rename(std::string(old_file).c_str(), + std::string(new_file).c_str()) == 0; } -bool IsFile(const std::string& file) { +bool IsFile(absl::string_view file) { struct stat st; - int res = ::stat(file.c_str(), &st); + int res = ::stat(std::string(file).c_str(), &st); // Treat symlinks, named pipes, etc. all as files. return res == 0 && !S_ISDIR(st.st_mode); } -bool IsFolder(const std::string& file) { +bool IsFolder(absl::string_view file) { struct stat st; - int res = ::stat(file.c_str(), &st); + int res = ::stat(std::string(file).c_str(), &st); return res == 0 && S_ISDIR(st.st_mode); } -absl::optional GetFileSize(const std::string& file) { +absl::optional GetFileSize(absl::string_view file) { struct stat st; - if (::stat(file.c_str(), &st) != 0) + if (::stat(std::string(file).c_str(), &st) != 0) return absl::nullopt; return st.st_size; } @@ -170,8 +179,8 @@ absl::optional GetFileSize(const std::string& file) { } // namespace -FileRotatingStream::FileRotatingStream(const std::string& dir_path, - const std::string& file_prefix, +FileRotatingStream::FileRotatingStream(absl::string_view dir_path, + absl::string_view file_prefix, size_t max_file_size, size_t num_files) : dir_path_(AddTrailingPathDelimiterIfNeeded(dir_path)), @@ -331,7 +340,7 @@ std::string FileRotatingStream::GetFilePath(size_t index, } CallSessionFileRotatingStream::CallSessionFileRotatingStream( - const std::string& dir_path, + absl::string_view dir_path, size_t max_total_log_size) : FileRotatingStream(dir_path, kCallSessionLogPrefix, @@ -376,8 +385,8 @@ size_t CallSessionFileRotatingStream::GetNumRotatingLogFiles( } FileRotatingStreamReader::FileRotatingStreamReader( - const std::string& dir_path, - const std::string& file_prefix) { + absl::string_view dir_path, + absl::string_view file_prefix) { file_names_ = GetFilesWithPrefix(AddTrailingPathDelimiterIfNeeded(dir_path), file_prefix); @@ -413,7 +422,7 @@ size_t FileRotatingStreamReader::ReadAll(void* buffer, size_t size) const { } CallSessionFileRotatingStreamReader::CallSessionFileRotatingStreamReader( - const std::string& dir_path) + absl::string_view dir_path) : FileRotatingStreamReader(dir_path, kCallSessionLogPrefix) {} } // namespace rtc diff --git a/rtc_base/file_rotating_stream.h b/rtc_base/file_rotating_stream.h index 6aaa0bd783..6ae2753098 100644 --- a/rtc_base/file_rotating_stream.h +++ b/rtc_base/file_rotating_stream.h @@ -17,6 +17,7 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/system/file_wrapper.h" namespace rtc { @@ -29,8 +30,8 @@ class FileRotatingStream { public: // Use this constructor for writing to a directory. Files in the directory // matching the prefix will be deleted on open. - FileRotatingStream(const std::string& dir_path, - const std::string& file_prefix, + FileRotatingStream(absl::string_view dir_path, + absl::string_view file_prefix, size_t max_file_size, size_t num_files); @@ -126,7 +127,7 @@ class CallSessionFileRotatingStream : public FileRotatingStream { // Use this constructor for writing to a directory. Files in the directory // matching what's used by the stream will be deleted. `max_total_log_size` // must be at least 4. - CallSessionFileRotatingStream(const std::string& dir_path, + CallSessionFileRotatingStream(absl::string_view dir_path, size_t max_total_log_size); ~CallSessionFileRotatingStream() override {} @@ -152,8 +153,8 @@ class CallSessionFileRotatingStream : public FileRotatingStream { // directory at construction time. class FileRotatingStreamReader { public: - FileRotatingStreamReader(const std::string& dir_path, - const std::string& file_prefix); + FileRotatingStreamReader(absl::string_view dir_path, + absl::string_view file_prefix); ~FileRotatingStreamReader(); size_t GetSize() const; size_t ReadAll(void* buffer, size_t size) const; @@ -164,7 +165,7 @@ class FileRotatingStreamReader { class CallSessionFileRotatingStreamReader : public FileRotatingStreamReader { public: - CallSessionFileRotatingStreamReader(const std::string& dir_path); + CallSessionFileRotatingStreamReader(absl::string_view dir_path); }; } // namespace rtc diff --git a/rtc_base/file_rotating_stream_unittest.cc b/rtc_base/file_rotating_stream_unittest.cc index 849b111148..a48dfe9a61 100644 --- a/rtc_base/file_rotating_stream_unittest.cc +++ b/rtc_base/file_rotating_stream_unittest.cc @@ -15,6 +15,7 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/arraysize.h" #include "test/gtest.h" #include "test/testsupport/file_utils.h" @@ -44,15 +45,15 @@ class MAYBE_FileRotatingStreamTest : public ::testing::Test { static const char* kFilePrefix; static const size_t kMaxFileSize; - void Init(const std::string& dir_name, - const std::string& file_prefix, + void Init(absl::string_view dir_name, + absl::string_view file_prefix, size_t max_file_size, size_t num_log_files, bool ensure_trailing_delimiter = true) { dir_path_ = webrtc::test::OutputPath(); // Append per-test output path in order to run within gtest parallel. - dir_path_.append(dir_name); + dir_path_.append(dir_name.begin(), dir_name.end()); if (ensure_trailing_delimiter) { dir_path_.append(webrtc::test::kPathDelimiter); } @@ -80,7 +81,7 @@ class MAYBE_FileRotatingStreamTest : public ::testing::Test { // end of stream result. void VerifyStreamRead(const char* expected_contents, const size_t expected_length, - const std::string& dir_path, + absl::string_view dir_path, const char* file_prefix) { FileRotatingStreamReader reader(dir_path, file_prefix); EXPECT_EQ(reader.GetSize(), expected_length); @@ -92,9 +93,10 @@ class MAYBE_FileRotatingStreamTest : public ::testing::Test { void VerifyFileContents(const char* expected_contents, const size_t expected_length, - const std::string& file_path) { + absl::string_view file_path) { std::unique_ptr buffer(new uint8_t[expected_length + 1]); - webrtc::FileWrapper f = webrtc::FileWrapper::OpenReadOnly(file_path); + webrtc::FileWrapper f = + webrtc::FileWrapper::OpenReadOnly(std::string(file_path)); ASSERT_TRUE(f.is_open()); size_t size_read = f.Read(buffer.get(), expected_length + 1); EXPECT_EQ(size_read, expected_length); @@ -255,11 +257,11 @@ TEST_F(MAYBE_FileRotatingStreamTest, GetFilePath) { class MAYBE_CallSessionFileRotatingStreamTest : public ::testing::Test { protected: - void Init(const std::string& dir_name, size_t max_total_log_size) { + void Init(absl::string_view dir_name, size_t max_total_log_size) { dir_path_ = webrtc::test::OutputPath(); // Append per-test output path in order to run within gtest parallel. - dir_path_.append(dir_name); + dir_path_.append(dir_name.begin(), dir_name.end()); dir_path_.append(webrtc::test::kPathDelimiter); ASSERT_TRUE(webrtc::test::CreateDir(dir_path_)); stream_.reset( @@ -285,7 +287,7 @@ class MAYBE_CallSessionFileRotatingStreamTest : public ::testing::Test { // end of stream result. void VerifyStreamRead(const char* expected_contents, const size_t expected_length, - const std::string& dir_path) { + absl::string_view dir_path) { CallSessionFileRotatingStreamReader reader(dir_path); EXPECT_EQ(reader.GetSize(), expected_length); std::unique_ptr buffer(new uint8_t[expected_length]); diff --git a/rtc_base/gunit.cc b/rtc_base/gunit.cc index 83ee8075fb..7cd60fe9ee 100644 --- a/rtc_base/gunit.cc +++ b/rtc_base/gunit.cc @@ -13,6 +13,7 @@ #include #include "absl/strings/match.h" +#include "absl/strings/string_view.h" ::testing::AssertionResult AssertStartsWith(const char* text_expr, const char* prefix_expr, @@ -30,9 +31,9 @@ ::testing::AssertionResult AssertStringContains(const char* str_expr, const char* substr_expr, - const std::string& str, - const std::string& substr) { - if (str.find(substr) != std::string::npos) { + absl::string_view str, + absl::string_view substr) { + if (str.find(substr) != absl::string_view::npos) { return ::testing::AssertionSuccess(); } else { return ::testing::AssertionFailure() diff --git a/rtc_base/gunit.h b/rtc_base/gunit.h index dedf3ee067..ac99c7ac4d 100644 --- a/rtc_base/gunit.h +++ b/rtc_base/gunit.h @@ -11,6 +11,7 @@ #ifndef RTC_BASE_GUNIT_H_ #define RTC_BASE_GUNIT_H_ +#include "absl/strings/string_view.h" #include "rtc_base/fake_clock.h" #include "rtc_base/logging.h" #include "rtc_base/thread.h" @@ -162,7 +163,7 @@ testing::AssertionResult AssertStartsWith(const char* text_expr, // Usage: EXPECT_PRED_FORMAT2(AssertStringContains, str, "substring"); testing::AssertionResult AssertStringContains(const char* str_expr, const char* substr_expr, - const std::string& str, - const std::string& substr); + absl::string_view str, + absl::string_view substr); #endif // RTC_BASE_GUNIT_H_ diff --git a/rtc_base/helpers.cc b/rtc_base/helpers.cc index 64cab10335..337239894a 100644 --- a/rtc_base/helpers.cc +++ b/rtc_base/helpers.cc @@ -16,6 +16,7 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/checks.h" #include "rtc_base/logging.h" @@ -145,10 +146,8 @@ bool CreateRandomString(size_t len, std::string* str) { return CreateRandomString(len, kBase64, 64, str); } -bool CreateRandomString(size_t len, - const std::string& table, - std::string* str) { - return CreateRandomString(len, table.c_str(), static_cast(table.size()), +bool CreateRandomString(size_t len, absl::string_view table, std::string* str) { + return CreateRandomString(len, table.data(), static_cast(table.size()), str); } diff --git a/rtc_base/helpers.h b/rtc_base/helpers.h index 2fd2fc5218..c214f5212f 100644 --- a/rtc_base/helpers.h +++ b/rtc_base/helpers.h @@ -16,6 +16,7 @@ #include +#include "absl/strings/string_view.h" #include "rtc_base/system/rtc_export.h" namespace rtc { @@ -42,7 +43,7 @@ RTC_EXPORT bool CreateRandomString(size_t length, std::string* str); // For ease of implementation, the function requires that the table // size evenly divide 256; otherwise, it returns false. RTC_EXPORT bool CreateRandomString(size_t length, - const std::string& table, + absl::string_view table, std::string* str); // Generates (cryptographically) random data of the given length. diff --git a/rtc_base/http_common.cc b/rtc_base/http_common.cc index 0d7832264b..88639a7c70 100644 --- a/rtc_base/http_common.cc +++ b/rtc_base/http_common.cc @@ -10,6 +10,8 @@ #include +#include "absl/strings/string_view.h" + #if defined(WEBRTC_WIN) #include #include @@ -185,7 +187,7 @@ void HttpParseAttributes(const char* data, } bool HttpHasAttribute(const HttpAttributeList& attributes, - const std::string& name, + absl::string_view name, std::string* value) { for (HttpAttributeList::const_iterator it = attributes.begin(); it != attributes.end(); ++it) { @@ -213,7 +215,7 @@ bool HttpHasNthAttribute(HttpAttributeList& attributes, return true; } -std::string quote(const std::string& str) { +std::string quote(absl::string_view str) { std::string result; result.push_back('"'); for (size_t i = 0; i < str.size(); ++i) { @@ -232,7 +234,7 @@ struct NegotiateAuthContext : public HttpAuthContext { size_t steps; bool specified_credentials; - NegotiateAuthContext(const std::string& auth, CredHandle c1, CtxtHandle c2) + NegotiateAuthContext(absl::string_view auth, CredHandle c1, CtxtHandle c2) : HttpAuthContext(auth), cred(c1), ctx(c2), @@ -251,9 +253,9 @@ struct NegotiateAuthContext : public HttpAuthContext { HttpAuthResult HttpAuthenticate(const char* challenge, size_t len, const SocketAddress& server, - const std::string& method, - const std::string& uri, - const std::string& username, + absl::string_view method, + absl::string_view uri, + absl::string_view username, const CryptString& password, HttpAuthContext*& context, std::string& response, @@ -326,7 +328,7 @@ HttpAuthResult HttpAuthenticate(const char* challenge, pos += strcpyn(sensitive + pos, len - pos, ":"); password.CopyTo(sensitive + pos, true); - std::string A2 = method + ":" + uri; + std::string A2 = std::string(method) + ":" + std::string(uri); std::string middle; if (has_qop) { qop = "auth"; @@ -459,11 +461,11 @@ HttpAuthResult HttpAuthenticate(const char* challenge, size_t len = password.GetLength() + 1; char* sensitive = new char[len]; password.CopyTo(sensitive, true); - std::string::size_type pos = username.find('\\'); - if (pos == std::string::npos) { + absl::string_view::size_type pos = username.find('\\'); + if (pos == absl::string_view::npos) { auth_id.UserLength = static_cast( std::min(sizeof(userbuf) - 1, username.size())); - memcpy(userbuf, username.c_str(), auth_id.UserLength); + memcpy(userbuf, username.data(), auth_id.UserLength); userbuf[auth_id.UserLength] = 0; auth_id.DomainLength = 0; domainbuf[auth_id.DomainLength] = 0; @@ -474,11 +476,11 @@ HttpAuthResult HttpAuthenticate(const char* challenge, } else { auth_id.UserLength = static_cast( std::min(sizeof(userbuf) - 1, username.size() - pos - 1)); - memcpy(userbuf, username.c_str() + pos + 1, auth_id.UserLength); + memcpy(userbuf, username.data() + pos + 1, auth_id.UserLength); userbuf[auth_id.UserLength] = 0; auth_id.DomainLength = static_cast(std::min(sizeof(domainbuf) - 1, pos)); - memcpy(domainbuf, username.c_str(), auth_id.DomainLength); + memcpy(domainbuf, username.data(), auth_id.DomainLength); domainbuf[auth_id.DomainLength] = 0; auth_id.PasswordLength = static_cast( std::min(sizeof(passbuf) - 1, password.GetLength())); diff --git a/rtc_base/http_common.h b/rtc_base/http_common.h index edf161fb4c..d287bd5d7c 100644 --- a/rtc_base/http_common.h +++ b/rtc_base/http_common.h @@ -13,6 +13,8 @@ #include +#include "absl/strings/string_view.h" + namespace rtc { class CryptString; @@ -24,7 +26,7 @@ class SocketAddress; struct HttpAuthContext { std::string auth_method; - HttpAuthContext(const std::string& auth) : auth_method(auth) {} + HttpAuthContext(absl::string_view auth) : auth_method(auth) {} virtual ~HttpAuthContext() {} }; @@ -37,9 +39,9 @@ enum HttpAuthResult { HAR_RESPONSE, HAR_IGNORE, HAR_CREDENTIALS, HAR_ERROR }; HttpAuthResult HttpAuthenticate(const char* challenge, size_t len, const SocketAddress& server, - const std::string& method, - const std::string& uri, - const std::string& username, + absl::string_view method, + absl::string_view uri, + absl::string_view username, const CryptString& password, HttpAuthContext*& context, std::string& response, diff --git a/rtc_base/ip_address.cc b/rtc_base/ip_address.cc index 86f42e0bf9..5ebb402145 100644 --- a/rtc_base/ip_address.cc +++ b/rtc_base/ip_address.cc @@ -11,6 +11,8 @@ #if defined(WEBRTC_POSIX) #include #include + +#include "absl/strings/string_view.h" #ifdef OPENBSD #include #endif @@ -276,14 +278,15 @@ bool IPFromAddrInfo(struct addrinfo* info, IPAddress* out) { return false; } -bool IPFromString(const std::string& str, IPAddress* out) { +bool IPFromString(absl::string_view str, IPAddress* out) { if (!out) { return false; } in_addr addr; - if (rtc::inet_pton(AF_INET, str.c_str(), &addr) == 0) { + const std::string str_copy = std::string(str); + if (rtc::inet_pton(AF_INET, str_copy.c_str(), &addr) == 0) { in6_addr addr6; - if (rtc::inet_pton(AF_INET6, str.c_str(), &addr6) == 0) { + if (rtc::inet_pton(AF_INET6, str_copy.c_str(), &addr6) == 0) { *out = IPAddress(); return false; } @@ -294,7 +297,7 @@ bool IPFromString(const std::string& str, IPAddress* out) { return true; } -bool IPFromString(const std::string& str, int flags, InterfaceAddress* out) { +bool IPFromString(absl::string_view str, int flags, InterfaceAddress* out) { IPAddress ip; if (!IPFromString(str, &ip)) { return false; diff --git a/rtc_base/ip_address.h b/rtc_base/ip_address.h index 8725417393..58ad8ba4b2 100644 --- a/rtc_base/ip_address.h +++ b/rtc_base/ip_address.h @@ -16,6 +16,8 @@ #include #include #include + +#include "absl/strings/string_view.h" #endif #if defined(WEBRTC_WIN) #include @@ -29,8 +31,8 @@ #if defined(WEBRTC_WIN) #include "rtc_base/win32.h" #endif +#include "absl/strings/string_view.h" #include "rtc_base/system/rtc_export.h" - namespace rtc { enum IPv6AddressFlag { @@ -155,8 +157,8 @@ class RTC_EXPORT InterfaceAddress : public IPAddress { }; bool IPFromAddrInfo(struct addrinfo* info, IPAddress* out); -RTC_EXPORT bool IPFromString(const std::string& str, IPAddress* out); -RTC_EXPORT bool IPFromString(const std::string& str, +RTC_EXPORT bool IPFromString(absl::string_view str, IPAddress* out); +RTC_EXPORT bool IPFromString(absl::string_view str, int flags, InterfaceAddress* out); bool IPIsAny(const IPAddress& ip); diff --git a/rtc_base/ip_address_unittest.cc b/rtc_base/ip_address_unittest.cc index f94649cfee..9ca05c95fe 100644 --- a/rtc_base/ip_address_unittest.cc +++ b/rtc_base/ip_address_unittest.cc @@ -10,6 +10,7 @@ #include "rtc_base/ip_address.h" +#include "absl/strings/string_view.h" #include "test/gtest.h" namespace rtc { @@ -118,7 +119,7 @@ bool AreEqual(const IPAddress& addr, const IPAddress& addr2) { return true; } -bool BrokenIPStringFails(const std::string& broken) { +bool BrokenIPStringFails(absl::string_view broken) { IPAddress addr(0); // Intentionally make it v4. if (IPFromString(kIPv4BrokenString1, &addr)) { return false; @@ -126,13 +127,13 @@ bool BrokenIPStringFails(const std::string& broken) { return addr.family() == AF_UNSPEC; } -bool CheckMaskCount(const std::string& mask, int expected_length) { +bool CheckMaskCount(absl::string_view mask, int expected_length) { IPAddress addr; return IPFromString(mask, &addr) && (expected_length == CountIPMaskBits(addr)); } -bool TryInvalidMaskCount(const std::string& mask) { +bool TryInvalidMaskCount(absl::string_view mask) { // We don't care about the result at all, but we do want to know if // CountIPMaskBits is going to crash or infinite loop or something. IPAddress addr; @@ -143,9 +144,9 @@ bool TryInvalidMaskCount(const std::string& mask) { return true; } -bool CheckTruncateIP(const std::string& initial, +bool CheckTruncateIP(absl::string_view initial, int truncate_length, - const std::string& expected_result) { + absl::string_view expected_result) { IPAddress addr, expected; IPFromString(initial, &addr); IPFromString(expected_result, &expected); diff --git a/rtc_base/mdns_responder_interface.h b/rtc_base/mdns_responder_interface.h index 64fb3cebff..14ef9a202d 100644 --- a/rtc_base/mdns_responder_interface.h +++ b/rtc_base/mdns_responder_interface.h @@ -14,6 +14,7 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/ip_address.h" namespace webrtc { @@ -23,7 +24,7 @@ namespace webrtc { class MdnsResponderInterface { public: using NameCreatedCallback = - std::function; + std::function; using NameRemovedCallback = std::function; MdnsResponderInterface() = default; diff --git a/rtc_base/message_digest.cc b/rtc_base/message_digest.cc index 62b4a6bc97..3b39cf9f18 100644 --- a/rtc_base/message_digest.cc +++ b/rtc_base/message_digest.cc @@ -15,6 +15,7 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/openssl_digest.h" #include "rtc_base/string_encode.h" @@ -30,7 +31,7 @@ const char DIGEST_SHA_512[] = "sha-512"; static const size_t kBlockSize = 64; // valid for SHA-256 and down -MessageDigest* MessageDigestFactory::Create(const std::string& alg) { +MessageDigest* MessageDigestFactory::Create(absl::string_view alg) { MessageDigest* digest = new OpenSSLDigest(alg); if (digest->Size() == 0) { // invalid algorithm delete digest; @@ -39,7 +40,7 @@ MessageDigest* MessageDigestFactory::Create(const std::string& alg) { return digest; } -bool IsFips180DigestAlgorithm(const std::string& alg) { +bool IsFips180DigestAlgorithm(absl::string_view alg) { // These are the FIPS 180 algorithms. According to RFC 4572 Section 5, // "Self-signed certificates (for which legacy certificates are not a // consideration) MUST use one of the FIPS 180 algorithms (SHA-1, @@ -59,7 +60,7 @@ size_t ComputeDigest(MessageDigest* digest, return digest->Finish(output, out_len); } -size_t ComputeDigest(const std::string& alg, +size_t ComputeDigest(absl::string_view alg, const void* input, size_t in_len, void* output, @@ -69,15 +70,15 @@ size_t ComputeDigest(const std::string& alg, : 0; } -std::string ComputeDigest(MessageDigest* digest, const std::string& input) { +std::string ComputeDigest(MessageDigest* digest, absl::string_view input) { std::unique_ptr output(new char[digest->Size()]); ComputeDigest(digest, input.data(), input.size(), output.get(), digest->Size()); return hex_encode(output.get(), digest->Size()); } -bool ComputeDigest(const std::string& alg, - const std::string& input, +bool ComputeDigest(absl::string_view alg, + absl::string_view input, std::string* output) { std::unique_ptr digest(MessageDigestFactory::Create(alg)); if (!digest) { @@ -87,7 +88,7 @@ bool ComputeDigest(const std::string& alg, return true; } -std::string ComputeDigest(const std::string& alg, const std::string& input) { +std::string ComputeDigest(absl::string_view alg, absl::string_view input) { std::string output; ComputeDigest(alg, input, &output); return output; @@ -135,7 +136,7 @@ size_t ComputeHmac(MessageDigest* digest, return digest->Finish(output, out_len); } -size_t ComputeHmac(const std::string& alg, +size_t ComputeHmac(absl::string_view alg, const void* key, size_t key_len, const void* input, @@ -151,17 +152,17 @@ size_t ComputeHmac(const std::string& alg, } std::string ComputeHmac(MessageDigest* digest, - const std::string& key, - const std::string& input) { + absl::string_view key, + absl::string_view input) { std::unique_ptr output(new char[digest->Size()]); ComputeHmac(digest, key.data(), key.size(), input.data(), input.size(), output.get(), digest->Size()); return hex_encode(output.get(), digest->Size()); } -bool ComputeHmac(const std::string& alg, - const std::string& key, - const std::string& input, +bool ComputeHmac(absl::string_view alg, + absl::string_view key, + absl::string_view input, std::string* output) { std::unique_ptr digest(MessageDigestFactory::Create(alg)); if (!digest) { @@ -171,9 +172,9 @@ bool ComputeHmac(const std::string& alg, return true; } -std::string ComputeHmac(const std::string& alg, - const std::string& key, - const std::string& input) { +std::string ComputeHmac(absl::string_view alg, + absl::string_view key, + absl::string_view input) { std::string output; ComputeHmac(alg, key, input, &output); return output; diff --git a/rtc_base/message_digest.h b/rtc_base/message_digest.h index 02e0bfd561..632b9af075 100644 --- a/rtc_base/message_digest.h +++ b/rtc_base/message_digest.h @@ -15,6 +15,8 @@ #include +#include "absl/strings/string_view.h" + namespace rtc { // Definitions for the digest algorithms. @@ -42,12 +44,12 @@ class MessageDigest { // A factory class for creating digest objects. class MessageDigestFactory { public: - static MessageDigest* Create(const std::string& alg); + static MessageDigest* Create(absl::string_view alg); }; // A check that an algorithm is in a list of approved digest algorithms // from RFC 4572 (FIPS 180). -bool IsFips180DigestAlgorithm(const std::string& alg); +bool IsFips180DigestAlgorithm(absl::string_view alg); // Functions to create hashes. @@ -63,25 +65,25 @@ size_t ComputeDigest(MessageDigest* digest, // Like the previous function, but creates a digest implementation based on // the desired digest name `alg`, e.g. DIGEST_SHA_1. Returns 0 if there is no // digest with the given name. -size_t ComputeDigest(const std::string& alg, +size_t ComputeDigest(absl::string_view alg, const void* input, size_t in_len, void* output, size_t out_len); // Computes the hash of `input` using the `digest` hash implementation, and // returns it as a hex-encoded string. -std::string ComputeDigest(MessageDigest* digest, const std::string& input); +std::string ComputeDigest(MessageDigest* digest, absl::string_view input); // Like the previous function, but creates a digest implementation based on // the desired digest name `alg`, e.g. DIGEST_SHA_1. Returns empty string if // there is no digest with the given name. -std::string ComputeDigest(const std::string& alg, const std::string& input); +std::string ComputeDigest(absl::string_view alg, absl::string_view input); // Like the previous function, but returns an explicit result code. -bool ComputeDigest(const std::string& alg, - const std::string& input, +bool ComputeDigest(absl::string_view alg, + absl::string_view input, std::string* output); // Shorthand way to compute a hex-encoded hash using MD5. -inline std::string MD5(const std::string& input) { +inline std::string MD5(absl::string_view input) { return ComputeDigest(DIGEST_MD5, input); } @@ -102,7 +104,7 @@ size_t ComputeHmac(MessageDigest* digest, // Like the previous function, but creates a digest implementation based on // the desired digest name `alg`, e.g. DIGEST_SHA_1. Returns 0 if there is no // digest with the given name. -size_t ComputeHmac(const std::string& alg, +size_t ComputeHmac(absl::string_view alg, const void* key, size_t key_len, const void* input, @@ -112,18 +114,18 @@ size_t ComputeHmac(const std::string& alg, // Computes the HMAC of `input` using the `digest` hash implementation and `key` // to key the HMAC, and returns it as a hex-encoded string. std::string ComputeHmac(MessageDigest* digest, - const std::string& key, - const std::string& input); + absl::string_view key, + absl::string_view input); // Like the previous function, but creates a digest implementation based on // the desired digest name `alg`, e.g. DIGEST_SHA_1. Returns empty string if // there is no digest with the given name. -std::string ComputeHmac(const std::string& alg, - const std::string& key, - const std::string& input); +std::string ComputeHmac(absl::string_view alg, + absl::string_view key, + absl::string_view input); // Like the previous function, but returns an explicit result code. -bool ComputeHmac(const std::string& alg, - const std::string& key, - const std::string& input, +bool ComputeHmac(absl::string_view alg, + absl::string_view key, + absl::string_view input, std::string* output); } // namespace rtc diff --git a/rtc_base/net_helper.cc b/rtc_base/net_helper.cc index 893b500d56..4afee7bfb0 100644 --- a/rtc_base/net_helper.cc +++ b/rtc_base/net_helper.cc @@ -10,6 +10,8 @@ #include "rtc_base/net_helper.h" +#include "absl/strings/string_view.h" + namespace cricket { const char UDP_PROTOCOL_NAME[] = "udp"; @@ -17,7 +19,7 @@ const char TCP_PROTOCOL_NAME[] = "tcp"; const char SSLTCP_PROTOCOL_NAME[] = "ssltcp"; const char TLS_PROTOCOL_NAME[] = "tls"; -int GetProtocolOverhead(const std::string& protocol) { +int GetProtocolOverhead(absl::string_view protocol) { if (protocol == TCP_PROTOCOL_NAME || protocol == SSLTCP_PROTOCOL_NAME) { return kTcpHeaderSize; } else if (protocol == UDP_PROTOCOL_NAME) { diff --git a/rtc_base/net_helper.h b/rtc_base/net_helper.h index 9abbbdefb2..758c0faad9 100644 --- a/rtc_base/net_helper.h +++ b/rtc_base/net_helper.h @@ -12,6 +12,8 @@ #include +#include "absl/strings/string_view.h" + // This header contains helper functions and constants used by different types // of transports. namespace cricket { @@ -25,7 +27,7 @@ constexpr int kTcpHeaderSize = 20; constexpr int kUdpHeaderSize = 8; // Get the transport layer overhead per packet based on the protocol. -int GetProtocolOverhead(const std::string& protocol); +int GetProtocolOverhead(absl::string_view protocol); } // namespace cricket diff --git a/rtc_base/network.cc b/rtc_base/network.cc index 295d39c5d9..52026308b7 100644 --- a/rtc_base/network.cc +++ b/rtc_base/network.cc @@ -10,6 +10,8 @@ #include "rtc_base/network.h" +#include "absl/strings/string_view.h" + #if defined(WEBRTC_POSIX) #include #endif // WEBRTC_POSIX @@ -190,7 +192,7 @@ const char kPublicIPv4Host[] = "8.8.8.8"; const char kPublicIPv6Host[] = "2001:4860:4860::8888"; const int kPublicPort = 53; // DNS port. -std::string MakeNetworkKey(const std::string& name, +std::string MakeNetworkKey(absl::string_view name, const IPAddress& prefix, int prefix_length) { rtc::StringBuilder ost; @@ -1055,8 +1057,8 @@ NetworkBindingResult BasicNetworkManager::BindSocketToNetwork( return network_monitor_->BindSocketToNetwork(socket_fd, address, if_name); } -Network::Network(const std::string& name, - const std::string& desc, +Network::Network(absl::string_view name, + absl::string_view desc, const IPAddress& prefix, int prefix_length) : name_(name), @@ -1073,8 +1075,8 @@ Network::Network(const std::string& name, add_network_cost_to_vpn_( webrtc::field_trial::IsEnabled("WebRTC-AddNetworkCostToVpn")) {} -Network::Network(const std::string& name, - const std::string& desc, +Network::Network(absl::string_view name, + absl::string_view desc, const IPAddress& prefix, int prefix_length, AdapterType type) diff --git a/rtc_base/network.h b/rtc_base/network.h index 83a2f7d272..bf14bef0e4 100644 --- a/rtc_base/network.h +++ b/rtc_base/network.h @@ -19,6 +19,7 @@ #include #include +#include "absl/strings/string_view.h" #include "api/array_view.h" #include "api/sequence_checker.h" #include "rtc_base/ip_address.h" @@ -51,7 +52,7 @@ const int kDefaultNetworkIgnoreMask = ADAPTER_TYPE_LOOPBACK; // Makes a string key for this network. Used in the network manager's maps. // Network objects are keyed on interface name, network prefix and the // length of that prefix. -std::string MakeNetworkKey(const std::string& name, +std::string MakeNetworkKey(absl::string_view name, const IPAddress& prefix, int prefix_length); @@ -350,13 +351,13 @@ class RTC_EXPORT BasicNetworkManager : public NetworkManagerBase, // Represents a Unix-type network interface, with a name and single address. class RTC_EXPORT Network { public: - Network(const std::string& name, - const std::string& description, + Network(absl::string_view name, + absl::string_view description, const IPAddress& prefix, int prefix_length); - Network(const std::string& name, - const std::string& description, + Network(absl::string_view name, + absl::string_view description, const IPAddress& prefix, int prefix_length, AdapterType type); diff --git a/rtc_base/network_monitor.h b/rtc_base/network_monitor.h index c0eea1ff52..72571d1497 100644 --- a/rtc_base/network_monitor.h +++ b/rtc_base/network_monitor.h @@ -14,6 +14,7 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/network_constants.h" namespace rtc { @@ -78,12 +79,12 @@ class NetworkMonitorInterface { virtual void Start() = 0; virtual void Stop() = 0; - virtual AdapterType GetAdapterType(const std::string& interface_name) = 0; + virtual AdapterType GetAdapterType(absl::string_view interface_name) = 0; virtual AdapterType GetVpnUnderlyingAdapterType( - const std::string& interface_name) = 0; + absl::string_view interface_name) = 0; virtual NetworkPreference GetNetworkPreference( - const std::string& interface_name) = 0; + absl::string_view interface_name) = 0; // Does `this` NetworkMonitorInterface implement BindSocketToNetwork? // Only Android returns true. @@ -94,7 +95,7 @@ class NetworkMonitorInterface { virtual NetworkBindingResult BindSocketToNetwork( int socket_fd, const IPAddress& address, - const std::string& interface_name) { + absl::string_view interface_name) { return NetworkBindingResult::NOT_IMPLEMENTED; } @@ -107,7 +108,7 @@ class NetworkMonitorInterface { // These specific use case this was added for was a phone with two SIM cards, // where attempting to use all interfaces returned from getifaddrs caused the // connection to be dropped. - virtual bool IsAdapterAvailable(const std::string& interface_name) { + virtual bool IsAdapterAvailable(absl::string_view interface_name) { return true; } diff --git a/rtc_base/network_unittest.cc b/rtc_base/network_unittest.cc index 5635f5d868..e622ca334a 100644 --- a/rtc_base/network_unittest.cc +++ b/rtc_base/network_unittest.cc @@ -18,6 +18,7 @@ #include "absl/algorithm/container.h" #include "absl/strings/match.h" +#include "absl/strings/string_view.h" #include "rtc_base/checks.h" #include "rtc_base/net_helpers.h" #include "rtc_base/network_monitor.h" @@ -45,7 +46,7 @@ namespace rtc { namespace { -IPAddress IPFromString(const std::string& str) { +IPAddress IPFromString(absl::string_view str) { IPAddress ip; RTC_CHECK(IPFromString(str, &ip)); return ip; @@ -56,7 +57,7 @@ class FakeNetworkMonitor : public NetworkMonitorInterface { void Start() override { started_ = true; } void Stop() override { started_ = false; } bool started() { return started_; } - AdapterType GetAdapterType(const std::string& if_name) override { + AdapterType GetAdapterType(absl::string_view if_name) override { // Note that the name matching rules are different from the // GetAdapterTypeFromName in NetworkManager. if (absl::StartsWith(if_name, "wifi")) { @@ -67,14 +68,14 @@ class FakeNetworkMonitor : public NetworkMonitorInterface { } return ADAPTER_TYPE_UNKNOWN; } - AdapterType GetVpnUnderlyingAdapterType(const std::string& if_name) override { + AdapterType GetVpnUnderlyingAdapterType(absl::string_view if_name) override { return ADAPTER_TYPE_UNKNOWN; } - NetworkPreference GetNetworkPreference(const std::string& if_name) override { + NetworkPreference GetNetworkPreference(absl::string_view if_name) override { return NetworkPreference::NEUTRAL; } - bool IsAdapterAvailable(const std::string& if_name) override { + bool IsAdapterAvailable(absl::string_view if_name) override { return absl::c_count(unavailable_adapters_, if_name) == 0; } @@ -85,16 +86,15 @@ class FakeNetworkMonitor : public NetworkMonitorInterface { bool SupportsBindSocketToNetwork() const override { return true; } - NetworkBindingResult BindSocketToNetwork( - int socket_fd, - const IPAddress& address, - const std::string& if_name) override { + NetworkBindingResult BindSocketToNetwork(int socket_fd, + const IPAddress& address, + absl::string_view if_name) override { if (absl::c_count(addresses_, address) > 0) { return NetworkBindingResult::SUCCESS; } for (auto const& iter : adapters_) { - if (if_name.find(iter) != std::string::npos) { + if (if_name.find(iter) != absl::string_view::npos) { return NetworkBindingResult::SUCCESS; } } @@ -209,7 +209,7 @@ class NetworkTest : public ::testing::Test, public sigslot::has_slots<> { include_ignored, networks); } - struct sockaddr_in6* CreateIpv6Addr(const std::string& ip_string, + struct sockaddr_in6* CreateIpv6Addr(absl::string_view ip_string, uint32_t scope_id) { struct sockaddr_in6* ipv6_addr = static_cast(malloc(sizeof(struct sockaddr_in6))); @@ -225,8 +225,8 @@ class NetworkTest : public ::testing::Test, public sigslot::has_slots<> { // Pointers created here need to be released via ReleaseIfAddrs. struct ifaddrs* AddIpv6Address(struct ifaddrs* list, char* if_name, - const std::string& ipv6_address, - const std::string& ipv6_netmask, + absl::string_view ipv6_address, + absl::string_view ipv6_netmask, uint32_t scope_id) { struct ifaddrs* if_addr = new struct ifaddrs; memset(if_addr, 0, sizeof(struct ifaddrs)); @@ -241,8 +241,8 @@ class NetworkTest : public ::testing::Test, public sigslot::has_slots<> { } struct ifaddrs* InstallIpv6Network(char* if_name, - const std::string& ipv6_address, - const std::string& ipv6_mask, + absl::string_view ipv6_address, + absl::string_view ipv6_mask, BasicNetworkManager& network_manager) { ifaddrs* addr_list = nullptr; addr_list = AddIpv6Address(addr_list, if_name, ipv6_address, ipv6_mask, 0); @@ -254,7 +254,7 @@ class NetworkTest : public ::testing::Test, public sigslot::has_slots<> { return addr_list; } - struct sockaddr_in* CreateIpv4Addr(const std::string& ip_string) { + struct sockaddr_in* CreateIpv4Addr(absl::string_view ip_string) { struct sockaddr_in* ipv4_addr = static_cast(malloc(sizeof(struct sockaddr_in))); memset(ipv4_addr, 0, sizeof(struct sockaddr_in)); @@ -268,8 +268,8 @@ class NetworkTest : public ::testing::Test, public sigslot::has_slots<> { // Pointers created here need to be released via ReleaseIfAddrs. struct ifaddrs* AddIpv4Address(struct ifaddrs* list, char* if_name, - const std::string& ipv4_address, - const std::string& ipv4_netmask) { + absl::string_view ipv4_address, + absl::string_view ipv4_netmask) { struct ifaddrs* if_addr = new struct ifaddrs; memset(if_addr, 0, sizeof(struct ifaddrs)); if_addr->ifa_name = if_name; @@ -283,8 +283,8 @@ class NetworkTest : public ::testing::Test, public sigslot::has_slots<> { } struct ifaddrs* InstallIpv4Network(char* if_name, - const std::string& ipv4_address, - const std::string& ipv4_mask, + absl::string_view ipv4_address, + absl::string_view ipv4_mask, BasicNetworkManager& network_manager) { ifaddrs* addr_list = nullptr; addr_list = AddIpv4Address(addr_list, if_name, ipv4_address, ipv4_mask); diff --git a/rtc_base/openssl_adapter.cc b/rtc_base/openssl_adapter.cc index bc10e619eb..dc9aefaa8e 100644 --- a/rtc_base/openssl_adapter.cc +++ b/rtc_base/openssl_adapter.cc @@ -13,6 +13,8 @@ #include #include #include + +#include "absl/strings/string_view.h" #ifdef OPENSSL_IS_BORINGSSL #include #endif @@ -744,7 +746,7 @@ void OpenSSLAdapter::OnCloseEvent(Socket* socket, int err) { AsyncSocketAdapter::OnCloseEvent(socket, err); } -bool OpenSSLAdapter::SSLPostConnectionCheck(SSL* ssl, const std::string& host) { +bool OpenSSLAdapter::SSLPostConnectionCheck(SSL* ssl, absl::string_view host) { bool is_valid_cert_name = openssl::VerifyPeerCertMatchesHost(ssl, host) && (SSL_get_verify_result(ssl) == X509_V_OK || custom_cert_verifier_status_); diff --git a/rtc_base/openssl_adapter.h b/rtc_base/openssl_adapter.h index 7e1f87b8ab..942d1fef12 100644 --- a/rtc_base/openssl_adapter.h +++ b/rtc_base/openssl_adapter.h @@ -19,6 +19,7 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/buffer.h" #include "rtc_base/message_handler.h" #ifdef OPENSSL_IS_BORINGSSL @@ -116,7 +117,7 @@ class OpenSSLAdapter final : public SSLAdapter, // an output parameter filled with the result of SSL_get_error. int DoSslWrite(const void* pv, size_t cb, int* error); void OnMessage(Message* msg) override; - bool SSLPostConnectionCheck(SSL* ssl, const std::string& host); + bool SSLPostConnectionCheck(SSL* ssl, absl::string_view host); #if !defined(NDEBUG) // In debug builds, logs info about the state of the SSL connection. diff --git a/rtc_base/openssl_digest.cc b/rtc_base/openssl_digest.cc index 1cf5bc09b4..bbf39570f6 100644 --- a/rtc_base/openssl_digest.cc +++ b/rtc_base/openssl_digest.cc @@ -10,12 +10,13 @@ #include "rtc_base/openssl_digest.h" +#include "absl/strings/string_view.h" #include "rtc_base/checks.h" // RTC_DCHECK, RTC_CHECK #include "rtc_base/openssl.h" namespace rtc { -OpenSSLDigest::OpenSSLDigest(const std::string& algorithm) { +OpenSSLDigest::OpenSSLDigest(absl::string_view algorithm) { ctx_ = EVP_MD_CTX_new(); RTC_CHECK(ctx_ != nullptr); EVP_MD_CTX_init(ctx_); @@ -55,7 +56,7 @@ size_t OpenSSLDigest::Finish(void* buf, size_t len) { return md_len; } -bool OpenSSLDigest::GetDigestEVP(const std::string& algorithm, +bool OpenSSLDigest::GetDigestEVP(absl::string_view algorithm, const EVP_MD** mdp) { const EVP_MD* md; if (algorithm == DIGEST_MD5) { @@ -105,8 +106,7 @@ bool OpenSSLDigest::GetDigestName(const EVP_MD* md, std::string* algorithm) { return true; } -bool OpenSSLDigest::GetDigestSize(const std::string& algorithm, - size_t* length) { +bool OpenSSLDigest::GetDigestSize(absl::string_view algorithm, size_t* length) { const EVP_MD* md; if (!GetDigestEVP(algorithm, &md)) return false; diff --git a/rtc_base/openssl_digest.h b/rtc_base/openssl_digest.h index 6da01a0ded..c6cc3bb86d 100644 --- a/rtc_base/openssl_digest.h +++ b/rtc_base/openssl_digest.h @@ -16,6 +16,7 @@ #include +#include "absl/strings/string_view.h" #include "rtc_base/message_digest.h" namespace rtc { @@ -24,7 +25,7 @@ namespace rtc { class OpenSSLDigest final : public MessageDigest { public: // Creates an OpenSSLDigest with `algorithm` as the hash algorithm. - explicit OpenSSLDigest(const std::string& algorithm); + explicit OpenSSLDigest(absl::string_view algorithm); ~OpenSSLDigest() override; // Returns the digest output size (e.g. 16 bytes for MD5). size_t Size() const override; @@ -34,11 +35,11 @@ class OpenSSLDigest final : public MessageDigest { size_t Finish(void* buf, size_t len) override; // Helper function to look up a digest's EVP by name. - static bool GetDigestEVP(const std::string& algorithm, const EVP_MD** md); + static bool GetDigestEVP(absl::string_view algorithm, const EVP_MD** md); // Helper function to look up a digest's name by EVP. static bool GetDigestName(const EVP_MD* md, std::string* algorithm); // Helper function to get the length of a digest. - static bool GetDigestSize(const std::string& algorithm, size_t* len); + static bool GetDigestSize(absl::string_view algorithm, size_t* len); private: EVP_MD_CTX* ctx_ = nullptr; diff --git a/rtc_base/openssl_key_pair.cc b/rtc_base/openssl_key_pair.cc index 6ac546e9bb..4c474f2d54 100644 --- a/rtc_base/openssl_key_pair.cc +++ b/rtc_base/openssl_key_pair.cc @@ -13,6 +13,8 @@ #include #include +#include "absl/strings/string_view.h" + #if defined(WEBRTC_WIN) // Must be included first before openssl headers. #include "rtc_base/win32.h" // NOLINT @@ -103,7 +105,7 @@ std::unique_ptr OpenSSLKeyPair::Generate( } std::unique_ptr OpenSSLKeyPair::FromPrivateKeyPEMString( - const std::string& pem_string) { + absl::string_view pem_string) { BIO* bio = BIO_new_mem_buf(const_cast(pem_string.data()), pem_string.size()); if (!bio) { diff --git a/rtc_base/openssl_key_pair.h b/rtc_base/openssl_key_pair.h index d9a4939a7e..d09bdb0d5e 100644 --- a/rtc_base/openssl_key_pair.h +++ b/rtc_base/openssl_key_pair.h @@ -16,6 +16,7 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/checks.h" #include "rtc_base/ssl_identity.h" @@ -34,7 +35,7 @@ class OpenSSLKeyPair final { // Constructs a key pair from the private key PEM string. This must not result // in missing public key parameters. Returns null on error. static std::unique_ptr FromPrivateKeyPEMString( - const std::string& pem_string); + absl::string_view pem_string); ~OpenSSLKeyPair(); diff --git a/rtc_base/openssl_session_cache.cc b/rtc_base/openssl_session_cache.cc index f8fcd473dc..d63724242a 100644 --- a/rtc_base/openssl_session_cache.cc +++ b/rtc_base/openssl_session_cache.cc @@ -10,6 +10,7 @@ #include "rtc_base/openssl_session_cache.h" +#include "absl/strings/string_view.h" #include "rtc_base/checks.h" #include "rtc_base/openssl.h" @@ -30,16 +31,16 @@ OpenSSLSessionCache::~OpenSSLSessionCache() { } SSL_SESSION* OpenSSLSessionCache::LookupSession( - const std::string& hostname) const { + absl::string_view hostname) const { auto it = sessions_.find(hostname); return (it != sessions_.end()) ? it->second : nullptr; } -void OpenSSLSessionCache::AddSession(const std::string& hostname, +void OpenSSLSessionCache::AddSession(absl::string_view hostname, SSL_SESSION* new_session) { SSL_SESSION* old_session = LookupSession(hostname); SSL_SESSION_free(old_session); - sessions_[hostname] = new_session; + sessions_.insert_or_assign(std::string(hostname), new_session); } SSL_CTX* OpenSSLSessionCache::GetSSLContext() const { diff --git a/rtc_base/openssl_session_cache.h b/rtc_base/openssl_session_cache.h index b801ec7b0b..75d8d9a0cf 100644 --- a/rtc_base/openssl_session_cache.h +++ b/rtc_base/openssl_session_cache.h @@ -16,7 +16,9 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/ssl_stream_adapter.h" +#include "rtc_base/string_utils.h" #ifndef OPENSSL_IS_BORINGSSL typedef struct ssl_session_st SSL_SESSION; @@ -40,10 +42,10 @@ class OpenSSLSessionCache final { OpenSSLSessionCache& operator=(const OpenSSLSessionCache&) = delete; // Looks up a session by hostname. The returned SSL_SESSION is not up_refed. - SSL_SESSION* LookupSession(const std::string& hostname) const; + SSL_SESSION* LookupSession(absl::string_view hostname) const; // Adds a session to the cache, and up_refs it. Any existing session with the // same hostname is replaced. - void AddSession(const std::string& hostname, SSL_SESSION* session); + void AddSession(absl::string_view hostname, SSL_SESSION* session); // Returns the true underlying SSL Context that holds these cached sessions. SSL_CTX* GetSSLContext() const; // The SSL Mode tht the OpenSSLSessionCache was constructed with. This cannot @@ -61,7 +63,7 @@ class OpenSSLSessionCache final { // Map of hostnames to SSL_SESSIONs; holds references to the SSL_SESSIONs, // which are cleaned up when the factory is destroyed. // TODO(juberti): Add LRU eviction to keep the cache from growing forever. - std::map sessions_; + std::map sessions_; // The cache should never be copied or assigned directly. }; diff --git a/rtc_base/openssl_stream_adapter.cc b/rtc_base/openssl_stream_adapter.cc index dd82e4f061..90870cd9cc 100644 --- a/rtc_base/openssl_stream_adapter.cc +++ b/rtc_base/openssl_stream_adapter.cc @@ -16,6 +16,8 @@ #include #include #include + +#include "absl/strings/string_view.h" #ifndef OPENSSL_IS_BORINGSSL #include #include @@ -327,7 +329,7 @@ void OpenSSLStreamAdapter::SetServerRole(SSLRole role) { } bool OpenSSLStreamAdapter::SetPeerCertificateDigest( - const std::string& digest_alg, + absl::string_view digest_alg, const unsigned char* digest_val, size_t digest_len, SSLPeerCertificateDigestError* error) { @@ -353,7 +355,7 @@ bool OpenSSLStreamAdapter::SetPeerCertificateDigest( } peer_certificate_digest_value_.SetData(digest_val, digest_len); - peer_certificate_digest_algorithm_ = digest_alg; + peer_certificate_digest_algorithm_ = std::string(digest_alg); if (!peer_cert_chain_) { // Normal case, where the digest is set before we obtain the certificate @@ -445,15 +447,15 @@ bool OpenSSLStreamAdapter::GetSslVersionBytes(int* version) const { } // Key Extractor interface -bool OpenSSLStreamAdapter::ExportKeyingMaterial(const std::string& label, +bool OpenSSLStreamAdapter::ExportKeyingMaterial(absl::string_view label, const uint8_t* context, size_t context_len, bool use_context, uint8_t* result, size_t result_len) { - if (SSL_export_keying_material(ssl_, result, result_len, label.c_str(), - label.length(), const_cast(context), - context_len, use_context) != 1) { + if (SSL_export_keying_material(ssl_, result, result_len, label.data(), + label.length(), context, context_len, + use_context) != 1) { return false; } return true; @@ -1263,7 +1265,7 @@ bool OpenSSLStreamAdapter::IsAcceptableCipher(int cipher, KeyType key_type) { return false; } -bool OpenSSLStreamAdapter::IsAcceptableCipher(const std::string& cipher, +bool OpenSSLStreamAdapter::IsAcceptableCipher(absl::string_view cipher, KeyType key_type) { if (key_type == KT_RSA) { for (const cipher_list& c : OK_RSA_ciphers) { diff --git a/rtc_base/openssl_stream_adapter.h b/rtc_base/openssl_stream_adapter.h index 236bdfdfea..de20ba93ce 100644 --- a/rtc_base/openssl_stream_adapter.h +++ b/rtc_base/openssl_stream_adapter.h @@ -19,6 +19,7 @@ #include #include +#include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "rtc_base/buffer.h" #ifdef OPENSSL_IS_BORINGSSL @@ -80,7 +81,7 @@ class OpenSSLStreamAdapter final : public SSLStreamAdapter { // Default argument is for compatibility void SetServerRole(SSLRole role = SSL_SERVER) override; bool SetPeerCertificateDigest( - const std::string& digest_alg, + absl::string_view digest_alg, const unsigned char* digest_val, size_t digest_len, SSLPeerCertificateDigestError* error = nullptr) override; @@ -113,7 +114,7 @@ class OpenSSLStreamAdapter final : public SSLStreamAdapter { SSLProtocolVersion GetSslVersion() const override; bool GetSslVersionBytes(int* version) const override; // Key Extractor interface - bool ExportKeyingMaterial(const std::string& label, + bool ExportKeyingMaterial(absl::string_view label, const uint8_t* context, size_t context_len, bool use_context, @@ -130,7 +131,7 @@ class OpenSSLStreamAdapter final : public SSLStreamAdapter { static bool IsBoringSsl(); static bool IsAcceptableCipher(int cipher, KeyType key_type); - static bool IsAcceptableCipher(const std::string& cipher, KeyType key_type); + static bool IsAcceptableCipher(absl::string_view cipher, KeyType key_type); // Use our timeutils.h source of timing in BoringSSL, allowing us to test // using a fake clock. diff --git a/rtc_base/openssl_utility.cc b/rtc_base/openssl_utility.cc index b5d649ca51..eba3788a94 100644 --- a/rtc_base/openssl_utility.cc +++ b/rtc_base/openssl_utility.cc @@ -9,6 +9,8 @@ */ #include "rtc_base/openssl_utility.h" + +#include "absl/strings/string_view.h" #if defined(WEBRTC_WIN) // Must be included first before openssl headers. #include "rtc_base/win32.h" // NOLINT @@ -184,7 +186,7 @@ bool ParseCertificate(CRYPTO_BUFFER* cert_buffer, } #endif // OPENSSL_IS_BORINGSSL -bool VerifyPeerCertMatchesHost(SSL* ssl, const std::string& host) { +bool VerifyPeerCertMatchesHost(SSL* ssl, absl::string_view host) { if (host.empty()) { RTC_DLOG(LS_ERROR) << "Hostname is empty. Cannot verify peer certificate."; return false; @@ -211,8 +213,7 @@ bool VerifyPeerCertMatchesHost(SSL* ssl, const std::string& host) { return false; } LogCertificates(ssl, x509.get()); - return X509_check_host(x509.get(), host.c_str(), host.size(), 0, nullptr) == - 1; + return X509_check_host(x509.get(), host.data(), host.size(), 0, nullptr) == 1; #else // OPENSSL_IS_BORINGSSL X509* certificate = SSL_get_peer_certificate(ssl); if (certificate == nullptr) { @@ -224,13 +225,13 @@ bool VerifyPeerCertMatchesHost(SSL* ssl, const std::string& host) { LogCertificates(ssl, certificate); bool is_valid_cert_name = - X509_check_host(certificate, host.c_str(), host.size(), 0, nullptr) == 1; + X509_check_host(certificate, host.data(), host.size(), 0, nullptr) == 1; X509_free(certificate); return is_valid_cert_name; #endif // !defined(OPENSSL_IS_BORINGSSL) } -void LogSSLErrors(const std::string& prefix) { +void LogSSLErrors(absl::string_view prefix) { char error_buf[200]; unsigned long err; // NOLINT diff --git a/rtc_base/openssl_utility.h b/rtc_base/openssl_utility.h index ee29ccd602..dd183c283a 100644 --- a/rtc_base/openssl_utility.h +++ b/rtc_base/openssl_utility.h @@ -15,6 +15,8 @@ #include +#include "absl/strings/string_view.h" + namespace rtc { // The openssl namespace holds static helper methods. All methods related // to OpenSSL that are commonly used and don't require global state should be @@ -35,11 +37,11 @@ bool ParseCertificate(CRYPTO_BUFFER* cert_buffer, // TODO(crbug.com/webrtc/11710): When OS certificate verification is available, // skip compiling this as it adds a dependency on OpenSSL X509 objects, which we // are trying to avoid in favor of CRYPTO_BUFFERs (see crbug.com/webrtc/11410). -bool VerifyPeerCertMatchesHost(SSL* ssl, const std::string& host); +bool VerifyPeerCertMatchesHost(SSL* ssl, absl::string_view host); // Logs all the errors in the OpenSSL errror queue from the current thread. A // prefix can be provided for context. -void LogSSLErrors(const std::string& prefix); +void LogSSLErrors(absl::string_view prefix); #ifndef WEBRTC_EXCLUDE_BUILT_IN_SSL_ROOT_CERTS // Attempt to add the certificates from the loader into the SSL_CTX. False is diff --git a/rtc_base/ref_counted_object_unittest.cc b/rtc_base/ref_counted_object_unittest.cc index 6b794e63f9..ab051d4f8a 100644 --- a/rtc_base/ref_counted_object_unittest.cc +++ b/rtc_base/ref_counted_object_unittest.cc @@ -15,6 +15,7 @@ #include #include +#include "absl/strings/string_view.h" #include "api/scoped_refptr.h" #include "rtc_base/ref_count.h" #include "test/gtest.h" @@ -52,7 +53,7 @@ class RefClassWithRvalue : public RefCountInterface { class RefClassWithMixedValues : public RefCountInterface { public: - RefClassWithMixedValues(std::unique_ptr a, int b, const std::string& c) + RefClassWithMixedValues(std::unique_ptr a, int b, absl::string_view c) : a_(std::move(a)), b_(b), c_(c) {} protected: diff --git a/rtc_base/rtc_certificate.h b/rtc_base/rtc_certificate.h index 0102c4f98c..67c5c29a89 100644 --- a/rtc_base/rtc_certificate.h +++ b/rtc_base/rtc_certificate.h @@ -17,6 +17,7 @@ #include #include "absl/base/attributes.h" +#include "absl/strings/string_view.h" #include "api/ref_counted_base.h" #include "api/scoped_refptr.h" #include "rtc_base/system/rtc_export.h" @@ -35,8 +36,8 @@ class SSLIdentity; // the string representations used by OpenSSL. class RTCCertificatePEM { public: - RTCCertificatePEM(const std::string& private_key, - const std::string& certificate) + RTCCertificatePEM(absl::string_view private_key, + absl::string_view certificate) : private_key_(private_key), certificate_(certificate) {} const std::string& private_key() const { return private_key_; } diff --git a/rtc_base/socket_adapters.cc b/rtc_base/socket_adapters.cc index 0bd6efad3e..bc7d2d85a9 100644 --- a/rtc_base/socket_adapters.cc +++ b/rtc_base/socket_adapters.cc @@ -12,15 +12,17 @@ #pragma warning(disable : 4786) #endif +#include "rtc_base/socket_adapters.h" + #include #include "absl/strings/match.h" +#include "absl/strings/string_view.h" #include "rtc_base/buffer.h" #include "rtc_base/byte_buffer.h" #include "rtc_base/checks.h" #include "rtc_base/http_common.h" #include "rtc_base/logging.h" -#include "rtc_base/socket_adapters.h" #include "rtc_base/strings/string_builder.h" #include "rtc_base/zero_memory.h" @@ -217,9 +219,9 @@ void AsyncSSLSocket::ProcessInput(char* data, size_t* len) { /////////////////////////////////////////////////////////////////////////////// AsyncHttpsProxySocket::AsyncHttpsProxySocket(Socket* socket, - const std::string& user_agent, + absl::string_view user_agent, const SocketAddress& proxy, - const std::string& username, + absl::string_view username, const CryptString& password) : BufferedReadAdapter(socket, 1024), proxy_(proxy), @@ -470,7 +472,7 @@ void AsyncHttpsProxySocket::Error(int error) { AsyncSocksProxySocket::AsyncSocksProxySocket(Socket* socket, const SocketAddress& proxy, - const std::string& username, + absl::string_view username, const CryptString& password) : BufferedReadAdapter(socket, 1024), state_(SS_ERROR), diff --git a/rtc_base/socket_adapters.h b/rtc_base/socket_adapters.h index 55f62115d3..e78ee18a27 100644 --- a/rtc_base/socket_adapters.h +++ b/rtc_base/socket_adapters.h @@ -13,6 +13,7 @@ #include +#include "absl/strings/string_view.h" #include "api/array_view.h" #include "rtc_base/async_socket.h" #include "rtc_base/crypt_string.h" @@ -82,9 +83,9 @@ class AsyncSSLSocket : public BufferedReadAdapter { class AsyncHttpsProxySocket : public BufferedReadAdapter { public: AsyncHttpsProxySocket(Socket* socket, - const std::string& user_agent, + absl::string_view user_agent, const SocketAddress& proxy, - const std::string& username, + absl::string_view username, const CryptString& password); ~AsyncHttpsProxySocket() override; @@ -143,7 +144,7 @@ class AsyncSocksProxySocket : public BufferedReadAdapter { public: AsyncSocksProxySocket(Socket* socket, const SocketAddress& proxy, - const std::string& username, + absl::string_view username, const CryptString& password); ~AsyncSocksProxySocket() override; diff --git a/rtc_base/socket_address.cc b/rtc_base/socket_address.cc index 2996ede9d2..93d6860a70 100644 --- a/rtc_base/socket_address.cc +++ b/rtc_base/socket_address.cc @@ -10,6 +10,7 @@ #include "rtc_base/socket_address.h" +#include "absl/strings/string_view.h" #include "rtc_base/numerics/safe_conversions.h" #if defined(WEBRTC_POSIX) @@ -43,7 +44,7 @@ SocketAddress::SocketAddress() { Clear(); } -SocketAddress::SocketAddress(const std::string& hostname, int port) { +SocketAddress::SocketAddress(absl::string_view hostname, int port) { SetIP(hostname); SetPort(port); } @@ -101,8 +102,8 @@ void SocketAddress::SetIP(const IPAddress& ip) { scope_id_ = 0; } -void SocketAddress::SetIP(const std::string& hostname) { - hostname_ = hostname; +void SocketAddress::SetIP(absl::string_view hostname) { + hostname_ = std::string(hostname); literal_ = IPFromString(hostname, &ip_); if (!literal_) { ip_ = IPAddress(); @@ -188,23 +189,24 @@ std::string SocketAddress::ToResolvedSensitiveString() const { return sb.str(); } -bool SocketAddress::FromString(const std::string& str) { +bool SocketAddress::FromString(absl::string_view str) { if (str.at(0) == '[') { - std::string::size_type closebracket = str.rfind(']'); - if (closebracket != std::string::npos) { - std::string::size_type colon = str.find(':', closebracket); - if (colon != std::string::npos && colon > closebracket) { - SetPort(strtoul(str.substr(colon + 1).c_str(), nullptr, 10)); + absl::string_view::size_type closebracket = str.rfind(']'); + if (closebracket != absl::string_view::npos) { + absl::string_view::size_type colon = str.find(':', closebracket); + if (colon != absl::string_view::npos && colon > closebracket) { + SetPort( + strtoul(std::string(str.substr(colon + 1)).c_str(), nullptr, 10)); SetIP(str.substr(1, closebracket - 1)); } else { return false; } } } else { - std::string::size_type pos = str.find(':'); - if (std::string::npos == pos) + absl::string_view::size_type pos = str.find(':'); + if (absl::string_view::npos == pos) return false; - SetPort(strtoul(str.substr(pos + 1).c_str(), nullptr, 10)); + SetPort(strtoul(std::string(str.substr(pos + 1)).c_str(), nullptr, 10)); SetIP(str.substr(0, pos)); } return true; diff --git a/rtc_base/socket_address.h b/rtc_base/socket_address.h index 570a71281e..99e14d8eab 100644 --- a/rtc_base/socket_address.h +++ b/rtc_base/socket_address.h @@ -12,6 +12,8 @@ #define RTC_BASE_SOCKET_ADDRESS_H_ #include + +#include "absl/strings/string_view.h" #ifdef WEBRTC_UNIT_TEST #include // no-presubmit-check TODO(webrtc:8982) #endif // WEBRTC_UNIT_TEST @@ -34,7 +36,7 @@ class RTC_EXPORT SocketAddress { // Creates the address with the given host and port. Host may be a // literal IP string or a hostname to be resolved later. // DCHECKs that port is in valid range (0 to 2^16-1). - SocketAddress(const std::string& hostname, int port); + SocketAddress(absl::string_view hostname, int port); // Creates the address with the given IP and port. // IP is given as an integer in host byte order. V4 only, to be deprecated. @@ -69,7 +71,7 @@ class RTC_EXPORT SocketAddress { // Changes the hostname of this address to the given one. // Does not resolve the address; use Resolve to do so. - void SetIP(const std::string& hostname); + void SetIP(absl::string_view hostname); // Sets the IP address while retaining the hostname. Useful for bypassing // DNS for a pre-resolved IP. @@ -129,7 +131,7 @@ class RTC_EXPORT SocketAddress { std::string ToResolvedSensitiveString() const; // Parses hostname:port and [hostname]:port. - bool FromString(const std::string& str); + bool FromString(absl::string_view str); #ifdef WEBRTC_UNIT_TEST inline std::ostream& operator<<( // no-presubmit-check TODO(webrtc:8982) diff --git a/rtc_base/socket_unittest.cc b/rtc_base/socket_unittest.cc index 01a2bed26d..0b9c2f2c58 100644 --- a/rtc_base/socket_unittest.cc +++ b/rtc_base/socket_unittest.cc @@ -17,6 +17,7 @@ #include #include "absl/memory/memory.h" +#include "absl/strings/string_view.h" #include "rtc_base/arraysize.h" #include "rtc_base/async_packet_socket.h" #include "rtc_base/async_udp_socket.h" @@ -287,7 +288,7 @@ void SocketTest::ConnectInternal(const IPAddress& loopback) { } void SocketTest::ConnectWithDnsLookupInternal(const IPAddress& loopback, - const std::string& host) { + absl::string_view host) { StreamSink sink; SocketAddress accept_addr; diff --git a/rtc_base/socket_unittest.h b/rtc_base/socket_unittest.h index 772df635d7..20ef003a80 100644 --- a/rtc_base/socket_unittest.h +++ b/rtc_base/socket_unittest.h @@ -11,6 +11,7 @@ #ifndef RTC_BASE_SOCKET_UNITTEST_H_ #define RTC_BASE_SOCKET_UNITTEST_H_ +#include "absl/strings/string_view.h" #include "rtc_base/gunit.h" #include "rtc_base/thread.h" @@ -74,7 +75,7 @@ class SocketTest : public ::testing::Test { private: void ConnectInternal(const IPAddress& loopback); void ConnectWithDnsLookupInternal(const IPAddress& loopback, - const std::string& host); + absl::string_view host); void ConnectFailInternal(const IPAddress& loopback); void ConnectWithDnsLookupFailInternal(const IPAddress& loopback); diff --git a/rtc_base/ssl_adapter_unittest.cc b/rtc_base/ssl_adapter_unittest.cc index 2b55211086..430343ecb8 100644 --- a/rtc_base/ssl_adapter_unittest.cc +++ b/rtc_base/ssl_adapter_unittest.cc @@ -8,16 +8,18 @@ * be found in the AUTHORS file in the root of the source tree. */ +#include "rtc_base/ssl_adapter.h" + #include #include #include #include "absl/memory/memory.h" +#include "absl/strings/string_view.h" #include "rtc_base/gunit.h" #include "rtc_base/ip_address.h" #include "rtc_base/message_digest.h" #include "rtc_base/socket_stream.h" -#include "rtc_base/ssl_adapter.h" #include "rtc_base/ssl_identity.h" #include "rtc_base/ssl_stream_adapter.h" #include "rtc_base/stream.h" @@ -99,7 +101,7 @@ class SSLAdapterTestDummyClient : public sigslot::has_slots<> { const std::string& GetReceivedData() const { return data_; } - int Connect(const std::string& hostname, const rtc::SocketAddress& address) { + int Connect(absl::string_view hostname, const rtc::SocketAddress& address) { RTC_LOG(LS_INFO) << "Initiating connection with " << address.ToString(); int rv = ssl_adapter_->Connect(address); @@ -108,7 +110,7 @@ class SSLAdapterTestDummyClient : public sigslot::has_slots<> { RTC_LOG(LS_INFO) << "Starting " << GetSSLProtocolName(ssl_mode_) << " handshake with " << hostname; - if (ssl_adapter_->StartSSL(hostname.c_str()) != 0) { + if (ssl_adapter_->StartSSL(std::string(hostname).c_str()) != 0) { return -1; } } @@ -118,7 +120,7 @@ class SSLAdapterTestDummyClient : public sigslot::has_slots<> { int Close() { return ssl_adapter_->Close(); } - int Send(const std::string& message) { + int Send(absl::string_view message) { RTC_LOG(LS_INFO) << "Client sending '" << message << "'"; return ssl_adapter_->Send(message.data(), message.length()); @@ -189,7 +191,7 @@ class SSLAdapterTestDummyServer : public sigslot::has_slots<> { const std::string& GetReceivedData() const { return data_; } - int Send(const std::string& message) { + int Send(absl::string_view message) { if (ssl_stream_adapter_ == nullptr || ssl_stream_adapter_->GetState() != rtc::SS_OPEN) { // No connection yet. @@ -363,7 +365,7 @@ class SSLAdapterTestBase : public ::testing::Test, public sigslot::has_slots<> { } } - void TestTransfer(const std::string& message) { + void TestTransfer(absl::string_view message) { int rv; rv = client_->Send(message); diff --git a/rtc_base/ssl_certificate.cc b/rtc_base/ssl_certificate.cc index ed42998353..ddb1524f76 100644 --- a/rtc_base/ssl_certificate.cc +++ b/rtc_base/ssl_certificate.cc @@ -15,6 +15,7 @@ #include #include "absl/algorithm/container.h" +#include "absl/strings/string_view.h" #include "rtc_base/checks.h" #include "rtc_base/openssl.h" #ifdef OPENSSL_IS_BORINGSSL @@ -121,7 +122,7 @@ std::unique_ptr SSLCertChain::GetStats() const { // static std::unique_ptr SSLCertificate::FromPEMString( - const std::string& pem_string) { + absl::string_view pem_string) { #ifdef OPENSSL_IS_BORINGSSL return BoringSSLCertificate::FromPEMString(pem_string); #else diff --git a/rtc_base/ssl_certificate.h b/rtc_base/ssl_certificate.h index d0e60ee9cc..77fbba3e9e 100644 --- a/rtc_base/ssl_certificate.h +++ b/rtc_base/ssl_certificate.h @@ -22,6 +22,7 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/buffer.h" #include "rtc_base/system/rtc_export.h" @@ -55,7 +56,7 @@ class RTC_EXPORT SSLCertificate { // stored in *pem_length if it is non-null, and only if // parsing was successful. static std::unique_ptr FromPEMString( - const std::string& pem_string); + absl::string_view pem_string); virtual ~SSLCertificate() = default; // Returns a new SSLCertificate object instance wrapping the same @@ -73,7 +74,7 @@ class RTC_EXPORT SSLCertificate { virtual bool GetSignatureDigestAlgorithm(std::string* algorithm) const = 0; // Compute the digest of the certificate given algorithm - virtual bool ComputeDigest(const std::string& algorithm, + virtual bool ComputeDigest(absl::string_view algorithm, unsigned char* digest, size_t size, size_t* length) const = 0; diff --git a/rtc_base/ssl_fingerprint.cc b/rtc_base/ssl_fingerprint.cc index 358402eb03..a85b7a09ce 100644 --- a/rtc_base/ssl_fingerprint.cc +++ b/rtc_base/ssl_fingerprint.cc @@ -11,11 +11,13 @@ #include "rtc_base/ssl_fingerprint.h" #include + #include #include #include #include "absl/algorithm/container.h" +#include "absl/strings/string_view.h" #include "rtc_base/logging.h" #include "rtc_base/message_digest.h" #include "rtc_base/rtc_certificate.h" @@ -25,19 +27,19 @@ namespace rtc { -SSLFingerprint* SSLFingerprint::Create(const std::string& algorithm, +SSLFingerprint* SSLFingerprint::Create(absl::string_view algorithm, const rtc::SSLIdentity* identity) { return CreateUnique(algorithm, *identity).release(); } std::unique_ptr SSLFingerprint::CreateUnique( - const std::string& algorithm, + absl::string_view algorithm, const rtc::SSLIdentity& identity) { return Create(algorithm, identity.certificate()); } std::unique_ptr SSLFingerprint::Create( - const std::string& algorithm, + absl::string_view algorithm, const rtc::SSLCertificate& cert) { uint8_t digest_val[64]; size_t digest_len; @@ -51,14 +53,14 @@ std::unique_ptr SSLFingerprint::Create( } SSLFingerprint* SSLFingerprint::CreateFromRfc4572( - const std::string& algorithm, - const std::string& fingerprint) { + absl::string_view algorithm, + absl::string_view fingerprint) { return CreateUniqueFromRfc4572(algorithm, fingerprint).release(); } std::unique_ptr SSLFingerprint::CreateUniqueFromRfc4572( - const std::string& algorithm, - const std::string& fingerprint) { + absl::string_view algorithm, + absl::string_view fingerprint) { if (algorithm.empty() || !rtc::IsFips180DigestAlgorithm(algorithm)) return nullptr; @@ -67,7 +69,7 @@ std::unique_ptr SSLFingerprint::CreateUniqueFromRfc4572( char value[rtc::MessageDigest::kMaxSize]; size_t value_len = rtc::hex_decode_with_delimiter( - value, sizeof(value), fingerprint.c_str(), fingerprint.length(), ':'); + value, sizeof(value), fingerprint.data(), fingerprint.length(), ':'); if (!value_len) return nullptr; @@ -94,11 +96,11 @@ std::unique_ptr SSLFingerprint::CreateFromCertificate( return fingerprint; } -SSLFingerprint::SSLFingerprint(const std::string& algorithm, +SSLFingerprint::SSLFingerprint(absl::string_view algorithm, ArrayView digest_view) : algorithm(algorithm), digest(digest_view.data(), digest_view.size()) {} -SSLFingerprint::SSLFingerprint(const std::string& algorithm, +SSLFingerprint::SSLFingerprint(absl::string_view algorithm, const uint8_t* digest_in, size_t digest_len) : SSLFingerprint(algorithm, MakeArrayView(digest_in, digest_len)) {} diff --git a/rtc_base/ssl_fingerprint.h b/rtc_base/ssl_fingerprint.h index add3ab7911..cfa26dd433 100644 --- a/rtc_base/ssl_fingerprint.h +++ b/rtc_base/ssl_fingerprint.h @@ -13,8 +13,10 @@ #include #include + #include +#include "absl/strings/string_view.h" #include "rtc_base/copy_on_write_buffer.h" #include "rtc_base/system/rtc_export.h" @@ -26,34 +28,34 @@ class SSLIdentity; struct RTC_EXPORT SSLFingerprint { // TODO(steveanton): Remove once downstream projects have moved off of this. - static SSLFingerprint* Create(const std::string& algorithm, + static SSLFingerprint* Create(absl::string_view algorithm, const rtc::SSLIdentity* identity); // TODO(steveanton): Rename to Create once projects have migrated. static std::unique_ptr CreateUnique( - const std::string& algorithm, + absl::string_view algorithm, const rtc::SSLIdentity& identity); static std::unique_ptr Create( - const std::string& algorithm, + absl::string_view algorithm, const rtc::SSLCertificate& cert); // TODO(steveanton): Remove once downstream projects have moved off of this. - static SSLFingerprint* CreateFromRfc4572(const std::string& algorithm, - const std::string& fingerprint); + static SSLFingerprint* CreateFromRfc4572(absl::string_view algorithm, + absl::string_view fingerprint); // TODO(steveanton): Rename to CreateFromRfc4572 once projects have migrated. static std::unique_ptr CreateUniqueFromRfc4572( - const std::string& algorithm, - const std::string& fingerprint); + absl::string_view algorithm, + absl::string_view fingerprint); // Creates a fingerprint from a certificate, using the same digest algorithm // as the certificate's signature. static std::unique_ptr CreateFromCertificate( const RTCCertificate& cert); - SSLFingerprint(const std::string& algorithm, + SSLFingerprint(absl::string_view algorithm, ArrayView digest_view); // TODO(steveanton): Remove once downstream projects have moved off of this. - SSLFingerprint(const std::string& algorithm, + SSLFingerprint(absl::string_view algorithm, const uint8_t* digest_in, size_t digest_len); diff --git a/rtc_base/ssl_identity.cc b/rtc_base/ssl_identity.cc index 81cf1d78a3..984979a8a6 100644 --- a/rtc_base/ssl_identity.cc +++ b/rtc_base/ssl_identity.cc @@ -15,6 +15,7 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/checks.h" #ifdef OPENSSL_IS_BORINGSSL #include "rtc_base/boringssl_identity.h" @@ -169,30 +170,32 @@ KeyType IntKeyTypeFamilyToKeyType(int key_type_family) { // SSLIdentity ////////////////////////////////////////////////////////////////////// -bool SSLIdentity::PemToDer(const std::string& pem_type, - const std::string& pem_string, +bool SSLIdentity::PemToDer(absl::string_view pem_type, + absl::string_view pem_string, std::string* der) { // Find the inner body. We need this to fulfill the contract of returning // pem_length. - size_t header = pem_string.find("-----BEGIN " + pem_type + "-----"); - if (header == std::string::npos) { + std::string pem_type_str = std::string(pem_type); + size_t header = pem_string.find("-----BEGIN " + pem_type_str + "-----"); + if (header == absl::string_view::npos) { return false; } size_t body = pem_string.find('\n', header); - if (body == std::string::npos) { + if (body == absl::string_view::npos) { return false; } - size_t trailer = pem_string.find("-----END " + pem_type + "-----"); - if (trailer == std::string::npos) { + size_t trailer = pem_string.find("-----END " + pem_type_str + "-----"); + if (trailer == absl::string_view::npos) { return false; } - std::string inner = pem_string.substr(body + 1, trailer - (body + 1)); + std::string inner = + std::string(pem_string.substr(body + 1, trailer - (body + 1))); *der = Base64::Decode(inner, Base64::DO_PARSE_WHITE | Base64::DO_PAD_ANY | Base64::DO_TERM_BUFFER); return true; } -std::string SSLIdentity::DerToPem(const std::string& pem_type, +std::string SSLIdentity::DerToPem(absl::string_view pem_type, const unsigned char* data, size_t length) { rtc::StringBuilder result; @@ -214,7 +217,7 @@ std::string SSLIdentity::DerToPem(const std::string& pem_type, } // static -std::unique_ptr SSLIdentity::Create(const std::string& common_name, +std::unique_ptr SSLIdentity::Create(absl::string_view common_name, const KeyParams& key_param, time_t certificate_lifetime) { #ifdef OPENSSL_IS_BORINGSSL @@ -227,13 +230,13 @@ std::unique_ptr SSLIdentity::Create(const std::string& common_name, } // static -std::unique_ptr SSLIdentity::Create(const std::string& common_name, +std::unique_ptr SSLIdentity::Create(absl::string_view common_name, const KeyParams& key_param) { return Create(common_name, key_param, kDefaultCertificateLifetimeInSeconds); } // static -std::unique_ptr SSLIdentity::Create(const std::string& common_name, +std::unique_ptr SSLIdentity::Create(absl::string_view common_name, KeyType key_type) { return Create(common_name, KeyParams(key_type), kDefaultCertificateLifetimeInSeconds); @@ -252,8 +255,8 @@ std::unique_ptr SSLIdentity::CreateForTest( // Construct an identity from a private key and a certificate. // static std::unique_ptr SSLIdentity::CreateFromPEMStrings( - const std::string& private_key, - const std::string& certificate) { + absl::string_view private_key, + absl::string_view certificate) { #ifdef OPENSSL_IS_BORINGSSL return BoringSSLIdentity::CreateFromPEMStrings(private_key, certificate); #else @@ -264,8 +267,8 @@ std::unique_ptr SSLIdentity::CreateFromPEMStrings( // Construct an identity from a private key and a certificate chain. // static std::unique_ptr SSLIdentity::CreateFromPEMChainStrings( - const std::string& private_key, - const std::string& certificate_chain) { + absl::string_view private_key, + absl::string_view certificate_chain) { #ifdef OPENSSL_IS_BORINGSSL return BoringSSLIdentity::CreateFromPEMChainStrings(private_key, certificate_chain); diff --git a/rtc_base/ssl_identity.h b/rtc_base/ssl_identity.h index 78d1ec12b7..a0119bb1c4 100644 --- a/rtc_base/ssl_identity.h +++ b/rtc_base/ssl_identity.h @@ -14,10 +14,12 @@ #define RTC_BASE_SSL_IDENTITY_H_ #include + #include #include #include +#include "absl/strings/string_view.h" #include "rtc_base/system/rtc_export.h" namespace rtc { @@ -108,12 +110,12 @@ class RTC_EXPORT SSLIdentity { // should be a non-negative number. // Returns null on failure. // Caller is responsible for freeing the returned object. - static std::unique_ptr Create(const std::string& common_name, + static std::unique_ptr Create(absl::string_view common_name, const KeyParams& key_param, time_t certificate_lifetime); - static std::unique_ptr Create(const std::string& common_name, + static std::unique_ptr Create(absl::string_view common_name, const KeyParams& key_param); - static std::unique_ptr Create(const std::string& common_name, + static std::unique_ptr Create(absl::string_view common_name, KeyType key_type); // Allows fine-grained control over expiration time. @@ -122,13 +124,13 @@ class RTC_EXPORT SSLIdentity { // Construct an identity from a private key and a certificate. static std::unique_ptr CreateFromPEMStrings( - const std::string& private_key, - const std::string& certificate); + absl::string_view private_key, + absl::string_view certificate); // Construct an identity from a private key and a certificate chain. static std::unique_ptr CreateFromPEMChainStrings( - const std::string& private_key, - const std::string& certificate_chain); + absl::string_view private_key, + absl::string_view certificate_chain); virtual ~SSLIdentity() {} @@ -144,10 +146,10 @@ class RTC_EXPORT SSLIdentity { virtual std::string PublicKeyToPEMString() const = 0; // Helpers for parsing converting between PEM and DER format. - static bool PemToDer(const std::string& pem_type, - const std::string& pem_string, + static bool PemToDer(absl::string_view pem_type, + absl::string_view pem_string, std::string* der); - static std::string DerToPem(const std::string& pem_type, + static std::string DerToPem(absl::string_view pem_type, const unsigned char* data, size_t length); diff --git a/rtc_base/ssl_identity_unittest.cc b/rtc_base/ssl_identity_unittest.cc index 53f4a2ad10..1f0278ac71 100644 --- a/rtc_base/ssl_identity_unittest.cc +++ b/rtc_base/ssl_identity_unittest.cc @@ -8,19 +8,22 @@ * be found in the AUTHORS file in the root of the source tree. */ +#include "rtc_base/ssl_identity.h" + #include + #include #include #include #include "absl/strings/str_replace.h" +#include "absl/strings/string_view.h" #include "rtc_base/checks.h" #include "rtc_base/fake_ssl_identity.h" #include "rtc_base/helpers.h" #include "rtc_base/logging.h" #include "rtc_base/message_digest.h" #include "rtc_base/ssl_fingerprint.h" -#include "rtc_base/ssl_identity.h" #include "test/gtest.h" using rtc::SSLIdentity; @@ -236,7 +239,7 @@ class SSLIdentityTest : public ::testing::Test { void TestDigestHelper(DigestType digest, const SSLIdentity* identity, - const std::string& algorithm, + absl::string_view algorithm, size_t expected_len) { DigestType digest1; size_t digest_len; @@ -258,7 +261,7 @@ class SSLIdentityTest : public ::testing::Test { EXPECT_EQ(0, memcmp(digest, digest1, expected_len)); } - void TestDigestForGeneratedCert(const std::string& algorithm, + void TestDigestForGeneratedCert(absl::string_view algorithm, size_t expected_len) { DigestType digest[4]; @@ -281,7 +284,7 @@ class SSLIdentityTest : public ::testing::Test { } } - void TestDigestForFixedCert(const std::string& algorithm, + void TestDigestForFixedCert(absl::string_view algorithm, size_t expected_len, const unsigned char* expected_digest) { bool rv; diff --git a/rtc_base/ssl_stream_adapter.cc b/rtc_base/ssl_stream_adapter.cc index b805fdc6c3..4b60d6d7b1 100644 --- a/rtc_base/ssl_stream_adapter.cc +++ b/rtc_base/ssl_stream_adapter.cc @@ -11,6 +11,7 @@ #include "rtc_base/ssl_stream_adapter.h" #include "absl/memory/memory.h" +#include "absl/strings/string_view.h" #include "rtc_base/openssl_stream_adapter.h" /////////////////////////////////////////////////////////////////////////////// @@ -39,7 +40,7 @@ std::string SrtpCryptoSuiteToName(int crypto_suite) { } } -int SrtpCryptoSuiteFromName(const std::string& crypto_suite) { +int SrtpCryptoSuiteFromName(absl::string_view crypto_suite) { if (crypto_suite == kCsAesCm128HmacSha1_32) return kSrtpAes128CmSha1_32; if (crypto_suite == kCsAesCm128HmacSha1_80) @@ -85,7 +86,7 @@ bool IsGcmCryptoSuite(int crypto_suite) { crypto_suite == kSrtpAeadAes128Gcm); } -bool IsGcmCryptoSuiteName(const std::string& crypto_suite) { +bool IsGcmCryptoSuiteName(absl::string_view crypto_suite) { return (crypto_suite == kCsAeadAes256Gcm || crypto_suite == kCsAeadAes128Gcm); } @@ -98,7 +99,7 @@ bool SSLStreamAdapter::GetSslCipherSuite(int* cipher_suite) { return false; } -bool SSLStreamAdapter::ExportKeyingMaterial(const std::string& label, +bool SSLStreamAdapter::ExportKeyingMaterial(absl::string_view label, const uint8_t* context, size_t context_len, bool use_context, @@ -122,7 +123,7 @@ bool SSLStreamAdapter::IsBoringSsl() { bool SSLStreamAdapter::IsAcceptableCipher(int cipher, KeyType key_type) { return OpenSSLStreamAdapter::IsAcceptableCipher(cipher, key_type); } -bool SSLStreamAdapter::IsAcceptableCipher(const std::string& cipher, +bool SSLStreamAdapter::IsAcceptableCipher(absl::string_view cipher, KeyType key_type) { return OpenSSLStreamAdapter::IsAcceptableCipher(cipher, key_type); } diff --git a/rtc_base/ssl_stream_adapter.h b/rtc_base/ssl_stream_adapter.h index 618ffca4d0..e68870c747 100644 --- a/rtc_base/ssl_stream_adapter.h +++ b/rtc_base/ssl_stream_adapter.h @@ -13,11 +13,13 @@ #include #include + #include #include #include #include "absl/memory/memory.h" +#include "absl/strings/string_view.h" #include "rtc_base/ssl_certificate.h" #include "rtc_base/ssl_identity.h" #include "rtc_base/stream.h" @@ -53,7 +55,7 @@ extern const char kCsAeadAes256Gcm[]; std::string SrtpCryptoSuiteToName(int crypto_suite); // The reverse of above conversion. -int SrtpCryptoSuiteFromName(const std::string& crypto_suite); +int SrtpCryptoSuiteFromName(absl::string_view crypto_suite); // Get key length and salt length for given crypto suite. Returns true for // valid suites, otherwise false. @@ -65,7 +67,7 @@ bool GetSrtpKeyAndSaltLengths(int crypto_suite, bool IsGcmCryptoSuite(int crypto_suite); // Returns true if the given crypto suite name uses a GCM cipher. -bool IsGcmCryptoSuiteName(const std::string& crypto_suite); +bool IsGcmCryptoSuiteName(absl::string_view crypto_suite); // SSLStreamAdapter : A StreamInterfaceAdapter that does SSL/TLS. // After SSL has been started, the stream will only open on successful @@ -176,7 +178,7 @@ class SSLStreamAdapter : public StreamInterface, public sigslot::has_slots<> { // Returns true if successful. // `error` is optional and provides more information about the failure. virtual bool SetPeerCertificateDigest( - const std::string& digest_alg, + absl::string_view digest_alg, const unsigned char* digest_val, size_t digest_len, SSLPeerCertificateDigestError* error = nullptr) = 0; @@ -208,7 +210,7 @@ class SSLStreamAdapter : public StreamInterface, public sigslot::has_slots<> { // zero-length ones). // result -- where to put the computed value // result_len -- the length of the computed value - virtual bool ExportKeyingMaterial(const std::string& label, + virtual bool ExportKeyingMaterial(absl::string_view label, const uint8_t* context, size_t context_len, bool use_context, @@ -233,7 +235,7 @@ class SSLStreamAdapter : public StreamInterface, public sigslot::has_slots<> { // Returns true iff the supplied cipher is deemed to be strong. // TODO(torbjorng): Consider removing the KeyType argument. static bool IsAcceptableCipher(int cipher, KeyType key_type); - static bool IsAcceptableCipher(const std::string& cipher, KeyType key_type); + static bool IsAcceptableCipher(absl::string_view cipher, KeyType key_type); // TODO(guoweis): Move this away from a static class method. Currently this is // introduced such that any caller could depend on sslstreamadapter.h without diff --git a/rtc_base/ssl_stream_adapter_unittest.cc b/rtc_base/ssl_stream_adapter_unittest.cc index f92958dd86..262eeefb79 100644 --- a/rtc_base/ssl_stream_adapter_unittest.cc +++ b/rtc_base/ssl_stream_adapter_unittest.cc @@ -8,12 +8,15 @@ * be found in the AUTHORS file in the root of the source tree. */ +#include "rtc_base/ssl_stream_adapter.h" + #include #include #include #include #include "absl/memory/memory.h" +#include "absl/strings/string_view.h" #include "rtc_base/buffer_queue.h" #include "rtc_base/checks.h" #include "rtc_base/gunit.h" @@ -24,7 +27,6 @@ #include "rtc_base/openssl_stream_adapter.h" #include "rtc_base/ssl_adapter.h" #include "rtc_base/ssl_identity.h" -#include "rtc_base/ssl_stream_adapter.h" #include "rtc_base/stream.h" #include "rtc_base/task_utils/pending_task_safety_flag.h" #include "rtc_base/task_utils/to_queued_task.h" @@ -147,7 +149,7 @@ class SSLDummyStreamBase : public rtc::StreamInterface, public sigslot::has_slots<> { public: SSLDummyStreamBase(SSLStreamAdapterTestBase* test, - const std::string& side, + absl::string_view side, rtc::StreamInterface* in, rtc::StreamInterface* out) : test_base_(test), side_(side), in_(in), out_(out), first_packet_(true) { @@ -235,7 +237,7 @@ class SSLDummyStreamBase : public rtc::StreamInterface, class SSLDummyStreamTLS : public SSLDummyStreamBase { public: SSLDummyStreamTLS(SSLStreamAdapterTestBase* test, - const std::string& side, + absl::string_view side, rtc::FifoBuffer* in, rtc::FifoBuffer* out) : SSLDummyStreamBase(test, side, in, out) {} @@ -303,7 +305,7 @@ class BufferQueueStream : public rtc::StreamInterface { class SSLDummyStreamDTLS : public SSLDummyStreamBase { public: SSLDummyStreamDTLS(SSLStreamAdapterTestBase* test, - const std::string& side, + absl::string_view side, BufferQueueStream* in, BufferQueueStream* out) : SSLDummyStreamBase(test, side, in, out) {} @@ -317,8 +319,8 @@ class SSLStreamAdapterTestBase : public ::testing::Test, public sigslot::has_slots<> { public: SSLStreamAdapterTestBase( - const std::string& client_cert_pem, - const std::string& client_private_key_pem, + absl::string_view client_cert_pem, + absl::string_view client_private_key_pem, bool dtls, rtc::KeyParams client_key_type = rtc::KeyParams(rtc::KT_DEFAULT), rtc::KeyParams server_key_type = rtc::KeyParams(rtc::KT_DEFAULT)) @@ -864,8 +866,8 @@ class SSLStreamAdapterTestDTLSBase : public SSLStreamAdapterTestBase { count_(0), sent_(0) {} - SSLStreamAdapterTestDTLSBase(const std::string& cert_pem, - const std::string& private_key_pem) + SSLStreamAdapterTestDTLSBase(absl::string_view cert_pem, + absl::string_view private_key_pem) : SSLStreamAdapterTestBase(cert_pem, private_key_pem, true), client_buffer_(kBufferCapacity, kDefaultBufferSize), server_buffer_(kBufferCapacity, kDefaultBufferSize), @@ -983,8 +985,8 @@ class SSLStreamAdapterTestDTLS : SSLStreamAdapterTestDTLSBase(::testing::get<0>(GetParam()), ::testing::get<1>(GetParam())) {} - SSLStreamAdapterTestDTLS(const std::string& cert_pem, - const std::string& private_key_pem) + SSLStreamAdapterTestDTLS(absl::string_view cert_pem, + absl::string_view private_key_pem) : SSLStreamAdapterTestDTLSBase(cert_pem, private_key_pem) {} }; @@ -1551,8 +1553,8 @@ class SSLStreamAdapterTestDTLSLegacyProtocols // initialized, so we set the experiment while creationg client_ssl_ // and server_ssl_. - void ConfigureClient(std::string experiment) { - webrtc::test::ScopedFieldTrials trial(experiment); + void ConfigureClient(absl::string_view experiment) { + webrtc::test::ScopedFieldTrials trial{std::string(experiment)}; client_stream_ = new SSLDummyStreamDTLS(this, "c2s", &client_buffer_, &server_buffer_); client_ssl_ = @@ -1564,8 +1566,8 @@ class SSLStreamAdapterTestDTLSLegacyProtocols client_ssl_->SetIdentity(std::move(client_identity)); } - void ConfigureServer(std::string experiment) { - webrtc::test::ScopedFieldTrials trial(experiment); + void ConfigureServer(absl::string_view experiment) { + webrtc::test::ScopedFieldTrials trial{std::string(experiment)}; server_stream_ = new SSLDummyStreamDTLS(this, "s2c", &server_buffer_, &client_buffer_); server_ssl_ = diff --git a/rtc_base/string_encode.cc b/rtc_base/string_encode.cc index 85fb992507..fa99c7a439 100644 --- a/rtc_base/string_encode.cc +++ b/rtc_base/string_encode.cc @@ -12,6 +12,7 @@ #include +#include "absl/strings/string_view.h" #include "rtc_base/arraysize.h" #include "rtc_base/checks.h" @@ -77,8 +78,8 @@ void hex_encode_with_delimiter(char* buffer, } // namespace -std::string hex_encode(const std::string& str) { - return hex_encode(str.c_str(), str.size()); +std::string hex_encode(absl::string_view str) { + return hex_encode(str.data(), str.size()); } std::string hex_encode(const char* source, size_t srclen) { @@ -141,14 +142,14 @@ size_t hex_decode_with_delimiter(char* cbuffer, return bufpos; } -size_t hex_decode(char* buffer, size_t buflen, const std::string& source) { +size_t hex_decode(char* buffer, size_t buflen, absl::string_view source) { return hex_decode_with_delimiter(buffer, buflen, source, 0); } size_t hex_decode_with_delimiter(char* buffer, size_t buflen, - const std::string& source, + absl::string_view source, char delimiter) { - return hex_decode_with_delimiter(buffer, buflen, source.c_str(), + return hex_decode_with_delimiter(buffer, buflen, source.data(), source.length(), delimiter); } @@ -177,7 +178,7 @@ bool tokenize_first(absl::string_view source, std::string* rest) { // Find the first delimiter size_t left_pos = source.find(delimiter); - if (left_pos == std::string::npos) { + if (left_pos == absl::string_view::npos) { return false; } @@ -245,8 +246,9 @@ std::string ToString(const bool b) { std::string ToString(const char* const s) { return std::string(s); } -std::string ToString(const std::string s) { - return s; + +std::string ToString(absl::string_view s) { + return std::string(s); } std::string ToString(const short s) { diff --git a/rtc_base/string_encode.h b/rtc_base/string_encode.h index c63d5271fa..87c5bc8d44 100644 --- a/rtc_base/string_encode.h +++ b/rtc_base/string_encode.h @@ -28,7 +28,7 @@ namespace rtc { // String Encoding Utilities ////////////////////////////////////////////////////////////////////// -std::string hex_encode(const std::string& str); +std::string hex_encode(absl::string_view str); std::string hex_encode(const char* source, size_t srclen); std::string hex_encode_with_delimiter(const char* source, size_t srclen, @@ -51,10 +51,10 @@ size_t hex_decode_with_delimiter(char* buffer, char delimiter); // Helper functions for hex_decode. -size_t hex_decode(char* buffer, size_t buflen, const std::string& source); +size_t hex_decode(char* buffer, size_t buflen, absl::string_view source); size_t hex_decode_with_delimiter(char* buffer, size_t buflen, - const std::string& source, + absl::string_view source, char delimiter); // Joins the source vector of strings into a single string, with each @@ -89,7 +89,7 @@ bool tokenize_first(absl::string_view source, std::string ToString(bool b); std::string ToString(const char* s); -std::string ToString(std::string t); +std::string ToString(absl::string_view s); std::string ToString(short s); std::string ToString(unsigned short s); diff --git a/rtc_base/string_utils.cc b/rtc_base/string_utils.cc index c03433541a..e8c13464bd 100644 --- a/rtc_base/string_utils.cc +++ b/rtc_base/string_utils.cc @@ -10,6 +10,8 @@ #include "rtc_base/string_utils.h" +#include "absl/strings/string_view.h" + namespace rtc { size_t strcpyn(char* buffer, diff --git a/rtc_base/string_utils.h b/rtc_base/string_utils.h index 1bb9d17528..a9cdd61a7b 100644 --- a/rtc_base/string_utils.h +++ b/rtc_base/string_utils.h @@ -16,6 +16,8 @@ #include #include +#include "absl/strings/string_view.h" + #if defined(WEBRTC_WIN) #include #include @@ -30,10 +32,24 @@ #include +#include "absl/strings/string_view.h" + namespace rtc { const size_t SIZE_UNKNOWN = static_cast(-1); +// An absl::string_view comparator functor for use with container types such as +// std::map that support heterogenous lookup. +// +// Example usage: +// std::map my_map; +struct AbslStringViewCmp { + using is_transparent = void; + bool operator()(absl::string_view a, absl::string_view b) const { + return a < b; + } +}; + // Safe version of strncpy that always nul-terminate. size_t strcpyn(char* buffer, size_t buflen, @@ -57,7 +73,7 @@ inline std::wstring ToUtf16(const char* utf8, size_t len) { return ws; } -inline std::wstring ToUtf16(const std::string& str) { +inline std::wstring ToUtf16(absl::string_view str) { return ToUtf16(str.data(), str.length()); } diff --git a/rtc_base/strings/json.cc b/rtc_base/strings/json.cc index 99664404cf..af8ba184e7 100644 --- a/rtc_base/strings/json.cc +++ b/rtc_base/strings/json.cc @@ -14,6 +14,7 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/string_encode.h" namespace rtc { @@ -240,46 +241,47 @@ bool GetDoubleFromJsonArray(const Json::Value& in, size_t n, double* out) { } bool GetValueFromJsonObject(const Json::Value& in, - const std::string& k, + absl::string_view k, Json::Value* out) { - if (!in.isObject() || !in.isMember(k)) { + std::string k_str = std::string(k); + if (!in.isObject() || !in.isMember(k_str)) { return false; } - *out = in[k]; + *out = in[k_str]; return true; } bool GetIntFromJsonObject(const Json::Value& in, - const std::string& k, + absl::string_view k, int* out) { Json::Value x; return GetValueFromJsonObject(in, k, &x) && GetIntFromJson(x, out); } bool GetUIntFromJsonObject(const Json::Value& in, - const std::string& k, + absl::string_view k, unsigned int* out) { Json::Value x; return GetValueFromJsonObject(in, k, &x) && GetUIntFromJson(x, out); } bool GetStringFromJsonObject(const Json::Value& in, - const std::string& k, + absl::string_view k, std::string* out) { Json::Value x; return GetValueFromJsonObject(in, k, &x) && GetStringFromJson(x, out); } bool GetBoolFromJsonObject(const Json::Value& in, - const std::string& k, + absl::string_view k, bool* out) { Json::Value x; return GetValueFromJsonObject(in, k, &x) && GetBoolFromJson(x, out); } bool GetDoubleFromJsonObject(const Json::Value& in, - const std::string& k, + absl::string_view k, double* out) { Json::Value x; return GetValueFromJsonObject(in, k, &x) && GetDoubleFromJson(x, out); diff --git a/rtc_base/strings/json.h b/rtc_base/strings/json.h index 0cb9542c7f..618cb71b04 100644 --- a/rtc_base/strings/json.h +++ b/rtc_base/strings/json.h @@ -14,6 +14,8 @@ #include #include +#include "absl/strings/string_view.h" + #if !defined(WEBRTC_EXTERNAL_JSON) #include "json/json.h" #else @@ -62,22 +64,20 @@ Json::Value DoubleVectorToJsonArray(const std::vector& in); // Pull values out of a JSON object. bool GetValueFromJsonObject(const Json::Value& in, - const std::string& k, + absl::string_view k, Json::Value* out); -bool GetIntFromJsonObject(const Json::Value& in, - const std::string& k, - int* out); +bool GetIntFromJsonObject(const Json::Value& in, absl::string_view k, int* out); bool GetUIntFromJsonObject(const Json::Value& in, - const std::string& k, + absl::string_view k, unsigned int* out); bool GetStringFromJsonObject(const Json::Value& in, - const std::string& k, + absl::string_view k, std::string* out); bool GetBoolFromJsonObject(const Json::Value& in, - const std::string& k, + absl::string_view k, bool* out); bool GetDoubleFromJsonObject(const Json::Value& in, - const std::string& k, + absl::string_view k, double* out); // Writes out a Json value as a string. diff --git a/rtc_base/strings/string_builder.cc b/rtc_base/strings/string_builder.cc index 7536cd77dd..e3e25e631b 100644 --- a/rtc_base/strings/string_builder.cc +++ b/rtc_base/strings/string_builder.cc @@ -15,6 +15,7 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/checks.h" #include "rtc_base/numerics/safe_minmax.h" @@ -26,16 +27,12 @@ SimpleStringBuilder::SimpleStringBuilder(rtc::ArrayView buffer) RTC_DCHECK(IsConsistent()); } -SimpleStringBuilder& SimpleStringBuilder::operator<<(const char* str) { - return Append(str, strlen(str)); -} - SimpleStringBuilder& SimpleStringBuilder::operator<<(char ch) { return Append(&ch, 1); } -SimpleStringBuilder& SimpleStringBuilder::operator<<(const std::string& str) { - return Append(str.c_str(), str.length()); +SimpleStringBuilder& SimpleStringBuilder::operator<<(absl::string_view str) { + return Append(str.data(), str.length()); } // Numeric conversion routines. diff --git a/rtc_base/strings/string_builder.h b/rtc_base/strings/string_builder.h index 6fe478ce4c..b35b7f1867 100644 --- a/rtc_base/strings/string_builder.h +++ b/rtc_base/strings/string_builder.h @@ -32,9 +32,8 @@ class SimpleStringBuilder { SimpleStringBuilder(const SimpleStringBuilder&) = delete; SimpleStringBuilder& operator=(const SimpleStringBuilder&) = delete; - SimpleStringBuilder& operator<<(const char* str); SimpleStringBuilder& operator<<(char ch); - SimpleStringBuilder& operator<<(const std::string& str); + SimpleStringBuilder& operator<<(absl::string_view str); SimpleStringBuilder& operator<<(int i); SimpleStringBuilder& operator<<(unsigned i); SimpleStringBuilder& operator<<(long i); // NOLINT diff --git a/rtc_base/thread.cc b/rtc_base/thread.cc index 307d499255..f9680650a9 100644 --- a/rtc_base/thread.cc +++ b/rtc_base/thread.cc @@ -10,6 +10,8 @@ #include "rtc_base/thread.h" +#include "absl/strings/string_view.h" + #if defined(WEBRTC_WIN) #include #elif defined(WEBRTC_POSIX) @@ -744,10 +746,10 @@ bool Thread::SleepMs(int milliseconds) { #endif } -bool Thread::SetName(const std::string& name, const void* obj) { +bool Thread::SetName(absl::string_view name, const void* obj) { RTC_DCHECK(!IsRunning()); - name_ = name; + name_ = std::string(name); if (obj) { // The %p specifier typically produce at most 16 hex digits, possibly with a // 0x prefix. But format is implementation defined, so add some margin. diff --git a/rtc_base/thread.h b/rtc_base/thread.h index 3c4ed558cd..052a71b22c 100644 --- a/rtc_base/thread.h +++ b/rtc_base/thread.h @@ -22,6 +22,8 @@ #include #include +#include "absl/strings/string_view.h" + #if defined(WEBRTC_POSIX) #include #endif @@ -348,7 +350,7 @@ class RTC_LOCKABLE RTC_EXPORT Thread : public webrtc::TaskQueueBase { // Sets the thread's name, for debugging. Must be called before Start(). // If `obj` is non-null, its value is appended to `name`. const std::string& name() const { return name_; } - bool SetName(const std::string& name, const void* obj); + bool SetName(absl::string_view name, const void* obj); // Sets the expected processing time in ms. The thread will write // log messages when Invoke() takes more time than this. diff --git a/rtc_base/unique_id_generator.cc b/rtc_base/unique_id_generator.cc index 9fa3021c6f..e68c643dbe 100644 --- a/rtc_base/unique_id_generator.cc +++ b/rtc_base/unique_id_generator.cc @@ -13,6 +13,7 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/helpers.h" #include "rtc_base/string_encode.h" #include "rtc_base/string_to_number.h" @@ -55,8 +56,11 @@ std::string UniqueStringGenerator::GenerateString() { return ToString(unique_number_generator_.GenerateNumber()); } -bool UniqueStringGenerator::AddKnownId(const std::string& value) { - absl::optional int_value = StringToNumber(value); +bool UniqueStringGenerator::AddKnownId(absl::string_view value) { + // TODO(webrtc:13579): remove string copy here once absl::string_view version + // of StringToNumber is available. + absl::optional int_value = + StringToNumber(std::string(value)); // The underlying generator works for uint32_t values, so if the provided // value is not a uint32_t it will never be generated anyway. if (int_value.has_value()) { diff --git a/rtc_base/unique_id_generator.h b/rtc_base/unique_id_generator.h index 3e2f9d7072..342dad7766 100644 --- a/rtc_base/unique_id_generator.h +++ b/rtc_base/unique_id_generator.h @@ -15,6 +15,7 @@ #include #include +#include "absl/strings/string_view.h" #include "api/array_view.h" #include "api/sequence_checker.h" #include "rtc_base/synchronization/mutex.h" @@ -103,7 +104,7 @@ class UniqueStringGenerator { // Adds an id that this generator should no longer generate. // Return value indicates whether the ID was hitherto unknown. - bool AddKnownId(const std::string& value); + bool AddKnownId(absl::string_view value); private: // This implementation will be simple and will generate "0", "1", ... diff --git a/sdk/BUILD.gn b/sdk/BUILD.gn index a5c7d47579..a8e246d5f6 100644 --- a/sdk/BUILD.gn +++ b/sdk/BUILD.gn @@ -355,6 +355,8 @@ if (is_ios || is_mac) { "../rtc_base:network_constants", "../rtc_base:threading", ] + + absl_deps = [ "//third_party/abseil-cpp/absl/strings" ] } rtc_library("network_monitor_objc") { @@ -374,6 +376,7 @@ if (is_ios || is_mac) { ":base_objc", ":helpers_objc", ":network_monitor_observer", + "../rtc_base:stringutils", "../rtc_base/system:gcd_helpers", ] } @@ -1581,6 +1584,8 @@ if (is_ios || is_mac) { "../rtc_base/task_utils:pending_task_safety_flag", "../rtc_base/task_utils:to_queued_task", ] + + absl_deps = [ "//third_party/abseil-cpp/absl/strings" ] } } diff --git a/sdk/android/BUILD.gn b/sdk/android/BUILD.gn index f81d3d5806..e17fb33dac 100644 --- a/sdk/android/BUILD.gn +++ b/sdk/android/BUILD.gn @@ -592,7 +592,10 @@ if (current_os == "linux" || is_android) { "../../system_wrappers:field_trial", "../../system_wrappers:metrics", ] - absl_deps = [ "//third_party/abseil-cpp/absl/types:optional" ] + absl_deps = [ + "//third_party/abseil-cpp/absl/strings", + "//third_party/abseil-cpp/absl/types:optional", + ] } rtc_library("audio_jni") { diff --git a/sdk/android/src/jni/android_network_monitor.cc b/sdk/android/src/jni/android_network_monitor.cc index 9dbc27fdc2..e6f2357912 100644 --- a/sdk/android/src/jni/android_network_monitor.cc +++ b/sdk/android/src/jni/android_network_monitor.cc @@ -11,6 +11,8 @@ #include "sdk/android/src/jni/android_network_monitor.h" #include + +#include "absl/strings/string_view.h" #ifndef RTLD_NOLOAD // This was added in Lollipop to dlfcn.h #define RTLD_NOLOAD 4 @@ -284,7 +286,7 @@ void AndroidNetworkMonitor::Stop() { rtc::NetworkBindingResult AndroidNetworkMonitor::BindSocketToNetwork( int socket_fd, const rtc::IPAddress& address, - const std::string& if_name) { + absl::string_view if_name) { RTC_DCHECK_RUN_ON(network_thread_); // Android prior to Lollipop didn't have support for binding sockets to @@ -417,7 +419,7 @@ void AndroidNetworkMonitor::OnNetworkConnected_n( absl::optional AndroidNetworkMonitor::FindNetworkHandleFromAddressOrName( const rtc::IPAddress& ip_address, - const std::string& if_name) const { + absl::string_view if_name) const { RTC_DCHECK_RUN_ON(network_thread_); RTC_LOG(LS_INFO) << "Find network handle."; if (find_network_handle_without_ipv6_temporary_part_) { @@ -443,11 +445,11 @@ AndroidNetworkMonitor::FindNetworkHandleFromAddressOrName( absl::optional AndroidNetworkMonitor::FindNetworkHandleFromIfname( - const std::string& if_name) const { + absl::string_view if_name) const { RTC_DCHECK_RUN_ON(network_thread_); if (bind_using_ifname_) { for (auto const& iter : network_info_by_handle_) { - if (if_name.find(iter.second.interface_name) != std::string::npos) { + if (if_name.find(iter.second.interface_name) != absl::string_view::npos) { // Use partial match so that e.g if_name="v4-wlan0" is matched // agains iter.first="wlan0" return absl::make_optional(iter.first); @@ -495,7 +497,7 @@ void AndroidNetworkMonitor::SetNetworkInfos( } rtc::AdapterType AndroidNetworkMonitor::GetAdapterType( - const std::string& if_name) { + absl::string_view if_name) { RTC_DCHECK_RUN_ON(network_thread_); auto iter = adapter_type_by_name_.find(if_name); rtc::AdapterType type = (iter == adapter_type_by_name_.end()) @@ -506,7 +508,7 @@ rtc::AdapterType AndroidNetworkMonitor::GetAdapterType( for (auto const& iter : adapter_type_by_name_) { // Use partial match so that e.g if_name="v4-wlan0" is matched // agains iter.first="wlan0" - if (if_name.find(iter.first) != std::string::npos) { + if (if_name.find(iter.first) != absl::string_view::npos) { type = iter.second; break; } @@ -520,7 +522,7 @@ rtc::AdapterType AndroidNetworkMonitor::GetAdapterType( } rtc::AdapterType AndroidNetworkMonitor::GetVpnUnderlyingAdapterType( - const std::string& if_name) { + absl::string_view if_name) { RTC_DCHECK_RUN_ON(network_thread_); auto iter = vpn_underlying_adapter_type_by_name_.find(if_name); rtc::AdapterType type = (iter == vpn_underlying_adapter_type_by_name_.end()) @@ -530,7 +532,7 @@ rtc::AdapterType AndroidNetworkMonitor::GetVpnUnderlyingAdapterType( // Use partial match so that e.g if_name="v4-wlan0" is matched // agains iter.first="wlan0" for (auto const& iter : vpn_underlying_adapter_type_by_name_) { - if (if_name.find(iter.first) != std::string::npos) { + if (if_name.find(iter.first) != absl::string_view::npos) { type = iter.second; break; } @@ -541,7 +543,7 @@ rtc::AdapterType AndroidNetworkMonitor::GetVpnUnderlyingAdapterType( } rtc::NetworkPreference AndroidNetworkMonitor::GetNetworkPreference( - const std::string& if_name) { + absl::string_view if_name) { RTC_DCHECK_RUN_ON(network_thread_); auto iter = adapter_type_by_name_.find(if_name); if (iter == adapter_type_by_name_.end()) { diff --git a/sdk/android/src/jni/android_network_monitor.h b/sdk/android/src/jni/android_network_monitor.h index 01e5fb7af7..dbf51c2020 100644 --- a/sdk/android/src/jni/android_network_monitor.h +++ b/sdk/android/src/jni/android_network_monitor.h @@ -17,9 +17,11 @@ #include #include +#include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "rtc_base/network_monitor.h" #include "rtc_base/network_monitor_factory.h" +#include "rtc_base/string_utils.h" #include "rtc_base/task_utils/pending_task_safety_flag.h" #include "rtc_base/thread.h" #include "rtc_base/thread_annotations.h" @@ -83,12 +85,12 @@ class AndroidNetworkMonitor : public rtc::NetworkMonitorInterface { rtc::NetworkBindingResult BindSocketToNetwork( int socket_fd, const rtc::IPAddress& address, - const std::string& if_name) override; - rtc::AdapterType GetAdapterType(const std::string& if_name) override; + absl::string_view if_name) override; + rtc::AdapterType GetAdapterType(absl::string_view if_name) override; rtc::AdapterType GetVpnUnderlyingAdapterType( - const std::string& if_name) override; + absl::string_view if_name) override; rtc::NetworkPreference GetNetworkPreference( - const std::string& if_name) override; + absl::string_view if_name) override; // Always expected to be called on the network thread. void SetNetworkInfos(const std::vector& network_infos); @@ -112,7 +114,7 @@ class AndroidNetworkMonitor : public rtc::NetworkMonitorInterface { // Visible for testing. absl::optional FindNetworkHandleFromAddressOrName( const rtc::IPAddress& address, - const std::string& ifname) const; + absl::string_view ifname) const; private: void OnNetworkConnected_n(const NetworkInformation& network_info); @@ -121,17 +123,17 @@ class AndroidNetworkMonitor : public rtc::NetworkMonitorInterface { rtc::NetworkPreference preference); absl::optional FindNetworkHandleFromIfname( - const std::string& ifname) const; + absl::string_view ifname) const; const int android_sdk_int_; ScopedJavaGlobalRef j_application_context_; ScopedJavaGlobalRef j_network_monitor_; rtc::Thread* const network_thread_; bool started_ RTC_GUARDED_BY(network_thread_) = false; - std::map adapter_type_by_name_ - RTC_GUARDED_BY(network_thread_); - std::map vpn_underlying_adapter_type_by_name_ - RTC_GUARDED_BY(network_thread_); + std::map + adapter_type_by_name_ RTC_GUARDED_BY(network_thread_); + std::map + vpn_underlying_adapter_type_by_name_ RTC_GUARDED_BY(network_thread_); std::map network_handle_by_address_ RTC_GUARDED_BY(network_thread_); std::map network_info_by_handle_ diff --git a/sdk/objc/components/network/RTCNetworkMonitor.mm b/sdk/objc/components/network/RTCNetworkMonitor.mm index 7ac4946ec3..7e75b2b4c0 100644 --- a/sdk/objc/components/network/RTCNetworkMonitor.mm +++ b/sdk/objc/components/network/RTCNetworkMonitor.mm @@ -15,6 +15,8 @@ #import "base/RTCLogging.h" #import "helpers/RTCDispatcher+Private.h" +#include "rtc_base/string_utils.h" + namespace { rtc::AdapterType AdapterTypeFromInterfaceType(nw_interface_type_t interfaceType) { @@ -78,8 +80,8 @@ rtc::AdapterType AdapterTypeFromInterfaceType(nw_interface_type_t interfaceType) } else if (status == nw_path_status_satisfiable) { RTCLog(@"NW path monitor status: satisfiable."); } - std::map *map = - new std::map(); + std::map *map = + new std::map(); nw_path_enumerate_interfaces( path, (nw_path_enumerate_interfaces_block_t) ^ (nw_interface_t interface) { const char *name = nw_interface_get_name(interface); diff --git a/sdk/objc/native/src/network_monitor_observer.h b/sdk/objc/native/src/network_monitor_observer.h index 6fd126a0ae..7c411a1db1 100644 --- a/sdk/objc/native/src/network_monitor_observer.h +++ b/sdk/objc/native/src/network_monitor_observer.h @@ -14,7 +14,9 @@ #include #include +#include "absl/strings/string_view.h" #include "rtc_base/network_constants.h" +#include "rtc_base/string_utils.h" #include "rtc_base/thread.h" namespace webrtc { @@ -28,7 +30,8 @@ class NetworkMonitorObserver { // adapter type, for all available interfaces on the current path. If an // interface name isn't present it can be assumed to be unavailable. virtual void OnPathUpdate( - std::map adapter_type_by_name) = 0; + std::map + adapter_type_by_name) = 0; protected: virtual ~NetworkMonitorObserver() {} diff --git a/sdk/objc/native/src/objc_network_monitor.h b/sdk/objc/native/src/objc_network_monitor.h index df4774efe2..05752e1f0c 100644 --- a/sdk/objc/native/src/objc_network_monitor.h +++ b/sdk/objc/native/src/objc_network_monitor.h @@ -13,9 +13,11 @@ #include +#include "absl/strings/string_view.h" #include "api/sequence_checker.h" #include "rtc_base/network_monitor.h" #include "rtc_base/network_monitor_factory.h" +#include "rtc_base/string_utils.h" #include "rtc_base/task_utils/pending_task_safety_flag.h" #include "rtc_base/thread.h" #include "rtc_base/thread_annotations.h" @@ -41,23 +43,24 @@ class ObjCNetworkMonitor : public rtc::NetworkMonitorInterface, void Start() override; void Stop() override; - rtc::AdapterType GetAdapterType(const std::string& interface_name) override; + rtc::AdapterType GetAdapterType(absl::string_view interface_name) override; rtc::AdapterType GetVpnUnderlyingAdapterType( - const std::string& interface_name) override; + absl::string_view interface_name) override; rtc::NetworkPreference GetNetworkPreference( - const std::string& interface_name) override; - bool IsAdapterAvailable(const std::string& interface_name) override; + absl::string_view interface_name) override; + bool IsAdapterAvailable(absl::string_view interface_name) override; // NetworkMonitorObserver override. // Fans out updates to observers on the correct thread. void OnPathUpdate( - std::map adapter_type_by_name) override; + std::map + adapter_type_by_name) override; private: rtc::Thread* thread_ = nullptr; bool started_ = false; - std::map adapter_type_by_name_ - RTC_GUARDED_BY(thread_); + std::map + adapter_type_by_name_ RTC_GUARDED_BY(thread_); rtc::scoped_refptr safety_flag_; RTCNetworkMonitor* network_monitor_ = nil; }; diff --git a/sdk/objc/native/src/objc_network_monitor.mm b/sdk/objc/native/src/objc_network_monitor.mm index 14ed73374c..1790798ab7 100644 --- a/sdk/objc/native/src/objc_network_monitor.mm +++ b/sdk/objc/native/src/objc_network_monitor.mm @@ -9,12 +9,14 @@ */ #include "sdk/objc/native/src/objc_network_monitor.h" +#include "absl/strings/string_view.h" #include "rtc_base/task_utils/to_queued_task.h" #include #include "rtc_base/logging.h" +#include "rtc_base/string_utils.h" namespace webrtc { @@ -56,24 +58,24 @@ void ObjCNetworkMonitor::Stop() { started_ = false; } -rtc::AdapterType ObjCNetworkMonitor::GetAdapterType(const std::string& interface_name) { +rtc::AdapterType ObjCNetworkMonitor::GetAdapterType(absl::string_view interface_name) { RTC_DCHECK_RUN_ON(thread_); - if (adapter_type_by_name_.find(interface_name) == adapter_type_by_name_.end()) { + auto iter = adapter_type_by_name_.find(interface_name); + if (iter == adapter_type_by_name_.end()) { return rtc::ADAPTER_TYPE_UNKNOWN; } - return adapter_type_by_name_.at(interface_name); + return iter->second; } -rtc::AdapterType ObjCNetworkMonitor::GetVpnUnderlyingAdapterType( - const std::string& interface_name) { +rtc::AdapterType ObjCNetworkMonitor::GetVpnUnderlyingAdapterType(absl::string_view interface_name) { return rtc::ADAPTER_TYPE_UNKNOWN; } -rtc::NetworkPreference ObjCNetworkMonitor::GetNetworkPreference(const std::string& interface_name) { +rtc::NetworkPreference ObjCNetworkMonitor::GetNetworkPreference(absl::string_view interface_name) { return rtc::NetworkPreference::NEUTRAL; } -bool ObjCNetworkMonitor::IsAdapterAvailable(const std::string& interface_name) { +bool ObjCNetworkMonitor::IsAdapterAvailable(absl::string_view interface_name) { RTC_DCHECK_RUN_ON(thread_); if (adapter_type_by_name_.empty()) { // If we have no path update, assume everything's available, because it's @@ -84,7 +86,7 @@ bool ObjCNetworkMonitor::IsAdapterAvailable(const std::string& interface_name) { } void ObjCNetworkMonitor::OnPathUpdate( - std::map adapter_type_by_name) { + std::map adapter_type_by_name) { RTC_DCHECK(network_monitor_ != nil); thread_->PostTask(ToQueuedTask(safety_flag_, [this, adapter_type_by_name] { RTC_DCHECK_RUN_ON(thread_);