diff --git a/.clang-tidy b/.clang-tidy index a9f97bc6c75c4..c29508271cc03 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -33,6 +33,7 @@ Checks: > performance-type-promotion-in-math-fn, performance-unnecessary-copy-initialization, readability-braces-around-statements, + readability-container-contains, readability-container-size-empty, readability-identifier-naming, readability-redundant-control-flow, diff --git a/contrib/client_ssl_auth/filters/network/source/client_ssl_auth.h b/contrib/client_ssl_auth/filters/network/source/client_ssl_auth.h index e452ed1587464..93d524c4aeafe 100644 --- a/contrib/client_ssl_auth/filters/network/source/client_ssl_auth.h +++ b/contrib/client_ssl_auth/filters/network/source/client_ssl_auth.h @@ -55,7 +55,7 @@ class AllowedPrincipals : public ThreadLocal::ThreadLocalObject { } } bool allowed(const std::string& sha256_digest) const { - return allowed_sha256_digests_.count(sha256_digest) != 0; + return allowed_sha256_digests_.contains(sha256_digest); } size_t size() const { return allowed_sha256_digests_.size(); } diff --git a/contrib/exe/contrib_version_test.cc b/contrib/exe/contrib_version_test.cc index 313024e7e45d8..987d26d02d603 100644 --- a/contrib/exe/contrib_version_test.cc +++ b/contrib/exe/contrib_version_test.cc @@ -12,7 +12,7 @@ TEST(ContribVersionTest, VersionContainsSuffix) { TEST(ContribVersionTest, BuildVersionContainsSuffix) { auto build_version = VersionInfo::buildVersion(); const auto& fields = build_version.metadata().fields(); - ASSERT_NE(fields.find(BuildVersionMetadataKeys::get().BuildLabel), fields.end()); + ASSERT_TRUE(fields.contains(BuildVersionMetadataKeys::get().BuildLabel)); EXPECT_THAT(fields.at(BuildVersionMetadataKeys::get().BuildLabel).string_value(), testing::EndsWith("contrib")); } diff --git a/contrib/kafka/filters/network/source/mesh/upstream_config.cc b/contrib/kafka/filters/network/source/mesh/upstream_config.cc index 1c541638991f5..89605d596cc4b 100644 --- a/contrib/kafka/filters/network/source/mesh/upstream_config.cc +++ b/contrib/kafka/filters/network/source/mesh/upstream_config.cc @@ -38,7 +38,7 @@ UpstreamKafkaConfigurationImpl::UpstreamKafkaConfigurationImpl(const KafkaMeshPr const std::string& cluster_name = upstream_cluster_definition.cluster_name(); // No duplicates are allowed. - if (cluster_name_to_cluster_config.find(cluster_name) != cluster_name_to_cluster_config.end()) { + if (cluster_name_to_cluster_config.contains(cluster_name)) { throw EnvoyException( absl::StrCat("kafka-mesh filter has multiple Kafka clusters referenced by the same name", cluster_name)); diff --git a/contrib/kafka/filters/network/test/broker/filter_unit_test.cc b/contrib/kafka/filters/network/test/broker/filter_unit_test.cc index 4d1205ce4d61a..0980dc1270fb4 100644 --- a/contrib/kafka/filters/network/test/broker/filter_unit_test.cc +++ b/contrib/kafka/filters/network/test/broker/filter_unit_test.cc @@ -279,7 +279,7 @@ TEST_F(KafkaMetricsFacadeImplUnitTest, ShouldRegisterResponse) { // then const auto& request_arrivals = testee_.getRequestArrivalsForTest(); - ASSERT_EQ(request_arrivals.find(correlation_id), request_arrivals.end()); + ASSERT_FALSE(request_arrivals.contains(correlation_id)); } TEST_F(KafkaMetricsFacadeImplUnitTest, ShouldRegisterUnknownResponse) { diff --git a/contrib/postgres_proxy/filters/network/source/postgres_decoder.cc b/contrib/postgres_proxy/filters/network/source/postgres_decoder.cc index 6aeee0a5ca65f..dc0c882a68aab 100644 --- a/contrib/postgres_proxy/filters/network/source/postgres_decoder.cc +++ b/contrib/postgres_proxy/filters/network/source/postgres_decoder.cc @@ -553,8 +553,7 @@ void DecoderImpl::onStartup() { attributes_ = absl::StrSplit(message_.substr(4), absl::ByChar('\0'), absl::SkipEmpty()); // If "database" attribute is not found, default it to "user" attribute. - if ((attributes_.find("database") == attributes_.end()) && - (attributes_.find("user") != attributes_.end())) { + if (!attributes_.contains("database") && attributes_.contains("user")) { attributes_["database"] = attributes_["user"]; } } diff --git a/contrib/rocketmq_proxy/filters/network/source/active_message.cc b/contrib/rocketmq_proxy/filters/network/source/active_message.cc index 119c102ca77d8..34308a74a09b1 100644 --- a/contrib/rocketmq_proxy/filters/network/source/active_message.cc +++ b/contrib/rocketmq_proxy/filters/network/source/active_message.cc @@ -122,7 +122,7 @@ void ActiveMessage::fillBrokerData(std::vector& list, const std::str for (auto& entry : list) { if (entry.cluster() == cluster && entry.brokerName() == broker_name) { found = true; - if (entry.brokerAddresses().find(broker_id) != entry.brokerAddresses().end()) { + if (entry.brokerAddresses().contains(broker_id)) { ENVOY_LOG(warn, "Duplicate broker_id found. Broker ID: {}, address: {}", broker_id, address); continue; diff --git a/contrib/sip_proxy/filters/network/source/conn_manager.cc b/contrib/sip_proxy/filters/network/source/conn_manager.cc index 14f77accbb05a..a75efb0abe6a9 100644 --- a/contrib/sip_proxy/filters/network/source/conn_manager.cc +++ b/contrib/sip_proxy/filters/network/source/conn_manager.cc @@ -307,7 +307,7 @@ void ConnectionManager::sendLocalReply(MessageMetadata& metadata, const DirectRe } void ConnectionManager::setLocalResponseSent(absl::string_view transaction_id) { - if (transactions_.find(transaction_id) != transactions_.end()) { + if (transactions_.contains(transaction_id)) { transactions_[transaction_id]->setLocalResponseSent(true); } } @@ -357,7 +357,7 @@ DecoderEventHandler& ConnectionManager::newDecoderEventHandler(MessageMetadataSh std::string&& k = std::string(metadata->transactionId().value()); // if (metadata->methodType() == MethodType::Ack) { - if (transactions_.find(k) != transactions_.end()) { + if (transactions_.contains(k)) { // ACK_4XX metadata will updated later. return *transactions_.at(k); } diff --git a/contrib/sip_proxy/filters/network/source/utility.h b/contrib/sip_proxy/filters/network/source/utility.h index 5eda59eed424c..32c7edee91b88 100644 --- a/contrib/sip_proxy/filters/network/source/utility.h +++ b/contrib/sip_proxy/filters/network/source/utility.h @@ -200,7 +200,7 @@ template class Cache { } } - bool contains(const K& key) { return cache_.find(key) != cache_.end(); } + bool contains(const K& key) { return cache_.contains(key); } OptRef at(const K& key) { auto it = cache_.find(key); diff --git a/contrib/sxg/filters/http/source/encoder.cc b/contrib/sxg/filters/http/source/encoder.cc index 924ea3dfebc39..33c9a46d80916 100644 --- a/contrib/sxg/filters/http/source/encoder.cc +++ b/contrib/sxg/filters/http/source/encoder.cc @@ -51,7 +51,7 @@ bool EncoderImpl::loadHeaders(Http::ResponseHeaderMap* headers) { } } // filter out headers that are not allowed to be encoded in the SXG document - if (filtered_headers.find(header_key) != filtered_headers.end()) { + if (filtered_headers.contains(header_key)) { return Http::HeaderMap::Iterate::Continue; } diff --git a/contrib/vcl/source/vcl_interface.cc b/contrib/vcl/source/vcl_interface.cc index 5c71271667532..abd97074d8b03 100644 --- a/contrib/vcl/source/vcl_interface.cc +++ b/contrib/vcl/source/vcl_interface.cc @@ -111,7 +111,7 @@ void vclInterfaceRegisterEpollEvent(Envoy::Event::Dispatcher& dispatcher) { MqFileEventsMap& mq_fevts_map = mqFileEventsMap(); const int wrk_index = vppcom_worker_index(); RELEASE_ASSERT(wrk_index != -1, ""); - if (mq_fevts_map.find(wrk_index) != mq_fevts_map.end()) { + if (mq_fevts_map.contains(wrk_index)) { return; } mq_fevts_map[wrk_index] = dispatcher.createFileEvent( diff --git a/source/common/access_log/access_log_impl.cc b/source/common/access_log/access_log_impl.cc index f4eb261998506..8eccb633bb992 100644 --- a/source/common/access_log/access_log_impl.cc +++ b/source/common/access_log/access_log_impl.cc @@ -274,7 +274,7 @@ bool GrpcStatusFilter::evaluate(const Formatter::Context& context, status = optional_status.value(); } - const bool found = statuses_.find(status) != statuses_.end(); + const bool found = statuses_.contains(status); return exclude_ ? !found : found; } diff --git a/source/common/filesystem/win32/watcher_impl.cc b/source/common/filesystem/win32/watcher_impl.cc index 2e7c0e72432e3..0b1b08868341f 100644 --- a/source/common/filesystem/win32/watcher_impl.cc +++ b/source/common/filesystem/win32/watcher_impl.cc @@ -75,7 +75,7 @@ absl::Status WatcherImpl::addWatch(absl::string_view path, uint32_t events, OnCh RELEASE_ASSERT( GetFileInformationByHandleEx(dir_handle, FileIdInfo, &fii_key[0], sizeof(FILE_ID_INFO)), fmt::format("unable to identify directory {}: {}", result.directory_, GetLastError())); - if (callback_map_.find(fii_key) != callback_map_.end()) { + if (callback_map_.contains(fii_key)) { CloseHandle(dir_handle); } else { callback_map_[fii_key] = std::make_unique(); diff --git a/source/common/grpc/async_client_manager_impl.cc b/source/common/grpc/async_client_manager_impl.cc index b6ba792b758a6..93ad50f461fdd 100644 --- a/source/common/grpc/async_client_manager_impl.cc +++ b/source/common/grpc/async_client_manager_impl.cc @@ -200,7 +200,7 @@ AsyncClientManagerImpl::RawAsyncClientCache::RawAsyncClientCache( void AsyncClientManagerImpl::RawAsyncClientCache::setCache( const GrpcServiceConfigWithHashKey& config_with_hash_key, const RawAsyncClientSharedPtr& client) { - ASSERT(lru_map_.find(config_with_hash_key) == lru_map_.end()); + ASSERT(!lru_map_.contains(config_with_hash_key)); // Create a new cache entry at the beginning of the list. lru_list_.emplace_front(config_with_hash_key, client, dispatcher_.timeSource().monotonicTime()); lru_map_[config_with_hash_key] = lru_list_.begin(); diff --git a/source/common/grpc/buffered_async_client.h b/source/common/grpc/buffered_async_client.h index 85d46a9384eeb..ef2717b86a862 100644 --- a/source/common/grpc/buffered_async_client.h +++ b/source/common/grpc/buffered_async_client.h @@ -101,7 +101,7 @@ template class BufferedAsyncClient { void erasePendingMessage(uint64_t message_id) { // This case will be considered if `onSuccess` had called with unknown message id that is not // received by envoy as response. - if (message_buffer_.find(message_id) == message_buffer_.end()) { + if (!message_buffer_.contains(message_id)) { return; } auto& buffer = message_buffer_.at(message_id); diff --git a/source/common/grpc/google_async_client_impl.h b/source/common/grpc/google_async_client_impl.h index 4db8cc9f5104e..8d48cef1eb816 100644 --- a/source/common/grpc/google_async_client_impl.h +++ b/source/common/grpc/google_async_client_impl.h @@ -77,7 +77,7 @@ class GoogleAsyncClientThreadLocal : public ThreadLocal::ThreadLocalObject, grpc::CompletionQueue& completionQueue() { return cq_; } void registerStream(GoogleAsyncStreamImpl* stream) { - ASSERT(streams_.find(stream) == streams_.end()); + ASSERT(!streams_.contains(stream)); streams_.insert(stream); } diff --git a/source/common/http/async_client_utility.cc b/source/common/http/async_client_utility.cc index 95630bc474bbe..9c2a70455ac3e 100644 --- a/source/common/http/async_client_utility.cc +++ b/source/common/http/async_client_utility.cc @@ -12,7 +12,7 @@ AsyncClientRequestTracker::~AsyncClientRequestTracker() { } void AsyncClientRequestTracker::add(AsyncClient::Request& request) { - ASSERT(active_requests_.find(&request) == active_requests_.end(), "request is already tracked."); + ASSERT(!active_requests_.contains(&request), "request is already tracked."); active_requests_.insert(&request); } diff --git a/source/common/http/session_idle_list.cc b/source/common/http/session_idle_list.cc index 0a368f4f6d33f..934939ca4a651 100644 --- a/source/common/http/session_idle_list.cc +++ b/source/common/http/session_idle_list.cc @@ -55,7 +55,7 @@ absl::Duration SessionIdleList::MinTimeBeforeTerminationAllowed() const { void SessionIdleList::IdleSessions::AddSessionToList(MonotonicTime enqueue_time, IdleSessionInterface& session) { - if (map_.find(&session) != map_.end()) { + if (map_.contains(&session)) { IS_ENVOY_BUG("Session is already on the idle list."); return; } diff --git a/source/common/http/utility.cc b/source/common/http/utility.cc index a4702282c4614..cd8f1b200d76d 100644 --- a/source/common/http/utility.cc +++ b/source/common/http/utility.cc @@ -1249,7 +1249,7 @@ std::string Utility::PercentEncoding::encode(absl::string_view value, // We do checking for each char in the string. If the current char is included in the defined // escaping characters, we jump to "the slow path" (append the char [encoded or not encoded] // to the returned string one by one) started from the current index. - if (ch < ' ' || ch >= '~' || reserved_char_set.find(ch) != reserved_char_set.end()) { + if (ch < ' ' || ch >= '~' || reserved_char_set.contains(ch)) { return PercentEncoding::encode(value, i, reserved_char_set); } } @@ -1265,7 +1265,7 @@ std::string Utility::PercentEncoding::encode(absl::string_view value, const size for (size_t i = index; i < value.size(); ++i) { const char& ch = value[i]; - if (ch < ' ' || ch >= '~' || reserved_char_set.find(ch) != reserved_char_set.end()) { + if (ch < ' ' || ch >= '~' || reserved_char_set.contains(ch)) { // For consistency, URI producers should use uppercase hexadecimal digits for all // percent-encodings. https://tools.ietf.org/html/rfc3986#section-2.1. absl::StrAppend(&encoded, fmt::format("%{:02X}", static_cast(ch))); diff --git a/source/common/init/manager_impl.cc b/source/common/init/manager_impl.cc index 1417c1d65d0ea..5b43f240d7175 100644 --- a/source/common/init/manager_impl.cc +++ b/source/common/init/manager_impl.cc @@ -83,7 +83,7 @@ void ManagerImpl::onTargetReady(absl::string_view target_name) { fmt::format("{} called back by target after initialization complete", target_name)); // Decrease target_name count by 1. - ASSERT(target_names_count_.find(target_name) != target_names_count_.end()); + ASSERT(target_names_count_.contains(target_name)); if (--target_names_count_[target_name] == 0) { target_names_count_.erase(target_name); } diff --git a/source/common/json/json_rpc_field_extractor.cc b/source/common/json/json_rpc_field_extractor.cc index 8b97a7b43bd79..4380c1cc95a80 100644 --- a/source/common/json/json_rpc_field_extractor.cc +++ b/source/common/json/json_rpc_field_extractor.cc @@ -341,14 +341,14 @@ void JsonRpcFieldExtractor::checkEarlyStop() { if (is_notification_ && field == "id") { continue; } - if (collected_fields_.count(field) == 0) { + if (!collected_fields_.contains(field)) { return; } } const auto& required_fields = config_.getFieldsForMethod(method_); for (const auto& field : required_fields) { - if (collected_fields_.count(field.path) == 0) { + if (!collected_fields_.contains(field.path)) { return; } } @@ -451,7 +451,7 @@ void JsonRpcFieldExtractor::copyFieldByPath(const std::string& path) { void JsonRpcFieldExtractor::validateRequiredFields() { const auto& fields = config_.getFieldsForMethod(method_); for (const auto& field : fields) { - if (extracted_fields_.count(field.path) == 0) { + if (!extracted_fields_.contains(field.path)) { missing_required_fields_.push_back(field.path); ENVOY_LOG(debug, "missing required field for {}: {}", method_, field.path); } diff --git a/source/common/jwt/jwt.cc b/source/common/jwt/jwt.cc index e8693536b87d4..0ea3c11e0fdbb 100644 --- a/source/common/jwt/jwt.cc +++ b/source/common/jwt/jwt.cc @@ -25,7 +25,7 @@ bool isImplemented(absl::string_view alg) { {"RS384"}, {"RS512"}, {"PS256"}, {"PS384"}, {"PS512"}, {"EdDSA"}, }; - return implemented_algs.find(alg) != implemented_algs.end(); + return implemented_algs.contains(alg); } } // namespace diff --git a/source/common/listener_manager/filter_chain_manager_impl.cc b/source/common/listener_manager/filter_chain_manager_impl.cc index 27856825bc2da..3e248bbdbfb1d 100644 --- a/source/common/listener_manager/filter_chain_manager_impl.cc +++ b/source/common/listener_manager/filter_chain_manager_impl.cc @@ -205,7 +205,7 @@ absl::Status FilterChainManagerImpl::addFilterChains( const auto* origin = getOriginFilterChainManager(); if (origin != nullptr) { for (const auto& message_and_filter_chain : origin->fc_contexts_) { - if (fc_contexts_.find(message_and_filter_chain.first) == fc_contexts_.end()) { + if (!fc_contexts_.contains(message_and_filter_chain.first)) { origin->draining_filter_chains_.push_back(message_and_filter_chain.second); } } @@ -415,7 +415,7 @@ absl::Status FilterChainManagerImpl::addFilterChainForDestinationPorts( const std::vector& source_ips, const absl::Span source_ports, const Network::FilterChainSharedPtr& filter_chain) { - if (destination_ports_map.find(destination_port) == destination_ports_map.end()) { + if (!destination_ports_map.contains(destination_port)) { destination_ports_map[destination_port] = std::make_pair(DestinationIPsMap{}, nullptr); } diff --git a/source/common/listener_manager/listener_manager_impl.cc b/source/common/listener_manager/listener_manager_impl.cc index c6a9b90778e2a..4d14f82055b3d 100644 --- a/source/common/listener_manager/listener_manager_impl.cc +++ b/source/common/listener_manager/listener_manager_impl.cc @@ -1208,7 +1208,7 @@ void ListenerManagerImpl::stopListeners(StopListenersType stop_listeners_type, // This prevents us from double incrementing if listeners are stopped twice. // This can happen if the admin endpoint is triggered for inbound_only and then // all. We perform the check in the callback to ensure it's done on the main thread - if (stopped_listener_tags_.find(listener_tag) == stopped_listener_tags_.end()) { + if (!stopped_listener_tags_.contains(listener_tag)) { stats_.listener_stopped_.inc(); stopped_listener_tags_.insert(listener_tag); for (auto& listener : active_listeners_) { diff --git a/source/common/quic/envoy_quic_dispatcher.cc b/source/common/quic/envoy_quic_dispatcher.cc index 196c96e58dbe8..e7cc60fa64715 100644 --- a/source/common/quic/envoy_quic_dispatcher.cc +++ b/source/common/quic/envoy_quic_dispatcher.cc @@ -197,7 +197,7 @@ void EnvoyQuicDispatcher::closeConnectionsWithFilterChain( // from the map as well. connection.close(Network::ConnectionCloseType::NoFlush); } - ASSERT(connections_by_filter_chain_.find(filter_chain) == connections_by_filter_chain_.end()); + ASSERT(!connections_by_filter_chain_.contains(filter_chain)); if (num_connections > 0) { // Explicitly destroy closed sessions in the current call stack. Because upon // returning the filter chain configs will be destroyed, and no longer safe to be accessed. diff --git a/source/common/runtime/runtime_impl.cc b/source/common/runtime/runtime_impl.cc index 8b052878b9c17..917b69f476972 100644 --- a/source/common/runtime/runtime_impl.cc +++ b/source/common/runtime/runtime_impl.cc @@ -469,8 +469,8 @@ absl::Status ProtoLayer::walkProtoValue(const Protobuf::Value& v, const std::str break; case Protobuf::Value::kStructValue: { const Protobuf::Struct& s = v.struct_value(); - if (s.fields().empty() || s.fields().find("numerator") != s.fields().end() || - s.fields().find("denominator") != s.fields().end()) { + if (s.fields().empty() || s.fields().contains("numerator") || + s.fields().contains("denominator")) { SnapshotImpl::addEntry(values_, prefix, v, ""); break; } diff --git a/source/common/stats/allocator.cc b/source/common/stats/allocator.cc index 186800a85ac74..f5b9c6a53a5e0 100644 --- a/source/common/stats/allocator.cc +++ b/source/common/stats/allocator.cc @@ -297,8 +297,8 @@ class TextReadoutImpl : public StatsSharedImpl { CounterSharedPtr Allocator::makeCounter(StatName name, StatName tag_extracted_name, StatNameTagSpan stat_name_tags) { Thread::LockGuard lock(mutex_); - ASSERT(gauges_.find(name) == gauges_.end()); - ASSERT(text_readouts_.find(name) == text_readouts_.end()); + ASSERT(!gauges_.contains(name)); + ASSERT(!text_readouts_.contains(name)); auto iter = counters_.find(name); if (iter != counters_.end()) { return {*iter}; @@ -316,8 +316,8 @@ CounterSharedPtr Allocator::makeCounter(StatName name, StatName tag_extracted_na GaugeSharedPtr Allocator::makeGauge(StatName name, StatName tag_extracted_name, StatNameTagSpan stat_name_tags, Gauge::ImportMode import_mode) { Thread::LockGuard lock(mutex_); - ASSERT(counters_.find(name) == counters_.end()); - ASSERT(text_readouts_.find(name) == text_readouts_.end()); + ASSERT(!counters_.contains(name)); + ASSERT(!text_readouts_.contains(name)); auto iter = gauges_.find(name); if (iter != gauges_.end()) { return {*iter}; @@ -336,8 +336,8 @@ GaugeSharedPtr Allocator::makeGauge(StatName name, StatName tag_extracted_name, TextReadoutSharedPtr Allocator::makeTextReadout(StatName name, StatName tag_extracted_name, StatNameTagSpan stat_name_tags) { Thread::LockGuard lock(mutex_); - ASSERT(counters_.find(name) == counters_.end()); - ASSERT(gauges_.find(name) == gauges_.end()); + ASSERT(!counters_.contains(name)); + ASSERT(!gauges_.contains(name)); auto iter = text_readouts_.find(name); if (iter != text_readouts_.end()) { return {*iter}; diff --git a/source/common/stats/custom_stat_namespaces_impl.cc b/source/common/stats/custom_stat_namespaces_impl.cc index ec2ef5be4a569..a115f85cac4fe 100644 --- a/source/common/stats/custom_stat_namespaces_impl.cc +++ b/source/common/stats/custom_stat_namespaces_impl.cc @@ -8,7 +8,7 @@ namespace Stats { bool CustomStatNamespacesImpl::registered(const absl::string_view name) const { ASSERT_IS_MAIN_OR_TEST_THREAD(); - return namespaces_.find(name) != namespaces_.end(); + return namespaces_.contains(name); } void CustomStatNamespacesImpl::registerStatNamespace(const absl::string_view name) { diff --git a/source/common/tcp_proxy/tcp_proxy.cc b/source/common/tcp_proxy/tcp_proxy.cc index 36101861b5489..b119e2ef6cd58 100644 --- a/source/common/tcp_proxy/tcp_proxy.cc +++ b/source/common/tcp_proxy/tcp_proxy.cc @@ -1554,7 +1554,7 @@ UpstreamDrainManager::~UpstreamDrainManager() { // cancelDrain() should cause that drainer to be removed from drainers_. // ASSERT so that we don't end up in an infinite loop. - ASSERT(drainers_.find(key) == drainers_.end()); + ASSERT(!drainers_.contains(key)); } // This destructor is run when shutting down `ThreadLocal`. The destructor of some objects use diff --git a/source/common/upstream/cluster_manager_impl.cc b/source/common/upstream/cluster_manager_impl.cc index a81b572775cd8..3fdc9fefcc935 100644 --- a/source/common/upstream/cluster_manager_impl.cc +++ b/source/common/upstream/cluster_manager_impl.cc @@ -1939,7 +1939,7 @@ void ClusterManagerImpl::ThreadLocalClusterManagerImpl::removeHosts( parent_.deferred_cluster_creation_, fmt::format("Cannot find ThreadLocalCluster {}, but deferred cluster creation is disabled.", name)); - ASSERT(thread_local_deferred_clusters_.find(name) != thread_local_deferred_clusters_.end(), + ASSERT(thread_local_deferred_clusters_.contains(name), "Cluster with removed host is neither deferred or inflated!"); return; } @@ -1957,7 +1957,7 @@ void ClusterManagerImpl::ThreadLocalClusterManagerImpl::updateClusterMembership( LocalityWeightsConstSharedPtr locality_weights, const HostVector& hosts_added, const HostVector& hosts_removed, bool weighted_priority_health, uint64_t overprovisioning_factor, HostMapConstSharedPtr cross_priority_host_map) { - ASSERT(thread_local_clusters_.find(name) != thread_local_clusters_.end()); + ASSERT(thread_local_clusters_.contains(name)); const auto& cluster_entry = thread_local_clusters_[name]; cluster_entry->updateHosts(name, priority, std::move(update_hosts_params), std::move(locality_weights), hosts_added, hosts_removed, diff --git a/source/common/upstream/outlier_detection_impl.cc b/source/common/upstream/outlier_detection_impl.cc index d610d2163e87c..738c699d252c7 100644 --- a/source/common/upstream/outlier_detection_impl.cc +++ b/source/common/upstream/outlier_detection_impl.cc @@ -375,7 +375,7 @@ void DetectorImpl::initialize(Cluster& cluster) { } void DetectorImpl::addHostMonitor(HostSharedPtr host) { - ASSERT(host_monitors_.count(host) == 0); + ASSERT(!host_monitors_.contains(host)); DetectorHostMonitorImpl* monitor = new DetectorHostMonitorImpl(shared_from_this(), host); host_monitors_[host] = monitor; host->setOutlierDetector(DetectorHostMonitorPtr{monitor}); @@ -663,7 +663,7 @@ void DetectorImpl::setHostDegradedMainThread(HostSharedPtr host) { // posting this degrade event and the main thread running it; if so, ignore it // (mirrors the guard in the eject path) so host_monitors_[host] does not // default-insert a null monitor that is then dereferenced. - if (host_monitors_.count(host) == 0) { + if (!host_monitors_.contains(host)) { return; } if (!host->healthFlagGet(Host::HealthFlag::DEGRADED_OUTLIER_DETECTION)) { @@ -704,7 +704,7 @@ void DetectorImpl::onConsecutiveErrorWorker(HostSharedPtr host, envoy::data::cluster::v3::OutlierEjectionType type) { // Ejections come in cross thread. There is a chance that the host has already been removed from // the set. If so, just ignore it. - if (host_monitors_.count(host) == 0) { + if (!host_monitors_.contains(host)) { return; } if (host->healthFlagGet(Host::HealthFlag::FAILED_OUTLIER_CHECK)) { diff --git a/source/common/upstream/upstream_impl.cc b/source/common/upstream/upstream_impl.cc index def04672f4ee7..a79d6e348fab7 100644 --- a/source/common/upstream/upstream_impl.cc +++ b/source/common/upstream/upstream_impl.cc @@ -192,7 +192,7 @@ HostVector filterHosts(const absl::node_hash_set& hosts, net_hosts.reserve(hosts.size()); for (const auto& host : hosts) { - if (excluded_hosts.find(host) == excluded_hosts.end()) { + if (!excluded_hosts.contains(host)) { net_hosts.emplace_back(host); } } @@ -988,7 +988,7 @@ void PrioritySetImpl::BatchUpdateScope::updateHosts( std::optional overprovisioning_factor, HostMapConstSharedPtr cross_priority_host_map) { // We assume that each call updates a different priority. - ASSERT(priorities_.find(priority) == priorities_.end()); + ASSERT(!priorities_.contains(priority)); priorities_.insert(priority); for (const auto& host : hosts_added) { @@ -2385,8 +2385,7 @@ void PriorityStateManager::updateClusterPrioritySet( // Do we have hosts for the local locality? const bool non_empty_local_locality = - local_info_node_.has_locality() && - hosts_per_locality.find(local_locality) != hosts_per_locality.end(); + local_info_node_.has_locality() && hosts_per_locality.contains(local_locality); // As per HostsPerLocality::get(), the per_locality vector must have the local locality hosts // first if non_empty_local_locality. diff --git a/source/server/drain_manager_impl.cc b/source/server/drain_manager_impl.cc index 30c986b438601..3116a7fc35bbf 100644 --- a/source/server/drain_manager_impl.cc +++ b/source/server/drain_manager_impl.cc @@ -157,7 +157,7 @@ void DrainManagerImpl::startDrainSequence(Network::DrainDirection direction, addDrainCompleteCallback(direction, drain_complete_cb); return; } - ASSERT(drain_tick_timers_.count(direction) == 0, + ASSERT(!drain_tick_timers_.contains(direction), "cannot run two drain sequences for the same direction."); const std::chrono::seconds drain_delay(server_.options().drainTime()); diff --git a/source/server/overload_manager_impl.cc b/source/server/overload_manager_impl.cc index 3fbf1dd2443b1..e48137de2195f 100644 --- a/source/server/overload_manager_impl.cc +++ b/source/server/overload_manager_impl.cc @@ -533,7 +533,7 @@ OverloadManagerImpl::OverloadManagerImpl(Event::Dispatcher& dispatcher, Stats::S auto proactive_resource_it = OverloadProactiveResources::get().proactive_action_name_to_resource_.find(resource); - if (resources_.find(resource) == resources_.end() && + if (!resources_.contains(resource) && proactive_resource_it == OverloadProactiveResources::get().proactive_action_name_to_resource_.end()) { creation_status = absl::InvalidArgumentError( @@ -631,7 +631,7 @@ bool OverloadManagerImpl::registerForAction(const std::string& action, ASSERT(!started_); const auto symbol = action_symbol_table_.get(action); - if (actions_.find(symbol) == actions_.end()) { + if (!actions_.contains(symbol)) { ENVOY_LOG(debug, "No overload action is configured for {}.", action); return false; } diff --git a/test/common/common/version_test.cc b/test/common/common/version_test.cc index d40bd3810fe9f..e7725a42a09b9 100644 --- a/test/common/common/version_test.cc +++ b/test/common/common/version_test.cc @@ -66,7 +66,7 @@ TEST(VersionTest, MakeBuildVersionWithoutLabel) { EXPECT_EQ(2, build_version.version().minor_number()); EXPECT_EQ(3, build_version.version().patch()); const auto& fields = build_version.metadata().fields(); - EXPECT_EQ(fields.find(BuildVersionMetadataKeys::get().BuildLabel), fields.end()); + EXPECT_FALSE(fields.contains(BuildVersionMetadataKeys::get().BuildLabel)); // Other metadata should still be present EXPECT_GE(fields.size(), 1); } @@ -77,7 +77,7 @@ TEST(VersionTest, MakeBadBuildVersion) { EXPECT_EQ(0, build_version.version().minor_number()); EXPECT_EQ(0, build_version.version().patch()); const auto& fields = build_version.metadata().fields(); - EXPECT_EQ(fields.find(BuildVersionMetadataKeys::get().BuildLabel), fields.end()); + EXPECT_FALSE(fields.contains(BuildVersionMetadataKeys::get().BuildLabel)); // Other metadata should still be present EXPECT_GE(fields.size(), 1); } diff --git a/test/common/config/grpc_subscription_test_harness.h b/test/common/config/grpc_subscription_test_harness.h index 3608803429118..33abcfd4e52e5 100644 --- a/test/common/config/grpc_subscription_test_harness.h +++ b/test/common/config/grpc_subscription_test_harness.h @@ -203,7 +203,7 @@ class GrpcSubscriptionTestHarness : public SubscriptionTestHarness { // is no longer internally used by GrpcSubscriptionImpl. std::set both; for (const auto& n : cluster_names) { - if (last_cluster_names_.find(n) != last_cluster_names_.end()) { + if (last_cluster_names_.contains(n)) { both.insert(n); } } diff --git a/test/common/config/metadata_test.cc b/test/common/config/metadata_test.cc index 4e193b8a9ac86..5f112a7de9b92 100644 --- a/test/common/config/metadata_test.cc +++ b/test/common/config/metadata_test.cc @@ -143,7 +143,7 @@ class TypedMetadataTest : public testing::Test { public: // Throws EnvoyException (conversion failure) if d is empty. std::unique_ptr parse(const Protobuf::Struct& d) const override { - if (d.fields().find("name") != d.fields().end()) { + if (d.fields().contains("name")) { return std::make_unique(d.fields().at("name").string_value()); } throw EnvoyException("Cannot create a Foo when Struct metadata is empty."); diff --git a/test/common/config/registry_test.cc b/test/common/config/registry_test.cc index 6b86f4f08f620..eade39b6e3231 100644 --- a/test/common/config/registry_test.cc +++ b/test/common/config/registry_test.cc @@ -65,7 +65,7 @@ TEST(RegistryTest, DefaultFactoryPublished) { const auto& factories = Envoy::Registry::FactoryCategoryRegistry::registeredFactories(); // Expect that the category is present. - ASSERT_NE(factories.find("testing.published"), factories.end()); + ASSERT_TRUE(factories.contains("testing.published")); // Expect that the factory is listed in the right category. const auto& names = factories.find("testing.published")->second->registeredNames(); @@ -94,7 +94,7 @@ TEST(RegistryTest, VersionedFactory) { const auto& factories = Envoy::Registry::FactoryCategoryRegistry::registeredFactories(); // Expect that the category is present. - ASSERT_NE(factories.find("testing.published"), factories.end()); + ASSERT_TRUE(factories.contains("testing.published")); // Expect that the factory is listed in the right category. const auto& names = factories.find("testing.published")->second->registeredNames(); diff --git a/test/common/http/filter_chain_helper_test.cc b/test/common/http/filter_chain_helper_test.cc index d76d9b4d3fc50..b08c85f9015a2 100644 --- a/test/common/http/filter_chain_helper_test.cc +++ b/test/common/http/filter_chain_helper_test.cc @@ -47,8 +47,8 @@ TEST(FilterChainUtilityTest, CreateFilterChainForFactoriesWithRouteDisabled) { // 'filter_1' and 'filter_2' should be added. FilterChainUtility::createFilterChainForFactories(callbacks, filter_factories); - EXPECT_TRUE(added_filters.find("filter_1") != added_filters.end()); - EXPECT_TRUE(added_filters.find("filter_2") != added_filters.end()); + EXPECT_TRUE(added_filters.contains("filter_1")); + EXPECT_TRUE(added_filters.contains("filter_2")); EXPECT_EQ(added_filters.size(), 2); } } @@ -84,7 +84,7 @@ TEST(FilterChainUtilityTest, CreateFilterChainForFactoriesWithRouteDisabledAndDe // Only filter_1 should be added. FilterChainUtility::createFilterChainForFactories(callbacks, filter_factories); - EXPECT_TRUE(added_filters.find("filter_1") != added_filters.end()); + EXPECT_TRUE(added_filters.contains("filter_1")); EXPECT_EQ(added_filters.size(), 1); } } diff --git a/test/common/network/socket_option_test.h b/test/common/network/socket_option_test.h index 9afd8dd2236e8..a869d9526f50c 100644 --- a/test/common/network/socket_option_test.h +++ b/test/common/network/socket_option_test.h @@ -99,7 +99,7 @@ class SocketOptionTest : public testing::Test { }; unset_socketstates.remove_if( [&](envoy::config::core::v3::SocketOption::SocketState state) -> bool { - return when.find(state) != when.end(); + return when.contains(state); }); for (auto state : unset_socketstates) { EXPECT_CALL(os_sys_calls_, setsockopt_(_, _, _, _, _)).Times(0); diff --git a/test/common/protobuf/utility_test.cc b/test/common/protobuf/utility_test.cc index 6a0f2c594dce2..c3b2cc5d329fe 100644 --- a/test/common/protobuf/utility_test.cc +++ b/test/common/protobuf/utility_test.cc @@ -1414,8 +1414,8 @@ TEST_F(ProtobufUtilityTest, HashedValueStdHash) { set.emplace(hv3); EXPECT_EQ(set.size(), 2); // hv1 == hv2 - EXPECT_NE(set.find(hv1), set.end()); - EXPECT_NE(set.find(hv3), set.end()); + EXPECT_TRUE(set.contains(hv1)); + EXPECT_TRUE(set.contains(hv3)); } TEST_F(ProtobufUtilityTest, AnyBytes) { diff --git a/test/common/quic/envoy_quic_h3_fuzz_helper.cc b/test/common/quic/envoy_quic_h3_fuzz_helper.cc index bb53108da6e8e..7b63f25d6cafd 100644 --- a/test/common/quic/envoy_quic_h3_fuzz_helper.cc +++ b/test/common/quic/envoy_quic_h3_fuzz_helper.cc @@ -83,7 +83,7 @@ std::string H3Serializer::serialize(bool unidirectional, uint32_t type, uint32_t char buffer[kMaxPacketSize]; quiche::QuicheDataWriter dw(kMaxPacketSize, buffer); if (unidirectional) { - if (open_unidirectional_streams_.find(id) == open_unidirectional_streams_.end()) { + if (!open_unidirectional_streams_.contains(id)) { dw.WriteVarInt62(static_cast(type)); open_unidirectional_streams_.insert(id); } diff --git a/test/common/router/config_impl_test.cc b/test/common/router/config_impl_test.cc index 8905458b25237..d39ec87e3ea7f 100644 --- a/test/common/router/config_impl_test.cc +++ b/test/common/router/config_impl_test.cc @@ -6672,7 +6672,7 @@ class BazFactory : public HttpRouteTypedMetadataFactory { // Returns nullptr (conversion failure) if d is empty. std::unique_ptr parse(const Protobuf::Struct& d) const override { - if (d.fields().find("name") != d.fields().end()) { + if (d.fields().contains("name")) { return std::make_unique(d.fields().at("name").string_value()); } throw EnvoyException("Cannot create a Baz when metadata is empty."); @@ -8836,7 +8836,7 @@ TEST_F(RouteConfigurationV2, RouteTracingConfig) { std::vector custom_tags{"ltag", "etag", "rtag", "mtag"}; const Tracing::CustomTagMap& map = route3->tracingConfig()->getCustomTags(); for (const std::string& custom_tag : custom_tags) { - EXPECT_NE(map.find(custom_tag), map.end()); + EXPECT_TRUE(map.contains(custom_tag)); } NiceMock stream_info; @@ -10375,7 +10375,7 @@ TEST_F(RouteConfigurationV2, UpgradeConfigs) { genRedirectHeaders("idle.lyft.com", "/regex", true, false); const RouteEntry::UpgradeMap& upgrade_map = config.route(headers, 0)->routeEntry()->upgradeMap(); EXPECT_TRUE(upgrade_map.find("websocket")->second); - EXPECT_TRUE(upgrade_map.find("foo") == upgrade_map.end()); + EXPECT_FALSE(upgrade_map.contains("foo")); EXPECT_FALSE(upgrade_map.find("disabled")->second); } diff --git a/test/common/router/scoped_rds_test.cc b/test/common/router/scoped_rds_test.cc index 9a99e1f11838d..445bbd688e52d 100644 --- a/test/common/router/scoped_rds_test.cc +++ b/test/common/router/scoped_rds_test.cc @@ -441,7 +441,7 @@ name: foo_scoped_routes TestUtility::parseYaml( fmt::format(route_config_tmpl, name)); const auto decoded_resources = TestUtility::decodeResources({route_config}); - if (rds_subscription_by_name_.find(name) == rds_subscription_by_name_.end()) { + if (!rds_subscription_by_name_.contains(name)) { continue; } EXPECT_OK( diff --git a/test/common/stats/stat_test_utility.h b/test/common/stats/stat_test_utility.h index 5d31491882a07..4a1ecef794c46 100644 --- a/test/common/stats/stat_test_utility.h +++ b/test/common/stats/stat_test_utility.h @@ -176,7 +176,7 @@ class TestSinkPredicates : public SinkPredicates { public: ~TestSinkPredicates() override = default; - bool has(StatName name) { return sinked_stat_names_.find(name) != sinked_stat_names_.end(); } + bool has(StatName name) { return sinked_stat_names_.contains(name); } // Note: The backing store for the StatName needs to live longer than the // TestSinkPredicates object. @@ -184,16 +184,16 @@ class TestSinkPredicates : public SinkPredicates { // SinkPredicates bool includeCounter(const Counter& counter) override { - return sinked_stat_names_.find(counter.statName()) != sinked_stat_names_.end(); + return sinked_stat_names_.contains(counter.statName()); } bool includeGauge(const Gauge& gauge) override { - return sinked_stat_names_.find(gauge.statName()) != sinked_stat_names_.end(); + return sinked_stat_names_.contains(gauge.statName()); } bool includeTextReadout(const TextReadout& text_readout) override { - return sinked_stat_names_.find(text_readout.statName()) != sinked_stat_names_.end(); + return sinked_stat_names_.contains(text_readout.statName()); } bool includeHistogram(const Histogram& histogram) override { - return sinked_stat_names_.find(histogram.statName()) != sinked_stat_names_.end(); + return sinked_stat_names_.contains(histogram.statName()); } private: diff --git a/test/common/upstream/upstream_impl_test.cc b/test/common/upstream/upstream_impl_test.cc index 8663936aa4771..1d7179006b15f 100644 --- a/test/common/upstream/upstream_impl_test.cc +++ b/test/common/upstream/upstream_impl_test.cc @@ -4816,7 +4816,7 @@ class BazFactory : public ClusterTypedMetadataFactory { // Returns nullptr (conversion failure) if d is empty. std::unique_ptr parse(const Protobuf::Struct& d) const override { - if (d.fields().find("name") != d.fields().end()) { + if (d.fields().contains("name")) { return std::make_unique(d.fields().at("name").string_value()); } throw EnvoyException("Cannot create a Baz when metadata is empty."); @@ -5908,7 +5908,7 @@ TEST_F(ClusterInfoImplTest, ExtensionProtocolOptionsForFilterWithOptions) { []() -> ProtobufTypes::MessagePtr { return std::make_unique(); }, [&](const Protobuf::Message& msg) -> Upstream::ProtocolOptionsConfigConstSharedPtr { const auto& msg_struct = Envoy::Protobuf::DynamicCastMessage(msg); - EXPECT_TRUE(msg_struct.fields().find("option") != msg_struct.fields().end()); + EXPECT_TRUE(msg_struct.fields().contains("option")); return protocol_options; }); diff --git a/test/integration/utility.cc b/test/integration/utility.cc index 9becce8810f08..38d2a3f1b9197 100644 --- a/test/integration/utility.cc +++ b/test/integration/utility.cc @@ -479,7 +479,7 @@ Api::SysCallIntResult OsSysCallsWithMockedDns::getaddrinfo(const char* node, } return {0, 0}; } - if (nonexisting_addresses_.find(node) != nonexisting_addresses_.end()) { + if (nonexisting_addresses_.contains(node)) { return {EAI_NONAME, 0}; } std::cerr << "Mock DNS does not have entry for: " << node << std::endl; diff --git a/test/mocks/server/config_tracker.cc b/test/mocks/server/config_tracker.cc index bf53f7501e3ac..e30b0cbe45075 100644 --- a/test/mocks/server/config_tracker.cc +++ b/test/mocks/server/config_tracker.cc @@ -14,7 +14,7 @@ using ::testing::Invoke; MockConfigTracker::MockConfigTracker() { ON_CALL(*this, add_(_, _)) .WillByDefault(Invoke([this](const std::string& key, Cb callback) -> EntryOwner* { - EXPECT_TRUE(config_tracker_callbacks_.find(key) == config_tracker_callbacks_.end()); + EXPECT_FALSE(config_tracker_callbacks_.contains(key)); config_tracker_callbacks_[key] = callback; return new MockEntryOwner(); })); diff --git a/test/mocks/upstream/cluster_manager.cc b/test/mocks/upstream/cluster_manager.cc index 4a4a5272a3941..2562281aea0c1 100644 --- a/test/mocks/upstream/cluster_manager.cc +++ b/test/mocks/upstream/cluster_manager.cc @@ -87,8 +87,7 @@ void MockClusterManager::initializeClusters(const std::vector& acti })); ON_CALL(*this, hasCluster(_)) .WillByDefault(Invoke([this](absl::string_view cluster_name) -> bool { - return active_clusters_.find(cluster_name) != active_clusters_.end() || - warming_clusters_.find(cluster_name) != warming_clusters_.end(); + return active_clusters_.contains(cluster_name) || warming_clusters_.contains(cluster_name); })); ON_CALL(*this, hasActiveClusters()).WillByDefault(Return(!active_cluster_names.empty())); } diff --git a/test/server/admin/prometheus_stats_test.cc b/test/server/admin/prometheus_stats_test.cc index 440c7f2155bff..acd6d65d5f93b 100644 --- a/test/server/admin/prometheus_stats_test.cc +++ b/test/server/admin/prometheus_stats_test.cc @@ -2341,8 +2341,8 @@ TEST_F(RealHistogramNativePrometheusTest, NativeHistogramDenseDataAccuracy) { NativeHistogramDecoder::expectedBucketIndex(schema, static_cast(v)); // The bucket should exist - EXPECT_TRUE(buckets.count(expected_idx) > 0 || buckets.count(expected_idx - 1) > 0 || - buckets.count(expected_idx + 1) > 0) + EXPECT_TRUE(buckets.contains(expected_idx) || buckets.contains(expected_idx - 1) || + buckets.contains(expected_idx + 1)) << "Value " << v << " should be in bucket near index " << expected_idx; } diff --git a/test/server/config_validation/xds_fuzz.cc b/test/server/config_validation/xds_fuzz.cc index e9393dee7f88f..e44ce7522c405 100644 --- a/test/server/config_validation/xds_fuzz.cc +++ b/test/server/config_validation/xds_fuzz.cc @@ -395,7 +395,7 @@ std::vector XdsFuzzTest::getRoutes auto map = test_server_->server().admin()->getConfigTracker().getCallbacksMap(); // There is no route config dump before envoy has a route. - if (map.find("routes") == map.end()) { + if (!map.contains("routes")) { return {}; } diff --git a/test/test_common/simulated_time_system.cc b/test/test_common/simulated_time_system.cc index a1f2017cc23c8..0d1d5e2dc11d0 100644 --- a/test/test_common/simulated_time_system.cc +++ b/test/test_common/simulated_time_system.cc @@ -180,9 +180,7 @@ class SimulatedTimeSystemHelper::SimulatedScheduler : public Scheduler { return true; } - bool contains(Alarm& alarm) const { - return alarm_registrations_map_.find(&alarm) != alarm_registrations_map_.end(); - } + bool contains(Alarm& alarm) const { return alarm_registrations_map_.contains(&alarm); } private: std::set sorted_alarms_;