0

Remove erase-remove idiom usage

This idiom is very easy to get wrong, and should be avoided. It can be
replaced with std::erase[_if] or base::Erase[If].

A followup CL will add a presubmit to prevent backsliding.

Bug: 41408868
Change-Id: I6d7c9c793424e8e40503b2e5afaed77da94d1e77
Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/6427068
Commit-Queue: Chris Fredrickson <cfredric@chromium.org>
Reviewed-by: Rick Byers <rbyers@chromium.org>
Owners-Override: Rick Byers <rbyers@chromium.org>
Cr-Commit-Position: refs/heads/main@{#1442311}
This commit is contained in:
Chris Fredrickson
2025-04-03 11:28:02 -07:00
committed by Chromium LUCI CQ
parent e9f5408276
commit 4b552a72fe
32 changed files with 35 additions and 103 deletions
ash
base/ios
chrome
chromecast
chromeos/ash/components/system
components
autofill
core
component_updater
content/browser
headless/app
ios/chrome/browser
ipc
media/audio/mac
mojo/public/cpp/bindings/tests
services/device/geolocation
third_party/blink/renderer/platform/peerconnection
tools
binary_size
libsupersize
viewer
caspian
clang

@ -1293,10 +1293,7 @@ TEST_F(WindowTreeHostManagerTest, SetPrimaryWithThreeDisplays) {
int64_t primary_id = display::Screen::GetScreen()->GetPrimaryDisplay().id();
display::DisplayIdList non_primary_ids =
display_manager()->GetConnectedDisplayIdList();
auto itr =
std::remove(non_primary_ids.begin(), non_primary_ids.end(), primary_id);
ASSERT_TRUE(itr != non_primary_ids.end());
non_primary_ids.erase(itr, non_primary_ids.end());
ASSERT_GT(std::erase(non_primary_ids, primary_id), 0u);
ASSERT_EQ(2u, non_primary_ids.size());
// Build the following layout:
@ -1413,10 +1410,7 @@ TEST_F(WindowTreeHostManagerTest, SetPrimaryWithFourDisplays) {
int64_t primary_id = display::Screen::GetScreen()->GetPrimaryDisplay().id();
display::DisplayIdList non_primary_ids =
display_manager()->GetConnectedDisplayIdList();
auto itr =
std::remove(non_primary_ids.begin(), non_primary_ids.end(), primary_id);
ASSERT_TRUE(itr != non_primary_ids.end());
non_primary_ids.erase(itr, non_primary_ids.end());
ASSERT_GT(std::erase(non_primary_ids, primary_id), 0u);
ASSERT_EQ(3u, non_primary_ids.size());
// Build the following layout:

@ -359,9 +359,7 @@ void SessionStateAnimatorImpl::GetContainers(
GetContainersInRootWindow(container_mask, root_window, containers);
// Some of containers may be null in some tests.
containers->erase(
std::remove(containers->begin(), containers->end(), nullptr),
containers->end());
std::erase(*containers, nullptr);
}
void SessionStateAnimatorImpl::StartAnimation(int container_mask,

@ -197,8 +197,7 @@ id Iterator::GetNext() {
- (void)compact {
DCHECK(!_invocationDepth);
_observers.erase(std::remove(_observers.begin(), _observers.end(), nil),
_observers.end());
std::erase(_observers, nil);
}
@end

@ -212,9 +212,7 @@ void SpeechRecognitionServiceTest::OnSpeechRecognitionRecognitionEvent(
std::string transcription = result.transcription;
// The language pack used by the MacOS builder is newer and has punctuation
// enabled whereas the one used by the Linux builder does not.
transcription.erase(
std::remove(transcription.begin(), transcription.end(), ','),
transcription.end());
std::erase(transcription, ',');
recognition_results_.push_back(std::move(transcription));
std::move(reply).Run(is_client_requesting_speech_recognition_);
}

@ -140,10 +140,8 @@ void FallbackTaskProvider::ShowTask(Task* task) {
}
void FallbackTaskProvider::HideTask(Task* task) {
auto it = std::remove(shown_tasks_.begin(), shown_tasks_.end(), task);
pending_shown_tasks_.erase(task);
if (it != shown_tasks_.end()) {
shown_tasks_.erase(it, shown_tasks_.end());
if (std::erase(shown_tasks_, task) > 0) {
NotifyObserverTaskRemoved(task);
}
}

@ -162,12 +162,7 @@ void PerformanceInterventionButtonController::OnTabStripModelChanged(
std::optional<resource_attribution::PageContext> removed_page_context =
resource_attribution::PageContext::FromWebContents(tab.contents);
CHECK(removed_page_context.has_value());
const auto iter_position =
std::remove(actionable_cpu_tabs_.begin(), actionable_cpu_tabs_.end(),
removed_page_context);
if (iter_position != actionable_cpu_tabs_.end()) {
actionable_cpu_tabs_.erase(iter_position);
}
std::erase(actionable_cpu_tabs_, removed_page_context);
}
if (actionable_cpu_tabs_.empty()) {

@ -293,9 +293,7 @@ void RemoveModelEntries(
const std::vector<browsing_data_model_test_util::BrowsingDataEntry>&
entries_to_remove) {
for (const auto& entry : entries_to_remove) {
model_entries.erase(
std::remove(model_entries.begin(), model_entries.end(), entry),
model_entries.end());
std::erase(model_entries, entry);
}
}

@ -531,8 +531,7 @@ void TabSearchPageHandler::RemoveStaleTab(tabs::TabInterface* tab) {
inactive_tab_subscriptions_map_.end());
// Remove the TabInterface from stale_tabs_
stale_tabs_.erase(std::remove(stale_tabs_.begin(), stale_tabs_.end(), tab),
stale_tabs_.end());
std::erase(stale_tabs_, tab);
// Unregister the subscriptions for this TabInterface
inactive_tab_subscriptions_map_.erase(tab);

@ -68,7 +68,7 @@ void OnSodaResponse(const char* serialized_proto,
void SodaClientImplUnitTest::AddRecognitionResult(std::string result) {
// The language pack used by the MacOS builder is newer and has punctuation
// enabled whereas the one used by the Linux builder does not.
result.erase(std::remove(result.begin(), result.end(), ','), result.end());
std::erase(result, ',');
recognition_results_.push_back(std::move(result));
}

@ -282,9 +282,7 @@ class ObservableInternals
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(observer);
DCHECK(base::Contains(observers_, observer));
observers_.erase(
std::remove(observers_.begin(), observers_.end(), observer),
observers_.end());
std::erase(observers_, observer);
}
bool Empty() const {

@ -91,8 +91,7 @@ bool ParseUuid(const std::string& str, bluetooth_v2_shlib::Uuid* uuid) {
}
std::string no_dashes = str;
no_dashes.erase(std::remove(no_dashes.begin(), no_dashes.end(), '-'),
no_dashes.end());
std::erase(no_dashes, '-');
if (no_dashes.size() != kUuidHexNumChars) {
return false;

@ -74,9 +74,7 @@ void VolumeControlAndroid::AddVolumeObserver(VolumeObserver* observer) {
void VolumeControlAndroid::RemoveVolumeObserver(VolumeObserver* observer) {
base::AutoLock lock(observer_lock_);
volume_observers_.erase(
std::remove(volume_observers_.begin(), volume_observers_.end(), observer),
volume_observers_.end());
std::erase(volume_observers_, observer);
}
float VolumeControlAndroid::GetVolume(AudioContentType type) {

@ -54,9 +54,7 @@ class VolumeControlInternal {
void RemoveVolumeObserver(VolumeObserver* observer) {
base::AutoLock lock(observer_lock_);
volume_observers_.erase(std::remove(volume_observers_.begin(),
volume_observers_.end(), observer),
volume_observers_.end());
std::erase(volume_observers_, observer);
}
float GetVolume(AudioContentType type) {

@ -214,10 +214,7 @@ void MixerInput::RemoveAudioOutputRedirector(
<< ")";
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(redirector);
audio_output_redirectors_.erase(
std::remove(audio_output_redirectors_.begin(),
audio_output_redirectors_.end(), redirector),
audio_output_redirectors_.end());
std::erase(audio_output_redirectors_, redirector);
}
bool MixerInput::Render(

@ -113,9 +113,7 @@ class VolumeControlInternal : public SystemVolumeControl::Delegate {
void RemoveVolumeObserver(VolumeObserver* observer) {
base::AutoLock lock(observer_lock_);
volume_observers_.erase(std::remove(volume_observers_.begin(),
volume_observers_.end(), observer),
volume_observers_.end());
std::erase(volume_observers_, observer);
}
float GetVolume(AudioContentType type) {

@ -48,7 +48,7 @@ class NameValuePairsParserFuzzer {
// Test with the input as a value on the same line (i.e., without any
// newline in it).
std::string value = input;
value.erase(std::remove(value.begin(), value.end(), '\n'), value.end());
std::erase(value, '\n');
testInputAsVpdDumpValueForKey(value);
// TODO(crbug.com/40197992): Check that the value for "key" is |value|.
}

@ -46,7 +46,7 @@ AmountExtractionManager::MaybeParseAmountToMonetaryMicroUnits(
if (!RE2::FullMatch(amount, re, &dollar, nullptr, nullptr, &cent)) {
return std::nullopt;
}
dollar.erase(std::remove(dollar.begin(), dollar.end(), ','), dollar.end());
std::erase(dollar, ',');
uint64_t dollar_value = 0;
uint64_t cent_value = 0;

@ -47,9 +47,7 @@ std::string GetNormalizedLocale(const std::string& raw_locale) {
}
locale = raw_locale;
for (const auto c : "-_") {
locale.erase(std::remove(locale.begin(), locale.end(), c), locale.end());
}
std::erase_if(locale, [](const auto c) { return base::Contains("-_", c); });
std::ranges::transform(locale, locale.begin(),
[](char c) { return base::ToUpperASCII(c); });

@ -1203,10 +1203,7 @@ void GpuDataManagerImplPrivate::UpdateGpuFeatureInfo(
if (HardwareAccelerationEnabled() &&
gpu_feature_info_.status_values[gpu::GPU_FEATURE_TYPE_ACCELERATED_GL] !=
gpu::GpuFeatureStatus::kGpuFeatureStatusEnabled) {
fallback_modes_.erase(
std::remove(fallback_modes_.begin(), fallback_modes_.end(),
gpu::GpuMode::HARDWARE_GL),
fallback_modes_.end());
std::erase(fallback_modes_, gpu::GpuMode::HARDWARE_GL);
}
// If Vulkan or Graphite initialization fails, the GPU process can silently

@ -299,9 +299,7 @@ void InMemoryFederatedPermissionContext::RegisterIdP(const ::GURL& configURL) {
void InMemoryFederatedPermissionContext::UnregisterIdP(
const ::GURL& configURL) {
idp_registry_.erase(
std::remove(idp_registry_.begin(), idp_registry_.end(), configURL),
idp_registry_.end());
std::erase(idp_registry_, configURL);
}
std::vector<GURL> InMemoryFederatedPermissionContext::GetRegisteredIdPs() {

@ -128,9 +128,7 @@ void HeadlessShell::OnBrowserStart(HeadlessBrowser* browser) {
// Remove empty arguments sometimes left there by scripts to prevent weird
// error messages.
args.erase(
std::remove(args.begin(), args.end(), base::CommandLine::StringType()),
args.end());
std::erase(args, base::CommandLine::StringType());
// If no explicit URL is present assume about:blank unless we're being
// driven by a debugger.

@ -142,10 +142,7 @@ class DiscoverFeedProfileHelperList {
private:
// Compacts the list of helpers, removing all nil weak pointers.
void Compact() {
helpers_.erase(std::remove(helpers_.begin(), helpers_.end(), nil),
helpers_.end());
}
void Compact() { std::erase(helpers_, nil); }
std::vector<__weak id<DiscoverFeedProfileHelper>> helpers_;
};

@ -280,9 +280,7 @@ void URLDownloader::DownloadOfflineURL(const GURL& url) {
}
void URLDownloader::CancelDownloadOfflineURL(const GURL& url) {
tasks_.erase(
std::remove(tasks_.begin(), tasks_.end(), std::make_pair(DOWNLOAD, url)),
tasks_.end());
base::Erase(tasks_, std::make_pair(DOWNLOAD, url));
}
void URLDownloader::DownloadPDFOrHTMLCompletionHandler(

@ -37,8 +37,7 @@
- (void)removeItemWithID:(web::WebStateID)removedItemID
selectedItemID:(web::WebStateID)selectedItemID {
auto it = std::remove(_items.begin(), _items.end(), removedItemID);
_items.erase(it, _items.end());
std::erase(_items, removedItemID);
_selectedItemID = selectedItemID;
}
@ -52,8 +51,7 @@
}
- (void)moveItemWithID:(web::WebStateID)itemID toIndex:(NSUInteger)toIndex {
auto it = std::remove(_items.begin(), _items.end(), itemID);
_items.erase(it, _items.end());
std::erase(_items, itemID);
_items.insert(_items.begin() + toIndex, itemID);
}

@ -66,9 +66,7 @@
- (void)removeItemWithIdentifier:(GridItemIdentifier*)removedItem
selectedItemIdentifier:(GridItemIdentifier*)selectedItemIdentifier {
auto it = std::remove(_items.begin(), _items.end(),
removedItem.tabSwitcherItem.identifier);
_items.erase(it, _items.end());
std::erase(_items, removedItem.tabSwitcherItem.identifier);
_selectedItem = selectedItemIdentifier;
}
@ -88,8 +86,7 @@
- (void)moveItem:(GridItemIdentifier*)item
beforeItem:(GridItemIdentifier*)nextItemIdentifier {
web::WebStateID moved_id = item.tabSwitcherItem.identifier;
auto it = std::remove(_items.begin(), _items.end(), moved_id);
_items.erase(it, _items.end());
std::erase(_items, moved_id);
if (nextItemIdentifier) {
_items.insert(std::find(std::begin(_items), std::end(_items),
nextItemIdentifier.tabSwitcherItem.identifier),

@ -33,13 +33,7 @@ bool TryFiltersImpl(MessageFilterRouter::MessageFilters& filters,
bool RemoveFilterImpl(MessageFilterRouter::MessageFilters& filters,
MessageFilter* filter) {
MessageFilterRouter::MessageFilters::iterator it =
std::remove(filters.begin(), filters.end(), filter);
if (it == filters.end())
return false;
filters.erase(it, filters.end());
return true;
return std::erase(filters, filter) > 0;
}
bool ValidMessageClass(int message_class) {

@ -119,10 +119,7 @@ class SCKAudioInputStreamTest : public PlatformTest {
.andDo(^(NSInvocation* invocation) {
__unsafe_unretained id<SCStreamOutput> stream_output;
[invocation getArgument:&stream_output atIndex:2];
stream_outputs_.erase(
std::remove(stream_outputs_.begin(), stream_outputs_.end(),
stream_output),
stream_outputs_.end());
std::erase(stream_outputs_, stream_output);
})
.andReturn(TRUE);

@ -150,8 +150,7 @@ bool ReadResultFile(const std::string& path, std::string* result) {
return false;
// Result files are new-line delimited text files. Remove any CRs.
result->erase(std::remove(result->begin(), result->end(), '\r'),
result->end());
std::erase(*result, '\r');
// Remove trailing LFs.
size_t pos = result->find_last_not_of('\n');

@ -136,7 +136,7 @@ void PositionCacheImpl::OnNetworkChanged(
}
void PositionCacheImpl::EvictEntry(const Hash& hash) {
data_.erase(std::remove(data_.begin(), data_.end(), hash), data_.end());
std::erase(data_, hash);
}
} // namespace device

@ -3369,10 +3369,7 @@ TEST_F(RTCVideoEncoderEncodeTest, AV1TemporalLayerGenericFrameInfo) {
for (auto& profile : supported_profiles_) {
if (profile.profile == media::AV1PROFILE_PROFILE_MAIN) {
auto& scalability_modes = profile.scalability_modes;
scalability_modes.erase(
std::remove(scalability_modes.begin(), scalability_modes.end(),
media::SVCScalabilityMode::kL1T2),
scalability_modes.end());
std::erase(scalability_modes, media::SVCScalabilityMode::kL1T2);
}
}

@ -69,8 +69,7 @@ namespace {
// Copied from /base/stl_util.h
template <class T, class Allocator, class Value>
void Erase(std::vector<T, Allocator>& container, const Value& value) {
container.erase(std::remove(container.begin(), container.end(), value),
container.end());
std::erase(container, value);
}
std::string_view GetIdPath(const caspian::Symbol& sym) {

@ -1127,9 +1127,7 @@ std::string GenerateClassName(std::string var_name) {
}
prev = c;
}
// Now we need to remove the '_'s from the string, recall std::remove moves
// everything to the end and then returns the first '_' (or end()). We then
// call erase from there to the end to actually remove.
// Now we need to remove the '_'s from the string.
llvm::erase(var_name, '_');
return var_name;
}