0

[base] Remove BasicStringPiece::starts_with()

In order to make BasicStringPiece API compatible with C++17's
std::basic_string_view this change removes the starts_with() API and
updates call sites to use base::StartsWith instead.

In order to keep this callsites concise, base::StartsWith's
case_sensitivity parameter now defaults to CompareCase::SENSITIVE.

TBR=dcheng

Bug: 1049498
Change-Id: Ie621c6d08283d2ffd1055c5753ade5451f5c0b1d
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/2358745
Commit-Queue: Jan Wilken Dörrie <jdoerrie@chromium.org>
Reviewed-by: Daniel Cheng <dcheng@chromium.org>
Cr-Commit-Position: refs/heads/master@{#799265}
This commit is contained in:
Jan Wilken Dörrie
2020-08-18 19:35:56 +00:00
committed by Commit Bot
parent c3907c3e68
commit f05bb1087f
82 changed files with 185 additions and 188 deletions
android_webview/renderer
base
chrome
chromeos/printing
components
autofill
content
client_update_protocol
drive
flags_ui
invalidation
password_manager
core
browser
policy
core
search_engines
search_provider_logos
services
quarantine
storage
dom_storage
indexed_db
viz
service
display
content
device/gamepad
extensions
fuchsia/engine/browser
google_apis/drive
headless/lib/browser
ios/chrome/common
media/capture/video/linux
net
pdf
printing
services
sql/recover_module
tools/android/forwarder2
url

@ -10,6 +10,7 @@
#include "android_webview/common/aw_hit_test_data.h"
#include "android_webview/common/render_view_messages.h"
#include "base/no_destructor.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "components/autofill/content/renderer/autofill_agent.h"
#include "components/autofill/content/renderer/password_autofill_agent.h"
@ -79,7 +80,7 @@ bool RemovePrefixAndAssignIfMatches(const base::StringPiece& prefix,
std::string* dest) {
const base::StringPiece spec(url.possibly_invalid_spec());
if (spec.starts_with(prefix)) {
if (base::StartsWith(spec, prefix)) {
url::RawCanonOutputW<1024> output;
url::DecodeURLEscapeSequences(
spec.data() + prefix.length(), spec.length() - prefix.length(),

@ -536,7 +536,7 @@ void FeatureList::RegisterOverride(StringPiece feature_name,
DCHECK(IsValidFeatureOrFieldTrialName(field_trial->trial_name()))
<< field_trial->trial_name();
}
if (feature_name.starts_with("*")) {
if (StartsWith(feature_name, "*")) {
feature_name = feature_name.substr(1);
overridden_state = OVERRIDE_USE_DEFAULT;
}

@ -200,7 +200,7 @@ pid_t FindThreadID(pid_t pid, pid_t ns_tid, bool* ns_pid_supported) {
StringTokenizer tokenizer(status, "\n");
while (tokenizer.GetNext()) {
StringPiece value_str(tokenizer.token_piece());
if (!value_str.starts_with("NSpid"))
if (!StartsWith(value_str, "NSpid"))
continue;
*ns_pid_supported = true;

@ -459,8 +459,8 @@ bool Histogram::InspectConstructionArguments(StringPiece name,
// them here.
// Blink.UseCounter legitimately has more than 1000 entries in its enum.
// Arc.OOMKills: https://crbug.com/916757
if (!name.starts_with("Blink.UseCounter") &&
!name.starts_with("Arc.OOMKills.")) {
if (!StartsWith(name, "Blink.UseCounter") &&
!StartsWith(name, "Arc.OOMKills.")) {
DVLOG(1) << "Histogram: " << name
<< " has bad bucket_count: " << *bucket_count << " (limit "
<< kBucketCount_MAX << ")";

@ -195,7 +195,7 @@ bool SupportsPerTaskTimeInState() {
.Append("time_in_state");
std::string contents;
return internal::ReadProcFile(time_in_state_path, &contents) &&
StartsWith(contents, "cpu", CompareCase::SENSITIVE);
StartsWith(contents, "cpu");
}
} // namespace
@ -350,7 +350,7 @@ int ProcessMetrics::GetOpenFdSoftLimit() const {
for (const auto& line : SplitStringPiece(
limits_contents, "\n", KEEP_WHITESPACE, SPLIT_WANT_NONEMPTY)) {
if (!line.starts_with("Max open files"))
if (!StartsWith(line, "Max open files"))
continue;
auto tokens =
@ -790,7 +790,7 @@ bool IsValidDiskName(StringPiece candidate) {
}
const char kMMCName[] = "mmcblk";
if (!candidate.starts_with(kMMCName))
if (!StartsWith(candidate, kMMCName))
return false;
// mmcblk[0-9]+ case

@ -260,13 +260,6 @@ template <typename STRING_TYPE> class BasicStringPiece {
return internal::copy(*this, buf, n, pos);
}
// Does "this" start with "x"
constexpr bool starts_with(BasicStringPiece x) const noexcept {
return (
(this->length_ >= x.length_) &&
(CharTraits<value_type>::compare(this->ptr_, x.ptr_, x.length_) == 0));
}
// find: Search for a character or substring at a given offset.
size_type find(const BasicStringPiece<STRING_TYPE>& s,
size_type pos = 0) const {

@ -543,18 +543,6 @@ TEST(StringPieceTest, CheckCustom) {
StringPiece e;
std::string s2;
// starts_with
ASSERT_TRUE(a.starts_with(a));
ASSERT_TRUE(a.starts_with("foo"));
ASSERT_TRUE(a.starts_with(e));
ASSERT_TRUE(b.starts_with(s1));
ASSERT_TRUE(b.starts_with(b));
ASSERT_TRUE(b.starts_with(e));
ASSERT_TRUE(e.starts_with(""));
ASSERT_TRUE(!a.starts_with(b));
ASSERT_TRUE(!b.starts_with(a));
ASSERT_TRUE(!e.starts_with(a));
StringPiece c;
c = {"foobar", 6};
ASSERT_EQ(c, a);
@ -595,16 +583,6 @@ TYPED_TEST(CommonStringPieceTest, CheckComparisons2) {
ASSERT_GT(abc.compare(BasicStringPiece<TypeParam>(alphabet_y)), 0);
}
// Test operations only supported by std::string version.
TEST(StringPieceTest, CheckComparisons2) {
StringPiece abc("abcdefghijklmnopqrstuvwxyz");
// starts_with
ASSERT_TRUE(abc.starts_with(abc));
ASSERT_TRUE(abc.starts_with("abcdefghijklm"));
ASSERT_TRUE(!abc.starts_with("abcdefguvwxyz"));
}
TYPED_TEST(CommonStringPieceTest, StringCompareNotAmbiguous) {
ASSERT_TRUE(TestFixture::as_string("hello").c_str() ==
TestFixture::as_string("hello"));
@ -774,20 +752,6 @@ TEST(StringPieceTest, Compare) {
static_assert(piece.compare("ghij") == -1, "");
}
TEST(StringPieceTest, StartsWith) {
constexpr StringPiece piece("abc");
static_assert(piece.starts_with(""), "");
static_assert(piece.starts_with("a"), "");
static_assert(piece.starts_with("ab"), "");
static_assert(piece.starts_with("abc"), "");
static_assert(!piece.starts_with("b"), "");
static_assert(!piece.starts_with("bc"), "");
static_assert(!piece.starts_with("abcd"), "");
}
TEST(StringPieceTest, Substr) {
constexpr StringPiece piece = "abcdefghijklmnopqrstuvwxyz";

@ -313,12 +313,14 @@ enum class CompareCase {
INSENSITIVE_ASCII,
};
BASE_EXPORT bool StartsWith(StringPiece str,
StringPiece search_for,
CompareCase case_sensitivity);
BASE_EXPORT bool StartsWith(StringPiece16 str,
StringPiece16 search_for,
CompareCase case_sensitivity);
BASE_EXPORT bool StartsWith(
StringPiece str,
StringPiece search_for,
CompareCase case_sensitivity = CompareCase::SENSITIVE);
BASE_EXPORT bool StartsWith(
StringPiece16 str,
StringPiece16 search_for,
CompareCase case_sensitivity = CompareCase::SENSITIVE);
BASE_EXPORT bool EndsWith(
StringPiece str,
StringPiece search_for,

@ -171,13 +171,15 @@ BASE_EXPORT bool LowerCaseEqualsASCII(WStringPiece str,
BASE_EXPORT bool EqualsASCII(StringPiece16 str, StringPiece ascii);
BASE_EXPORT bool StartsWith(WStringPiece str,
WStringPiece search_for,
CompareCase case_sensitivity);
BASE_EXPORT bool StartsWith(
WStringPiece str,
WStringPiece search_for,
CompareCase case_sensitivity = CompareCase::SENSITIVE);
BASE_EXPORT bool EndsWith(WStringPiece str,
WStringPiece search_for,
CompareCase case_sensitivity);
BASE_EXPORT bool EndsWith(
WStringPiece str,
WStringPiece search_for,
CompareCase case_sensitivity = CompareCase::SENSITIVE);
BASE_EXPORT void ReplaceFirstSubstringAfterOffset(std::wstring* str,
size_t start_offset,

@ -49,7 +49,7 @@ StringPiece GetFeatureName(StringPiece feature) {
StringPiece feature_name = feature;
// Remove default info.
if (feature_name.starts_with("*"))
if (StartsWith(feature_name, "*"))
feature_name = feature_name.substr(1);
// Remove field_trial info.

@ -15,6 +15,7 @@
#include "base/no_destructor.h"
#include "base/notreached.h"
#include "base/optional.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/third_party/nspr/prtime.h"
#include "base/time/time_override.h"
@ -36,7 +37,7 @@ namespace {
// Adapted from absl::ConsumePrefix():
// https://cs.chromium.org/chromium/src/third_party/abseil-cpp/absl/strings/strip.h?l=45&rcl=2c22e9135f107a4319582ae52e2e3e6b201b6b7c
inline bool ConsumePrefix(StringPiece& str, StringPiece expected) {
if (!str.starts_with(expected))
if (!StartsWith(str, expected))
return false;
str.remove_prefix(expected.size());
return true;

@ -42,7 +42,7 @@ void TraceConfigCategoryFilter::InitializeFromString(
// Excluded categories start with '-'.
// Remove '-' from category string.
excluded_categories_.push_back(category.substr(1).as_string());
} else if (category.starts_with(TRACE_DISABLED_BY_DEFAULT(""))) {
} else if (StartsWith(category, TRACE_DISABLED_BY_DEFAULT(""))) {
disabled_categories_.push_back(category.as_string());
} else {
included_categories_.push_back(category.as_string());

@ -16,6 +16,7 @@
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/platform_thread.h"
#include "base/trace_event/trace_event.h"
@ -463,7 +464,7 @@ bool TraceEventETWExport::IsCategoryEnabled(StringPiece category_name) const {
// Otherwise return the corresponding default status by first checking if the
// category is disabled by default.
if (category_name.starts_with("disabled-by-default")) {
if (StartsWith(category_name, "disabled-by-default")) {
DCHECK(categories_status_.find(
kFilteredEventGroupNames[kDisabledOtherEventsGroupNameIndex]) !=
categories_status_.end());

@ -90,8 +90,7 @@ DatabaseTables ReadTables(sql::Database* db) {
"SELECT name FROM sqlite_master WHERE type='table'"));
while (table_names.Step()) {
const std::string table_name = table_names.ColumnString(0);
if (table_name == "meta" ||
base::StringPiece(table_name).starts_with("sqlite_"))
if (table_name == "meta" || base::StartsWith(table_name, "sqlite_"))
continue;
database_tables.tables[table_name] = ReadTable(db, table_name);
}

@ -5,6 +5,7 @@
#include "base/command_line.h"
#include "base/files/file_util.h"
#include "base/path_service.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "base/threading/thread_restrictions.h"
#include "build/build_config.h"
@ -129,7 +130,7 @@ void SendRangeResponse(net::test_server::ControllableHttpResponse* response,
ASSERT_NE(response->http_request()->headers.end(), it);
base::StringPiece range_header = it->second;
base::StringPiece kBytesPrefix = "bytes=";
ASSERT_TRUE(range_header.starts_with(kBytesPrefix));
ASSERT_TRUE(base::StartsWith(range_header, kBytesPrefix));
range_header.remove_prefix(kBytesPrefix.size());
auto dash_pos = range_header.find('-');
ASSERT_NE(std::string::npos, dash_pos);

@ -10,6 +10,7 @@
#include "base/files/scoped_temp_dir.h"
#include "base/path_service.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/drive/drive_integration_service.h"
#include "chrome/browser/chromeos/drive/drivefs_test_support.h"
@ -601,7 +602,7 @@ class MultiProfileDriveFileSystemExtensionApiTest :
base::FilePath::StringType(), &drivefs_dir);
auto profile_name_storage = profile->GetPath().BaseName().value();
base::StringPiece profile_name = profile_name_storage;
if (profile_name.starts_with("u-")) {
if (base::StartsWith(profile_name, "u-")) {
profile_name = profile_name.substr(2);
}
drivefs_dir = drivefs_dir.Append(base::StrCat({"drive-", profile_name}));

@ -13,6 +13,7 @@
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
#include "chrome/browser/chromeos/login/screens/recommend_apps/recommend_apps_fetcher_delegate.h"
@ -490,7 +491,7 @@ void RecommendAppsFetcherImpl::OnDownloaded(
RecordUmaResponseSize(response_body->size());
constexpr base::StringPiece json_xss_prevention_prefix(")]}'");
base::StringPiece response_body_json(*response_body);
if (response_body_json.starts_with(json_xss_prevention_prefix))
if (base::StartsWith(response_body_json, json_xss_prevention_prefix))
response_body_json.remove_prefix(json_xss_prevention_prefix.length());
base::Optional<base::Value> output = ParseResponse(response_body_json);
if (!output.has_value()) {

@ -123,8 +123,8 @@ void MergePrinterToSpecifics(const Printer& printer,
}
std::string MakeAndModel(base::StringPiece make, base::StringPiece model) {
return model.starts_with(make) ? model.as_string()
: base::JoinString({make, model}, " ");
return base::StartsWith(model, make) ? model.as_string()
: base::JoinString({make, model}, " ");
}
} // namespace chromeos

@ -85,7 +85,7 @@ class ParsedMetadata {
pdl = value.as_string();
} else if (key == "product") {
// Strip parens; ignore anything not enclosed in parens as malformed.
if (value.starts_with("(") && base::EndsWith(value, ")")) {
if (base::StartsWith(value, "(") && base::EndsWith(value, ")")) {
product = value.substr(1, value.size() - 2).as_string();
}
} else if (key == "rp") {
@ -188,7 +188,7 @@ bool ConvertToPrinter(const std::string& service_type,
// (possibly in addition to prefix-free versions). If we get a printer from a
// _print service type, it should be auto-configurable with IPP Everywhere.
printer.mutable_ppd_reference()->autoconf =
base::StringPiece(service_type).starts_with("_print._sub");
base::StartsWith(service_type, "_print._sub");
// Gather ppd identification candidates.
detected_printer->ppd_search_data.discovery_type =

@ -310,8 +310,7 @@ TEST_F(ExtensionInfoGeneratorUnitTest, BasicInfoTest) {
EXPECT_FALSE(info->file_access.is_active);
EXPECT_TRUE(info->incognito_access.is_enabled);
EXPECT_FALSE(info->incognito_access.is_active);
EXPECT_TRUE(
base::StringPiece(info->icon_url).starts_with("data:image/png;base64,"));
EXPECT_TRUE(base::StartsWith(info->icon_url, "data:image/png;base64,"));
// Strip out the kHostReadWrite permission created by the extension requesting
// host permissions above; runtime host permissions mean these are always

@ -6,6 +6,7 @@
#include "base/files/file_util.h"
#include "base/macros.h"
#include "base/scoped_observer.h"
#include "base/strings/string_util.h"
#include "base/test/scoped_feature_list.h"
#include "build/build_config.h"
#include "chrome/browser/background/background_mode_manager.h"
@ -388,9 +389,9 @@ class NativeMessagingLaunchBackgroundModeApiTest
void SetUpCommandLine(base::CommandLine* command_line) override {
NativeMessagingLaunchApiTest::SetUpCommandLine(command_line);
if (base::StringPiece(
::testing::UnitTest::GetInstance()->current_test_info()->name())
.starts_with("PRE")) {
if (base::StartsWith(
::testing::UnitTest::GetInstance()->current_test_info()->name(),
"PRE")) {
return;
}
set_exit_when_last_browser_closes(false);

@ -32,9 +32,9 @@ base::StringPiece ExtractUUID(const base::StringPiece& sink_id) {
return sink_id;
size_t prefix_length = 0;
if (sink_id.starts_with(kCastPrefix))
if (base::StartsWith(sink_id, kCastPrefix))
prefix_length = sizeof(kCastPrefix) - 1;
if (sink_id.starts_with(kDialPrefix))
if (base::StartsWith(sink_id, kDialPrefix))
prefix_length = sizeof(kDialPrefix) - 1;
if (prefix_length == 0)

@ -680,7 +680,7 @@ bool ShortcutFilenameMatcher::IsCanonical(
return true;
base::StringPiece16 shortcut_suffix(filename);
if (!shortcut_suffix.starts_with(profile_shortcut_name_))
if (!base::StartsWith(shortcut_suffix, profile_shortcut_name_))
return false;
shortcut_suffix.remove_prefix(profile_shortcut_name_.size());
@ -688,7 +688,7 @@ bool ShortcutFilenameMatcher::IsCanonical(
return false;
shortcut_suffix.remove_suffix(lnk_ext_.size());
if (shortcut_suffix.size() < 4 || !shortcut_suffix.starts_with(L" (") ||
if (shortcut_suffix.size() < 4 || !base::StartsWith(shortcut_suffix, L" (") ||
!base::EndsWith(shortcut_suffix, L")")) {
return false;
}

@ -18,6 +18,7 @@
#include "base/process/process_iterator.h"
#include "base/strings/string_split.h"
#include "base/strings/string_tokenizer.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/task/post_task.h"
#include "base/task/thread_pool.h"
@ -145,7 +146,7 @@ bool ReadNameFromStatus(pid_t pid, pid_t tid, std::string* out_name) {
base::StringTokenizer tokenizer(status, "\n");
while (tokenizer.GetNext()) {
base::StringPiece value_str(tokenizer.token_piece());
if (!value_str.starts_with("Name:"))
if (!base::StartsWith(value_str, "Name:"))
continue;
std::vector<base::StringPiece> split_value_str = base::SplitStringPiece(
value_str, "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY);

@ -12,6 +12,7 @@
#include "base/command_line.h"
#include "base/metrics/field_trial_params.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
@ -392,8 +393,8 @@ ExtensionsUI::ExtensionsUI(content::WebUI* web_ui)
// GetVisibleURL() because the load hasn't committed and this check isn't used
// for a security decision, however a stronger check will be implemented if we
// decide to invest more in this experiment.
if (web_ui->GetWebContents()->GetVisibleURL().query_piece().starts_with(
"checkup")) {
if (base::StartsWith(web_ui->GetWebContents()->GetVisibleURL().query_piece(),
"checkup")) {
ExtensionPrefs::Get(profile)->SetUserHasSeenExtensionsCheckupOnStartup(
true);
}

@ -16,6 +16,7 @@
#include "base/metrics/user_metrics_action.h"
#include "base/strings/strcat.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/autocomplete/chrome_autocomplete_provider_client.h"
#include "chrome/browser/autocomplete/chrome_autocomplete_scheme_classifier.h"
@ -111,7 +112,7 @@ new_tab_page::mojom::ThemePtr MakeTheme(const NtpTheme& ntp_theme) {
if (!ntp_theme.custom_background_url.is_empty()) {
base::StringPiece url = ntp_theme.custom_background_url.spec();
// TODO(crbug.com/1041125): Clean up when chrome-search://local-ntp removed.
if (url.starts_with("chrome-search://local-ntp/")) {
if (base::StartsWith(url, "chrome-search://local-ntp/")) {
background_image->url =
GURL("chrome-untrusted://new-tab-page/" +
url.substr(strlen("chrome-search://local-ntp/")).as_string());

@ -184,7 +184,7 @@ void ChangePictureHandler::HandlePhotoTaken(const base::ListValue* args) {
base::StringPiece url(image_url);
const char kDataUrlPrefix[] = "data:image/png;base64,";
const size_t kDataUrlPrefixLength = base::size(kDataUrlPrefix) - 1;
if (!url.starts_with(kDataUrlPrefix) ||
if (!base::StartsWith(url, kDataUrlPrefix) ||
!base::Base64Decode(url.substr(kDataUrlPrefixLength), &raw_data)) {
LOG(WARNING) << "Invalid image URL";
return;

@ -255,7 +255,7 @@ void GetCertificateInfo(const base::FilePath& filename,
bool IsMicrosoftModule(base::StringPiece16 subject) {
static constexpr wchar_t kMicrosoft[] = L"Microsoft ";
return subject.starts_with(kMicrosoft);
return base::StartsWith(subject, kMicrosoft);
}
StringMapping GetEnvironmentVariablesMapping(
@ -284,8 +284,7 @@ void CollapseMatchingPrefixInPath(const StringMapping& prefix_mapping,
size_t min_length = std::numeric_limits<size_t>::max();
for (const auto& mapping : prefix_mapping) {
DCHECK_EQ(base::i18n::ToLower(mapping.first), mapping.first);
if (base::StartsWith(path_copy, mapping.first,
base::CompareCase::SENSITIVE)) {
if (base::StartsWith(path_copy, mapping.first)) {
// Make sure the matching prefix is a full path component.
if (path_copy[mapping.first.length()] != '\\' &&
path_copy[mapping.first.length()] != '\0') {

@ -8,6 +8,7 @@
#include "base/strings/strcat.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
namespace installer {
@ -126,7 +127,7 @@ ExperimentLabels::LabelAndValue ExperimentLabels::FindLabel(
std::vector<base::StringPiece16> labels = Parse(value_);
for (const auto& label : labels) {
if (label.size() < label_name.size() + 2 ||
!label.starts_with(label_name) ||
!base::StartsWith(label, label_name) ||
label[label_name.size()] != kNameValueSeparator[0]) {
continue;
}

@ -6,6 +6,7 @@
#include <algorithm>
#include "base/strings/string_util.h"
#include "chromeos/printing/ppd_provider.h"
namespace chromeos {
@ -34,7 +35,7 @@ bool CanUseEpsonGenericPPD(const PrinterSearchData& sd) {
// The command set is retrieved from the 'CMD' field of the printer's IEEE
// 1284 Device ID.
for (base::StringPiece format : sd.printer_id.command_set()) {
if (format.starts_with("ESCPR")) {
if (base::StartsWith(format, "ESCPR")) {
return true;
}
}

@ -1227,7 +1227,7 @@ class PpdProviderImpl : public PpdProvider {
size_t best_idx = -1;
for (size_t i = 0; i < available_locales.size(); ++i) {
const std::string& available = available_locales[i];
if (base::StringPiece(browser_locale_).starts_with(available + "-") &&
if (base::StartsWith(browser_locale_, available + "-") &&
available.size() > best_len) {
best_len = available.size();
best_idx = i;

@ -17,6 +17,7 @@
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "components/autofill/content/renderer/form_autofill_util.h"
@ -93,9 +94,9 @@ blink::FormElementPiiType MapTypePredictionToFormElementPiiType(
return blink::FormElementPiiType::kUnknown;
}
if (type.starts_with("EMAIL_"))
if (base::StartsWith(type, "EMAIL_"))
return blink::FormElementPiiType::kEmail;
if (type.starts_with("PHONE_"))
if (base::StartsWith(type, "PHONE_"))
return blink::FormElementPiiType::kPhone;
return blink::FormElementPiiType::kOthers;
}

@ -48,9 +48,10 @@ bool ParseETagHeader(const base::StringPiece& etag_header_value_in,
// Remove the weak prefix, then remove the begin and the end quotes.
const char kWeakETagPrefix[] = "W/";
if (etag_header_value.starts_with(kWeakETagPrefix))
if (base::StartsWith(etag_header_value, kWeakETagPrefix))
etag_header_value.remove_prefix(base::size(kWeakETagPrefix) - 1);
if (etag_header_value.size() >= 2 && etag_header_value.starts_with("\"") &&
if (etag_header_value.size() >= 2 &&
base::StartsWith(etag_header_value, "\"") &&
base::EndsWith(etag_header_value, "\"")) {
etag_header_value.remove_prefix(1);
etag_header_value.remove_suffix(1);

@ -122,7 +122,7 @@ void DriveNotificationManager::OnIncomingInvalidation(
std::string DriveNotificationManager::GetOwnerName() const { return "Drive"; }
bool DriveNotificationManager::IsPublicTopic(const syncer::Topic& topic) const {
return base::StringPiece(topic).starts_with(kTeamDriveChangePrefix);
return base::StartsWith(topic, kTeamDriveChangePrefix);
}
void DriveNotificationManager::AddObserver(
@ -291,7 +291,7 @@ syncer::Topic DriveNotificationManager::GetTeamDriveInvalidationTopic(
std::string DriveNotificationManager::ExtractTeamDriveId(
base::StringPiece topic_name) const {
base::StringPiece prefix = kTeamDriveChangePrefix;
if (!topic_name.starts_with(prefix)) {
if (!base::StartsWith(topic_name, prefix)) {
return {};
}
return topic_name.substr(prefix.size()).as_string();

@ -106,7 +106,7 @@ bool IsValidLookingOwner(base::StringPiece owner) {
return owner.find(".", at_pos) != std::string::npos;
}
if (owner.starts_with("//")) {
if (base::StartsWith(owner, "//")) {
// Looks like a path to a file. It would be nice to check that the file
// actually exists here, but that's not possible because when this test
// runs it runs in an isolated environment. To check for the presence of the

@ -16,6 +16,7 @@
#include "base/metrics/histogram_macros.h"
#include "base/observer_list.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/task/post_task.h"
#include "build/build_config.h"
#include "components/gcm_driver/gcm_driver.h"
@ -98,9 +99,9 @@ std::string GetValueFromMessage(const gcm::IncomingMessage& message,
//
// If the provided sender does not match either pattern, return it unchanged.
std::string UnpackPrivateTopic(base::StringPiece private_topic) {
if (private_topic.starts_with("/topics/private/")) {
if (base::StartsWith(private_topic, "/topics/private/")) {
return private_topic.substr(strlen("/topics")).as_string();
} else if (private_topic.starts_with("/topics/")) {
} else if (base::StartsWith(private_topic, "/topics/")) {
return private_topic.substr(strlen("/topics/")).as_string();
} else {
return private_topic.as_string();

@ -34,7 +34,7 @@ bool CSVFieldParser::NextField(base::StringPiece* field_contents) {
*field_contents =
base::StringPiece(row_.data() + start, position_ - start - 1);
if (field_contents->starts_with("\"")) {
if (base::StartsWith(*field_contents, "\"")) {
DCHECK(base::EndsWith(*field_contents, "\"")) << *field_contents;
DCHECK_GE(field_contents->size(), 2u);
field_contents->remove_prefix(1);

@ -145,7 +145,7 @@ class EmbeddedURLExtractor {
// ("webcache.googleusercontent.com/search?q=cache:...").
std::string query;
if (url.host_piece() == kGoogleWebCacheHost &&
url.path_piece().starts_with(kGoogleWebCachePathPrefix) &&
base::StartsWith(url.path_piece(), kGoogleWebCachePathPrefix) &&
net::GetValueForKeyInQuery(url, "q", &query)) {
std::string fingerprint;
std::string scheme;
@ -159,8 +159,7 @@ class EmbeddedURLExtractor {
// Check for Google translate URLs ("translate.google.TLD/...?...&u=URL" or
// "translate.googleusercontent.com/...?...&u=URL").
bool is_translate = false;
if (base::StartsWith(url.host_piece(), kGoogleTranslateSubdomain,
base::CompareCase::SENSITIVE)) {
if (base::StartsWith(url.host_piece(), kGoogleTranslateSubdomain)) {
// Remove the "translate." prefix.
GURL::Replacements replace;
replace.SetHostStr(
@ -174,8 +173,7 @@ class EmbeddedURLExtractor {
is_translate = google_util::IsGoogleDomainUrl(
trimmed, google_util::DISALLOW_SUBDOMAIN,
google_util::DISALLOW_NON_STANDARD_PORTS) &&
!base::StartsWith(trimmed.host_piece(), "www.",
base::CompareCase::SENSITIVE);
!base::StartsWith(trimmed.host_piece(), "www.");
}
bool is_alternate_translate =
url.host_piece() == kAlternateGoogleTranslateHost;

@ -549,7 +549,7 @@ bool TemplateURLRef::ExtractSearchTermsFromURL(
// not a match.
if (source.size() < (search_term_value_prefix_.size() +
search_term_value_suffix_.size()) ||
!source.starts_with(search_term_value_prefix_) ||
!base::StartsWith(source, search_term_value_prefix_) ||
!base::EndsWith(source, search_term_value_suffix_))
return false;
position =
@ -578,7 +578,7 @@ bool TemplateURLRef::ExtractSearchTermsFromURL(
base::StringPiece(source).substr(value.begin, value.len);
if (search_term.size() < (search_term_value_prefix_.size() +
search_term_value_suffix_.size()) ||
!search_term.starts_with(search_term_value_prefix_) ||
!base::StartsWith(search_term, search_term_value_prefix_) ||
!base::EndsWith(search_term, search_term_value_suffix_))
continue;
@ -863,7 +863,8 @@ bool TemplateURLRef::PathIsEqual(const GURL& url) const {
if (!path_wildcard_present_)
return path == path_prefix_;
return ((path.length() >= path_prefix_.length() + path_suffix_.length()) &&
path.starts_with(path_prefix_) && base::EndsWith(path, path_suffix_));
base::StartsWith(path, path_prefix_) &&
base::EndsWith(path, path_suffix_));
}
void TemplateURLRef::ParseHostAndSearchTermKey(

@ -183,7 +183,7 @@ std::unique_ptr<EncodedLogo> ParseDoodleLogoResponse(
bool* parsing_failed) {
// The response may start with )]}'. Ignore this.
base::StringPiece response_sp(*response);
if (response_sp.starts_with(kResponsePreamble))
if (base::StartsWith(response_sp, kResponsePreamble))
response_sp.remove_prefix(strlen(kResponsePreamble));
// Default parsing failure to be true.

@ -10,6 +10,7 @@
#include "base/files/file_path.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/win/scoped_handle.h"
#include "base/win/windows_version.h"
#include "components/services/quarantine/common.h"
@ -58,11 +59,11 @@ bool ZoneIdentifierPresentForFile(const base::FilePath& path,
// a test. If Windows starts adding whitespace or doing anything fancier than
// ASCII, then we'd have to update this.
for (const auto& line : lines) {
if (line.starts_with("ZoneId="))
if (base::StartsWith(line, "ZoneId="))
found_zone_id = line.substr(7);
else if (line.starts_with("HostUrl="))
else if (base::StartsWith(line, "HostUrl="))
found_host_url = line.substr(8);
else if (line.starts_with("ReferrerUrl="))
else if (base::StartsWith(line, "ReferrerUrl="))
found_referrer_url = line.substr(12);
}

@ -8,6 +8,7 @@
#include "base/macros.h"
#include "base/stl_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "components/services/storage/dom_storage/async_dom_storage_database.h"
#include "third_party/blink/public/common/dom_storage/session_storage_namespace_id.h"
@ -148,9 +149,10 @@ bool SessionStorageMetadata::ParseNamespaces(
}
// The key must start with 'namespace-'.
if (!key_as_string.starts_with(base::StringPiece(
reinterpret_cast<const char*>(kNamespacePrefixBytes),
kNamespacePrefixLength))) {
if (!base::StartsWith(key_as_string,
base::StringPiece(reinterpret_cast<const char*>(
kNamespacePrefixBytes),
kNamespacePrefixLength))) {
LOG(ERROR) << "Key must start with 'namespace-': " << key_as_string;
error = true;
break;

@ -8,6 +8,7 @@
#include "base/check_op.h"
#include "base/memory/ptr_util.h"
#include "base/strings/string_util.h"
#include "base/trace_event/trace_event.h"
#include "components/services/storage/indexed_db/scopes/leveldb_scope.h"
#include "components/services/storage/indexed_db/scopes/leveldb_scopes.h"
@ -72,8 +73,9 @@ leveldb::Status TransactionalLevelDBTransaction::Get(const StringPiece& key,
#if DCHECK_IS_ON()
DCHECK(!finished_);
const std::vector<uint8_t>& prefix = db_->scopes()->metadata_key_prefix();
DCHECK(!key.starts_with(base::StringPiece(
reinterpret_cast<const char*>(prefix.data()), prefix.size())));
DCHECK(!base::StartsWith(
key, base::StringPiece(reinterpret_cast<const char*>(prefix.data()),
prefix.size())));
#endif
leveldb::Status s = scope_->WriteChangesAndUndoLog();
if (!s.ok() && !s.IsNotFound())
@ -174,8 +176,9 @@ leveldb::Status LevelDBDirectTransaction::Get(const StringPiece& key,
#if DCHECK_IS_ON()
DCHECK(!IsFinished());
const std::vector<uint8_t>& prefix = db_->scopes()->metadata_key_prefix();
DCHECK(!key.starts_with(base::StringPiece(
reinterpret_cast<const char*>(prefix.data()), prefix.size())));
DCHECK(!base::StartsWith(
key, base::StringPiece(reinterpret_cast<const char*>(prefix.data()),
prefix.size())));
#endif
leveldb::Status s = db_->Get(key, value, found);
DCHECK(s.ok() || !*found);

@ -14,6 +14,7 @@
#include "base/notreached.h"
#include "base/strings/char_traits.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "components/viz/service/display/static_geometry_binding.h"
#include "gpu/command_buffer/client/gles2_interface.h"
@ -23,7 +24,7 @@
constexpr base::StringPiece StripLambda(base::StringPiece shader) {
// Must contain at least "[]() {}".
DCHECK(shader.starts_with("[]() {"));
DCHECK_EQ(shader.substr(0, 6), "[]() {");
DCHECK_EQ(shader.back(), '}');
shader.remove_prefix(6);
shader.remove_suffix(1);

@ -304,13 +304,13 @@ void AccessibilityEventRecorderWin::OnWinEventHook(HWINEVENTHOOK handle,
base::string16(attributes_bstr.Get(), attributes_bstr.Length()),
base::string16(1, ';'), base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
for (base::string16& attr : ia2_attributes) {
if (base::StringPiece16(attr).starts_with(L"class:"))
if (base::StartsWith(attr, L"class:"))
obj_class = attr.substr(6); // HTML or view class
if (base::StringPiece16(attr).starts_with(L"id:")) {
if (base::StartsWith(attr, L"id:")) {
html_id = base::string16(L"#");
html_id += attr.substr(3);
}
if (base::StringPiece16(attr).starts_with(L"tag:")) {
if (base::StartsWith(attr, L"tag:")) {
html_tag = attr.substr(4);
}
}

@ -40,6 +40,7 @@
#include "base/metrics/histogram_functions.h"
#include "base/notreached.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/utf_string_conversions.h"
#include "content/browser/appcache/appcache.h"
#include "third_party/blink/public/common/origin_trials/trial_token.h"
@ -217,8 +218,7 @@ GURL ParseUrlToken(base::StringPiece url_token, const GURL& manifest_url) {
}
bool IsUrlWithinScope(const GURL& url, const GURL& scope) {
return base::StartsWith(url.spec(), scope.spec(),
base::CompareCase::SENSITIVE);
return base::StartsWith(url.spec(), scope.spec());
}
// Records UMA metrics for parsing one AppCache manifest.
@ -344,16 +344,16 @@ bool ParseManifest(const GURL& manifest_url,
// Discard a leading UTF-8 Byte-Order-Mark (BOM) (0xEF, 0xBB, 0xBF);
static constexpr base::StringPiece kUtf8Bom("\xEF\xBB\xBF");
if (data.starts_with(kUtf8Bom))
if (base::StartsWith(data, kUtf8Bom))
data = data.substr(kUtf8Bom.length());
// The manifest has to start with a well-defined signature.
static constexpr base::StringPiece kSignature("CACHE MANIFEST");
static constexpr base::StringPiece kChromiumSignature(
"CHROMIUM CACHE MANIFEST");
if (data.starts_with(kSignature)) {
if (base::StartsWith(data, kSignature)) {
data = data.substr(kSignature.length());
} else if (data.starts_with(kChromiumSignature)) {
} else if (base::StartsWith(data, kChromiumSignature)) {
// Chrome recognizes a separate signature, CHROMIUM CACHE MANIFEST. This was
// built so that manifests that use the Chrome-only feature
// CHROMIUM-INTERCEPT will be ignored by other browsers.

@ -1541,7 +1541,7 @@ bool ChildProcessSecurityPolicyImpl::CanAccessDataForOrigin(
const GURL& lock_url = actual_process_lock.lock_url();
// SitePerProcessBrowserTest.TwoBlobURLsWithNullOriginDontShareProcess.
if (lock_url.SchemeIsBlob() &&
lock_url.path_piece().starts_with("null/")) {
base::StartsWith(lock_url.path_piece(), "null/")) {
return true;
}

@ -9,6 +9,7 @@
#include "base/metrics/field_trial_params.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "build/build_config.h"
#include "content/browser/frame_host/frame_tree_node.h"
#include "content/browser/frame_host/render_frame_host_delegate.h"
@ -648,7 +649,7 @@ bool BackForwardCacheImpl::IsAllowed(const GURL& current_url) {
const auto& entry = allowed_urls_.find(current_url.host());
if (entry != allowed_urls_.end()) {
for (auto allowed_path : entry->second) {
if (current_url.path_piece().starts_with(allowed_path))
if (base::StartsWith(current_url.path_piece(), allowed_path))
return true;
}
}

@ -55,7 +55,7 @@ bool IsolatedOriginPattern::Parse(const base::StringPiece& unparsed_pattern) {
if (host_part.size() == 0)
return false;
if (host_part.starts_with(kAllSubdomainsWildcard)) {
if (base::StartsWith(host_part, kAllSubdomainsWildcard)) {
isolate_all_subdomains_ = true;
host_part.remove_prefix(strlen(kAllSubdomainsWildcard));
}

@ -9,6 +9,7 @@
#include "base/base64.h"
#include "base/big_endian.h"
#include "base/numerics/safe_conversions.h"
#include "base/strings/string_util.h"
#include "net/base/io_buffer.h"
namespace content {
@ -39,7 +40,7 @@ MerkleIntegritySourceStream::MerkleIntegritySourceStream(
// TODO(ksakamoto): Use appropriate SourceType.
: net::FilterSourceStream(SourceStream::TYPE_NONE, std::move(upstream)) {
std::string next_proof;
if (!digest_header_value.starts_with(kMiSha256Header) ||
if (!base::StartsWith(digest_header_value, kMiSha256Header) ||
!base::Base64Decode(digest_header_value.substr(kMiSha256HeaderLength),
&next_proof) ||
next_proof.size() != SHA256_DIGEST_LENGTH) {

@ -7,6 +7,7 @@
#include "base/base64.h"
#include "base/feature_list.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "components/link_header_util/link_header_util.h"
#include "content/browser/loader/cross_origin_read_blocking_checker.h"
@ -530,7 +531,7 @@ bool CanUseEntry(const PrefetchedSignedExchangeCacheEntry& entry,
// This method support the form of "sha256-<base64-hash-value>".
bool ExtractSHA256HashValueFromString(const base::StringPiece value,
net::SHA256HashValue* out) {
if (!value.starts_with("sha256-"))
if (!base::StartsWith(value, "sha256-"))
return false;
const base::StringPiece base64_str = value.substr(7);
std::string decoded;

@ -69,7 +69,8 @@ constexpr char kDynamicFrameMarker[] = "<!--dynamicFrame";
constexpr size_t kMaxRequestedNameSize = 80;
bool IsNameWithFramePath(base::StringPiece name) {
return name.starts_with(kFramePathPrefix) && base::EndsWith(name, "-->") &&
return base::StartsWith(name, kFramePathPrefix) &&
base::EndsWith(name, "-->") &&
(kFramePathPrefixLength + kFramePathSuffixLength) < name.size();
}

@ -99,10 +99,12 @@ std::string GetLowEntropyCpuArchitecture() {
// internal std::string, resulting in a memory violation.
std::string cpu_info_str = BuildCpuInfo();
base::StringPiece cpu_info = cpu_info_str;
if (cpu_info.starts_with("arm") || cpu_info.starts_with("aarch")) {
if (base::StartsWith(cpu_info, "arm") ||
base::StartsWith(cpu_info, "aarch")) {
return "arm";
} else if ((cpu_info.starts_with("i") && cpu_info.substr(2, 2) == "86") ||
cpu_info.starts_with("x86")) {
} else if ((base::StartsWith(cpu_info, "i") &&
cpu_info.substr(2, 2) == "86") ||
base::StartsWith(cpu_info, "x86")) {
return "x86";
}
#elif defined(OS_WIN)

@ -19,7 +19,7 @@ bool DeviceIndexFromDevicePath(base::StringPiece path,
base::StringPiece prefix,
int* index) {
DCHECK(index);
if (!path.starts_with(prefix))
if (!base::StartsWith(path, prefix))
return false;
base::StringPiece index_str = path;
index_str.remove_prefix(prefix.length());

@ -215,9 +215,9 @@ ExtensionWebRequestEventRouter::EventTypes GetEventTypeFromEventName(
strlen(webview::kWebViewEventPrefix);
// Canonicalize the |event_name| to the request stage.
if (event_name.starts_with(kWebRequestEventPrefix))
if (base::StartsWith(event_name, kWebRequestEventPrefix))
event_name.remove_prefix(kWebRequestEventPrefixLen);
else if (event_name.starts_with(webview::kWebViewEventPrefix))
else if (base::StartsWith(event_name, webview::kWebViewEventPrefix))
event_name.remove_prefix(kWebViewEventPrefixLen);
else
return ExtensionWebRequestEventRouter::kInvalidEvent;

@ -12,6 +12,7 @@
#include "base/bind.h"
#include "base/memory/writable_shared_memory_region.h"
#include "base/strings/string_util.h"
#include "base/version.h"
#include "build/build_config.h"
#include "content/public/browser/browser_context.h"
@ -97,10 +98,10 @@ bool UserScriptLoader::ParseMetadataHeader(const base::StringPiece& script_text,
line_end - line_start);
if (!in_metadata) {
if (line.starts_with(kUserScriptBegin))
if (base::StartsWith(line, kUserScriptBegin))
in_metadata = true;
} else {
if (line.starts_with(kUserScriptEng))
if (base::StartsWith(line, kUserScriptEng))
break;
std::string value;

@ -303,7 +303,7 @@ URLPattern::ParseResult URLPattern::Parse(base::StringPiece pattern) {
if (host_piece == "*") {
match_subdomains_ = true;
host_piece = base::StringPiece();
} else if (host_piece.starts_with("*.")) {
} else if (base::StartsWith(host_piece, "*.")) {
if (host_piece.length() == 2) {
// We don't allow just '*.' as a host.
return ParseResult::kEmptyHost;
@ -559,8 +559,7 @@ bool URLPattern::MatchesPath(base::StringPiece test) const {
// need to match hosted apps on e.g. 'google.com' also run on 'google.com/'.
// The below if is a no-copy way of doing (test + "/*" == path_escaped_).
if (path_escaped_.length() == test.length() + 2 &&
base::StartsWith(path_escaped_.c_str(), test,
base::CompareCase::SENSITIVE) &&
base::StartsWith(path_escaped_.c_str(), test) &&
base::EndsWith(path_escaped_, "/*")) {
return true;
}

@ -21,6 +21,7 @@
#include "base/no_destructor.h"
#include "base/strings/strcat.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/task/post_task.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
@ -405,7 +406,7 @@ void ContentDirectoryLoaderFactory::CreateLoaderAndStart(
// Fuchsia paths do not support the notion of absolute paths, so strip the
// leading slash from the URL's path fragment.
base::StringPiece requested_path = request.url.path_piece();
DCHECK(requested_path.starts_with("/"));
DCHECK(base::StartsWith(requested_path, "/"));
requested_path.remove_prefix(1);
fidl::InterfaceHandle<fuchsia::io::Node> file_handle;

@ -186,7 +186,7 @@ bool ParseMultipartResponse(const std::string& content_type,
return false;
base::StringPiece content_type_piece(content_type);
if (!content_type_piece.starts_with(kMultipartMixedMimeTypePrefix)) {
if (!base::StartsWith(content_type_piece, kMultipartMixedMimeTypePrefix)) {
return false;
}
content_type_piece.remove_prefix(
@ -228,7 +228,7 @@ bool ParseMultipartResponse(const std::string& content_type,
}
if (state == STATE_PART_HTTP_STATUS_LINE) {
if (line.starts_with(kHttpStatusPrefix)) {
if (base::StartsWith(line, kHttpStatusPrefix)) {
int int_code;
base::StringToInt(
line.substr(base::StringPiece(kHttpStatusPrefix).size()),

@ -86,7 +86,7 @@ HeadlessPrintManager::PageRangeTextToPages(base::StringPiece page_range_text,
} else if (range_string == "-") {
range.from = 1;
range.to = pages_count;
} else if (range_string.starts_with("-")) {
} else if (base::StartsWith(range_string, "-")) {
range.from = 1;
if (!base::StringToInt(range_string.substr(1), &range.to))
return SYNTAX_ERROR;

@ -27,7 +27,7 @@ bool IsXCallbackURL(const GURL& url) {
return url.host_piece() == kXCallbackURLHost;
base::StringPiece path_piece = url.path_piece();
if (path_piece.starts_with("//"))
if (base::StartsWith(path_piece, "//"))
path_piece = path_piece.substr(2, base::StringPiece::npos);
size_t pos = path_piece.find('/', 0);

@ -22,7 +22,7 @@ enum LensFacing { FRONT = 0, BACK = 1 };
bool ParseCameraId(const base::StringPiece& sub_key, int* camera_id) {
const base::StringPiece camera_id_prefix = "camera";
if (!sub_key.starts_with(camera_id_prefix))
if (!base::StartsWith(sub_key, camera_id_prefix))
return false;
return base::StringToInt(sub_key.substr(camera_id_prefix.size()), camera_id);
}
@ -100,7 +100,7 @@ std::string CameraConfigChromeOS::GetUsbId(const std::string& device_id) const {
// |device_id| is of the form "/dev/video2". We want to retrieve "video2"
// into |file_name|.
const std::string device_dir = "/dev/";
if (!base::StartsWith(device_id, device_dir, base::CompareCase::SENSITIVE)) {
if (!base::StartsWith(device_id, device_dir)) {
DLOG(ERROR) << "device_id is invalid: " << device_id;
return std::string();
}
@ -145,7 +145,8 @@ void CameraConfigChromeOS::InitializeDeviceInfo(
base::SplitResult::SPLIT_WANT_NONEMPTY);
for (const base::StringPiece& line : lines) {
if (line.starts_with("#")) // Ignore the comments that starts with "#".
// Ignore the comments that starts with "#".
if (base::StartsWith(line, "#"))
continue;
const std::vector<base::StringPiece> key_value = base::SplitStringPiece(
line, "=", base::WhitespaceHandling::TRIM_WHITESPACE,

@ -3,6 +3,7 @@
// found in the LICENSE file.
#include "net/base/hash_value.h"
#include "base/strings/string_util.h"
#include <stdlib.h>
#include <algorithm>
@ -43,7 +44,7 @@ HashValue::HashValue(const SHA256HashValue& hash)
bool HashValue::FromString(const base::StringPiece value) {
base::StringPiece base64_str;
if (value.starts_with("sha256/")) {
if (base::StartsWith(value, "sha256/")) {
tag_ = HASH_VALUE_SHA256;
base64_str = value.substr(7);
} else {

@ -4,6 +4,7 @@
#include "net/cert/internal/crl.h"
#include "base/strings/string_util.h"
#include "net/cert/internal/cert_errors.h"
#include "net/cert/internal/parsed_certificate.h"
#include "net/cert/internal/test_helpers.h"
@ -174,9 +175,9 @@ TEST_P(CheckCRLTest, FromFile) {
base::Time::UnixEpoch() + base::TimeDelta::FromSeconds(1489017600);
CRLRevocationStatus expected_revocation_status = CRLRevocationStatus::UNKNOWN;
if (file_name.starts_with("good"))
if (base::StartsWith(file_name, "good"))
expected_revocation_status = CRLRevocationStatus::GOOD;
else if (file_name.starts_with("revoked"))
else if (base::StartsWith(file_name, "revoked"))
expected_revocation_status = CRLRevocationStatus::REVOKED;
CRLRevocationStatus revocation_status =

@ -484,7 +484,7 @@ bool GetSubjectPublicKeyBytes(const der::Input& spki_tlv, der::Input* spk_tlv) {
// ExtractSubjectPublicKeyFromSPKI() includes the unused bit count. For this
// application, the unused bit count must be zero, and is not included in the
// result.
if (!spk_strpiece.starts_with("\0"))
if (!base::StartsWith(spk_strpiece, "\0"))
return false;
spk_strpiece.remove_prefix(1);

@ -9,6 +9,7 @@
#include "base/files/file_util.h"
#include "base/path_service.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "net/cert/internal/cert_error_params.h"
#include "net/cert/internal/cert_errors.h"
#include "net/cert/pem.h"
@ -24,7 +25,7 @@ bool GetValue(base::StringPiece prefix,
base::StringPiece line,
std::string* value,
bool* has_value) {
if (!line.starts_with(prefix))
if (!base::StartsWith(line, prefix))
return false;
if (*has_value) {
@ -255,7 +256,7 @@ bool ReadVerifyCertChainTestFromFile(const std::string& file_path_ascii,
ADD_FAILURE() << "Unrecognized last_cert_trust: " << value;
return false;
}
} else if (line_piece.starts_with("#")) {
} else if (base::StartsWith(line_piece, "#")) {
// Skip comments.
continue;
} else if (line_piece == kExpectedErrors) {

@ -44,7 +44,7 @@ bool PEMTokenizer::GetNext() {
std::vector<PEMType>::const_iterator it;
// Check to see if it is of an acceptable block type.
for (it = block_types_.begin(); it != block_types_.end(); ++it) {
if (!str_.substr(pos_).starts_with(it->header))
if (!base::StartsWith(str_.substr(pos_), it->header))
continue;
// Look for a footer matching the header. If none is found, then all

@ -513,7 +513,7 @@ bool X509Certificate::VerifyHostname(
SplitOnChar(reference_name, '.', &reference_host, &reference_domain);
bool allow_wildcards = false;
if (!reference_domain.empty()) {
DCHECK(reference_domain.starts_with("."));
DCHECK(base::StartsWith(reference_domain, "."));
// Do not allow wildcards for public/ICANN registry controlled domains -
// that is, prevent *.com or *.co.uk as valid presented names, but do not

@ -4,6 +4,7 @@
// The rules for parsing content-types were borrowed from Firefox:
// http://lxr.mozilla.org/mozilla/source/netwerk/base/src/nsURLHelper.cpp#834
#include "base/strings/string_util.h"
#include "net/http/http_util.h"
@ -1151,7 +1152,7 @@ bool HttpUtil::ParseAcceptEncoding(const std::string& accept_encoding,
if (qvalue.empty())
return false;
if (qvalue[0] == '1') {
if (base::StringPiece("1.000").starts_with(qvalue)) {
if (base::StartsWith("1.000", qvalue)) {
allowed_encodings->insert(base::ToLowerASCII(encoding));
continue;
}

@ -83,7 +83,7 @@ void ConvertResponseToUTF16(const std::string& charset,
// Guess the charset by looking at the BOM.
base::StringPiece bytes_str(bytes);
for (const auto& bom : kBomMappings) {
if (bytes_str.starts_with(bom.prefix)) {
if (base::StartsWith(bytes_str, bom.prefix)) {
return ConvertResponseToUTF16(
bom.charset,
// Strip the BOM in the converted response.

@ -34,8 +34,8 @@ const char kBypassSimpleHostnames[] = "<local>";
bool IsLinkLocalIP(const GURL& url) {
// Quick fail if definitely not link-local, to avoid doing unnecessary work in
// common case.
if (!(url.host_piece().starts_with("169.254.") ||
url.host_piece().starts_with("["))) {
if (!(base::StartsWith(url.host_piece(), "169.254.") ||
base::StartsWith(url.host_piece(), "["))) {
return false;
}
@ -53,7 +53,7 @@ bool IsLinkLocalIP(const GURL& url) {
// addresses. However for proxy resolving such URLs should bypass the use
// of a PAC script, since the destination is local.
bool IsIPv4MappedLoopback(const GURL& url) {
if (!url.host_piece().starts_with("[::ffff"))
if (!base::StartsWith(url.host_piece(), "[::ffff"))
return false;
IPAddress ip_address;

@ -5,6 +5,7 @@
#include "net/test/revocation_builder.h"
#include "base/hash/sha1.h"
#include "base/strings/string_util.h"
#include "net/cert/asn1_util.h"
#include "net/cert/x509_util.h"
#include "net/der/encode_values.h"
@ -108,7 +109,7 @@ std::string PKeyToSPK(const EVP_PKEY* pkey) {
// ExtractSubjectPublicKeyFromSPKI() includes the unused bit count. For this
// application, the unused bit count must be zero, and is not included in the
// result.
if (!spk.starts_with("\0")) {
if (!base::StartsWith(spk, "\0")) {
ADD_FAILURE();
return std::string();
}

@ -69,7 +69,7 @@ bool MatchCertificateName(base::StringPiece name, base::StringPiece pin_name) {
first_word = first_word.substr(0, first_word.size() - 1);
}
if (first_word.starts_with("*.")) {
if (base::StartsWith(first_word, "*.")) {
first_word = first_word.substr(2, first_word.size() - 2);
}

@ -433,7 +433,7 @@ int ExtractPrintPreviewPageIndex(base::StringPiece src_url) {
}
bool IsPrintPreviewUrl(base::StringPiece url) {
return url.starts_with(kChromePrint);
return base::StartsWith(url, kChromePrint);
}
bool IsPreviewingPDF(int print_preview_page_count) {
@ -503,7 +503,8 @@ bool OutOfProcessInstance::Init(uint32_t argc,
std::string document_url = document_url_var.AsString();
base::StringPiece document_url_piece(document_url);
is_print_preview_ = IsPrintPreviewUrl(document_url_piece);
CHECK(document_url_piece.starts_with(kChromeExtension) || is_print_preview_);
CHECK(base::StartsWith(document_url_piece, kChromeExtension) ||
is_print_preview_);
// Check if the plugin is full frame. This is passed in from JS.
for (uint32_t i = 0; i < argc; ++i) {

@ -353,8 +353,8 @@ PrintingContext::Result PrintingContextChromeos::UpdatePrinterSettings(
DCHECK(printer_);
std::string uri_string = printer_->GetUri();
const base::StringPiece uri(uri_string);
if (!uri.starts_with("ipps:") && !uri.starts_with("https:") &&
!uri.starts_with("usb:") && !uri.starts_with("ippusb:")) {
if (!base::StartsWith(uri, "ipps:") && !base::StartsWith(uri, "https:") &&
!base::StartsWith(uri, "usb:") && !base::StartsWith(uri, "ippusb:")) {
return OnError();
}
}

@ -181,9 +181,10 @@ PrinterSemanticCapsAndDefaults::Paper ParsePaper(base::StringPiece value) {
// We expect at least a display string and a dimension string.
// Additionally, we drop the "custom_min*" and "custom_max*" special
// "sizes" (not for users' eyes).
if (pieces.size() < 2 || value.starts_with(kMediaCustomMinPrefix) ||
value.starts_with(kMediaCustomMaxPrefix))
if (pieces.size() < 2 || base::StartsWith(value, kMediaCustomMinPrefix) ||
base::StartsWith(value, kMediaCustomMaxPrefix)) {
return PrinterSemanticCapsAndDefaults::Paper();
}
base::StringPiece dimensions = pieces.back();

@ -319,7 +319,7 @@ TEST_F(GeolocationNetworkProviderTest, NonEmptyApiKey) {
const GURL& request_url =
test_url_loader_factory_.pending_requests()->back().request.url;
EXPECT_TRUE(request_url.has_query());
EXPECT_TRUE(request_url.query_piece().starts_with("key="));
EXPECT_TRUE(base::StartsWith(request_url.query_piece(), "key="));
}
// Tests that, after StartProvider(), a TestURLFetcher can be extracted,

@ -137,7 +137,8 @@ size_t FindFirstJavascriptLineTerminator(const base::StringPiece& hay,
// TODO(lukasza): Prevent matching 3 bytes that span/straddle 2 UTF8
// characters.
base::StringPiece substr = hay.substr(pos);
if (substr.starts_with("\u2028") || substr.starts_with("\u2029"))
if (base::StartsWith(substr, "\u2028") ||
base::StartsWith(substr, "\u2029"))
break;
pos++; // Skip the \xe2 character.
@ -158,8 +159,8 @@ size_t FindFirstJavascriptLineTerminator(const base::StringPiece& hay,
// terminating character.
SniffingResult MaybeSkipHtmlComment(StringPiece* data) {
constexpr StringPiece kStartString = "<!--";
if (!data->starts_with(kStartString)) {
if (kStartString.starts_with(*data))
if (!base::StartsWith(*data, kStartString)) {
if (base::StartsWith(kStartString, *data))
return CrossOriginReadBlocking::kMaybe;
return CrossOriginReadBlocking::kNo;
}

@ -79,7 +79,7 @@ int ModuleCreate(sqlite3* sqlite_db,
}
base::StringPiece table_name(argv[kVirtualTableNameArgument]);
if (!table_name.starts_with("recover_")) {
if (!base::StartsWith(table_name, "recover_")) {
// In the future, we may deploy UMA metrics that use the virtual table name
// to attribute recovery events to Chrome features. In preparation for that
// future, require all recovery table names to start with "recover_".

@ -15,6 +15,7 @@
#include "base/logging.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/threading/thread.h"
#include "tools/android/forwarder2/common.h"
@ -119,7 +120,7 @@ class ClientDelegate : public Daemon::ClientDelegate {
DCHECK(static_cast<unsigned int>(bytes_read) < sizeof(buf));
buf[bytes_read] = 0;
base::StringPiece msg(buf, bytes_read);
if (msg.starts_with("ERROR")) {
if (base::StartsWith(msg, "ERROR")) {
LOG(ERROR) << msg;
has_failed_ = true;
return;

@ -22,6 +22,7 @@
#include "base/pickle.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_util.h"
#include "tools/android/forwarder2/common.h"
#include "tools/android/forwarder2/daemon.h"
#include "tools/android/forwarder2/host_controllers_manager.h"
@ -146,7 +147,7 @@ class ClientDelegate : public Daemon::ClientDelegate {
DCHECK(static_cast<size_t>(bytes_read) < sizeof(buf));
buf[bytes_read] = 0;
base::StringPiece msg(buf, bytes_read);
if (msg.starts_with("ERROR")) {
if (base::StartsWith(msg, "ERROR")) {
LOG(ERROR) << msg;
has_failed_ = true;
return;

@ -485,7 +485,7 @@ bool GURL::IsAboutUrl(base::StringPiece allowed_path) const {
if (has_host() || has_username() || has_password() || has_port())
return false;
if (!path_piece().starts_with(allowed_path))
if (!base::StartsWith(path_piece(), allowed_path))
return false;
if (path_piece().size() == allowed_path.size()) {