Skip to content

Commit

Permalink
tidy: Replace x.size() == 0 with x.empty() (envoyproxy#6511)
Browse files Browse the repository at this point in the history
Signed-off-by: James Synge <jamessynge@google.com>
  • Loading branch information
jamessynge authored and mattklein123 committed Apr 10, 2019
1 parent f7687d5 commit 814dd9f
Show file tree
Hide file tree
Showing 32 changed files with 40 additions and 40 deletions.
4 changes: 2 additions & 2 deletions .clang-tidy
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Checks: 'clang-diagnostic-*,clang-analyzer-*,abseil-*,bugprone-*,modernize-*,performance-*,readability-redundant-*,readability-braces-around-statements'
Checks: 'clang-diagnostic-*,clang-analyzer-*,abseil-*,bugprone-*,modernize-*,performance-*,readability-redundant-*,readability-braces-around-statements,readability-container-size-empty'

#TODO(lizan): grow this list, fix possible warnings and make more checks as error
WarningsAsErrors: 'bugprone-assert-side-effect,modernize-make-shared,modernize-make-unique,readability-redundant-smartptr-get,readability-braces-around-statements,readability-redundant-string-cstr,bugprone-use-after-move'
WarningsAsErrors: 'bugprone-assert-side-effect,modernize-make-shared,modernize-make-unique,readability-redundant-smartptr-get,readability-braces-around-statements,readability-redundant-string-cstr,bugprone-use-after-move,readability-container-size-empty'

CheckOptions:
- key: bugprone-assert-side-effect.AssertMacros
Expand Down
2 changes: 1 addition & 1 deletion source/common/buffer/buffer_impl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ void OwnedImpl::prepend(absl::string_view data) {
// only seems to happen the original buffer was created via
// addBufferFragment(), this forces the code execution path in
// evbuffer_prepend related to immutable buffers.
if (data.size() == 0) {
if (data.empty()) {
return;
}
evbuffer_prepend(buffer_.get(), data.data(), data.size());
Expand Down
2 changes: 1 addition & 1 deletion source/common/common/hex.cc
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ std::string Hex::encode(const uint8_t* data, size_t length) {
}

std::vector<uint8_t> Hex::decode(const std::string& hex_string) {
if (hex_string.size() == 0 || hex_string.size() % 2 != 0) {
if (hex_string.empty() || hex_string.size() % 2 != 0) {
return {};
}

Expand Down
2 changes: 1 addition & 1 deletion source/common/config/grpc_mux_impl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ void GrpcMuxImpl::onDiscoveryResponse(
}
// onConfigUpdate should be called only on watches(clusters/routes) that have
// updates in the message for EDS/RDS.
if (found_resources.size() > 0) {
if (!found_resources.empty()) {
watch->callbacks_.onConfigUpdate(found_resources, message->version_info());
}
}
Expand Down
2 changes: 1 addition & 1 deletion source/common/http/http1/conn_pool.cc
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ ConnectionPool::Cancellable* ConnPoolImpl::newStream(StreamDecoder& response_dec
}

// If we have no connections at all, make one no matter what so we don't starve.
if ((ready_clients_.size() == 0 && busy_clients_.size() == 0) || can_create_connection) {
if ((ready_clients_.empty() && busy_clients_.empty()) || can_create_connection) {
createNewConnection();
}

Expand Down
6 changes: 3 additions & 3 deletions source/common/router/config_impl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -970,11 +970,11 @@ RouteMatcher::RouteMatcher(const envoy::api::v2::RouteConfiguration& route_confi
throw EnvoyException(fmt::format("Only a single wildcard domain is permitted"));
}
default_virtual_host_ = virtual_host;
} else if (domain.size() > 0 && '*' == domain[0]) {
} else if (!domain.empty() && '*' == domain[0]) {
duplicate_found = !wildcard_virtual_host_suffixes_[domain.size() - 1]
.emplace(domain.substr(1), virtual_host)
.second;
} else if (domain.size() > 0 && '*' == domain[domain.size() - 1]) {
} else if (!domain.empty() && '*' == domain[domain.size() - 1]) {
duplicate_found = !wildcard_virtual_host_prefixes_[domain.size() - 1]
.emplace(domain.substr(0, domain.size() - 1), virtual_host)
.second;
Expand Down Expand Up @@ -1076,7 +1076,7 @@ VirtualHostImpl::virtualClusterFromEntries(const Http::HeaderMap& headers) const
}
}

if (virtual_clusters_.size() > 0) {
if (!virtual_clusters_.empty()) {
return &VIRTUAL_CLUSTER_CATCH_ALL;
}

Expand Down
2 changes: 1 addition & 1 deletion source/common/router/header_formatter.cc
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ parsePerRequestStateField(absl::string_view param_str) {
throw EnvoyException(formatPerRequestStateParseException(param_str));
}
modified_param_str = modified_param_str.substr(1, modified_param_str.size() - 2); // trim parens
if (modified_param_str.size() == 0) {
if (modified_param_str.empty()) {
throw EnvoyException(formatPerRequestStateParseException(param_str));
}

Expand Down
2 changes: 1 addition & 1 deletion source/common/router/header_parser.cc
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,7 @@ parseInternal(const envoy::api::v2::core::HeaderValueOption& header_value_option
formatters.emplace_back(new PlainHeaderFormatter(unescape(literal), append));
}

ASSERT(formatters.size() > 0);
ASSERT(!formatters.empty());

if (formatters.size() == 1) {
return std::move(formatters[0]);
Expand Down
2 changes: 1 addition & 1 deletion source/common/router/rds_impl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ RouteConfigProviderManagerImpl::dumpRouteConfigs() const {
// of this code, locking the weak_ptr will not fail.
auto subscription = element.second.lock();
ASSERT(subscription);
ASSERT(subscription->route_config_providers_.size() > 0);
ASSERT(!subscription->route_config_providers_.empty());

if (subscription->config_info_) {
auto* dynamic_config = config_dump->mutable_dynamic_route_configs()->Add();
Expand Down
2 changes: 1 addition & 1 deletion source/common/router/shadow_writer_impl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ void ShadowWriterImpl::shadow(const std::string& cluster, Http::MessagePtr&& req
ASSERT(!request->headers().Host()->value().empty());
// Switch authority to add a shadow postfix. This allows upstream logging to make more sense.
auto parts = StringUtil::splitToken(request->headers().Host()->value().c_str(), ":");
ASSERT(parts.size() > 0 && parts.size() <= 2);
ASSERT(!parts.empty() && parts.size() <= 2);
request->headers().Host()->value(
parts.size() == 2 ? absl::StrJoin(parts, "-shadow:")
: absl::StrCat(request->headers().Host()->value().c_str(), "-shadow"));
Expand Down
2 changes: 1 addition & 1 deletion source/common/upstream/health_checker_impl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ TcpHealthCheckMatcher::MatchSegments TcpHealthCheckMatcher::loadProtoBytes(

for (const auto& entry : byte_array) {
const auto decoded = Hex::decode(entry.text());
if (decoded.size() == 0) {
if (decoded.empty()) {
throw EnvoyException(fmt::format("invalid hex string '{}'", entry.text()));
}
result.push_back(decoded);
Expand Down
8 changes: 4 additions & 4 deletions source/common/upstream/load_balancer_impl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ void LoadBalancerBase::recalculatePerPriorityState(uint32_t priority,
// by the overprovisioning factor.
HostSet& host_set = *priority_set.hostSetsPerPriority()[priority];
per_priority_health.get()[priority] = 0;
if (host_set.hosts().size() > 0) {
if (!host_set.hosts().empty()) {
// Each priority level's health is ratio of healthy hosts to total number of hosts in a priority
// multiplied by overprovisioning factor of 1.4 and capped at 100%. It means that if all
// hosts are healthy that priority's health is 100%*1.4=140% and is capped at 100% which results
Expand Down Expand Up @@ -442,11 +442,11 @@ HostConstSharedPtr LoadBalancerBase::chooseHost(LoadBalancerContext* context) {
bool LoadBalancerBase::isGlobalPanic(const HostSet& host_set) {
uint64_t global_panic_threshold = std::min<uint64_t>(
100, runtime_.snapshot().getInteger(RuntimePanicThreshold, default_healthy_panic_percent_));
double healthy_percent = host_set.hosts().size() == 0
double healthy_percent = host_set.hosts().empty()
? 0
: 100.0 * host_set.healthyHosts().size() / host_set.hosts().size();

double degraded_percent = host_set.hosts().size() == 0
double degraded_percent = host_set.hosts().empty()
? 0
: 100.0 * host_set.degradedHosts().size() / host_set.hosts().size();
// If the % of healthy hosts in the cluster is less than our panic threshold, we use all hosts.
Expand Down Expand Up @@ -692,7 +692,7 @@ HostConstSharedPtr EdfLoadBalancerBase::chooseHostOnce(LoadBalancerContext* cont
return host;
} else {
const HostVector& hosts_to_use = hostSourceToHosts(hosts_source);
if (hosts_to_use.size() == 0) {
if (hosts_to_use.empty()) {
return nullptr;
}
return unweightedHostPick(hosts_to_use, hosts_source);
Expand Down
2 changes: 1 addition & 1 deletion source/common/upstream/load_stats_reporter.cc
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ void LoadStatsReporter::sendLoadStatsRequest() {
for (auto& host_set : cluster.prioritySet().hostSetsPerPriority()) {
ENVOY_LOG(trace, "Load report locality count {}", host_set->hostsPerLocality().get().size());
for (auto& hosts : host_set->hostsPerLocality().get()) {
ASSERT(hosts.size() > 0);
ASSERT(!hosts.empty());
uint64_t rq_success = 0;
uint64_t rq_error = 0;
uint64_t rq_active = 0;
Expand Down
2 changes: 1 addition & 1 deletion source/common/upstream/original_dst_cluster.cc
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ void OriginalDstCluster::cleanup() {
}
}

if (to_be_removed.size() > 0) {
if (!to_be_removed.empty()) {
priority_set_.updateHosts(0,
HostSetImpl::partitionHosts(new_hosts, HostsPerLocalityImpl::empty()),
{}, {}, to_be_removed, absl::nullopt);
Expand Down
2 changes: 1 addition & 1 deletion source/common/upstream/subset_lb.cc
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,7 @@ bool SubsetLoadBalancer::hostMatches(const SubsetMetadata& kvs, const Host& host
host_metadata.filter_metadata().find(Config::MetadataFilters::get().ENVOY_LB);

if (filter_it == host_metadata.filter_metadata().end()) {
return kvs.size() == 0;
return kvs.empty();
}

const ProtobufWkt::Struct& data_struct = filter_it->second;
Expand Down
2 changes: 1 addition & 1 deletion source/common/upstream/upstream_impl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ parseClusterSocketOptions(const envoy::api::v2::Cluster& config,
// Cluster socket_options trump cluster manager wide.
if (bind_config.socket_options().size() + config.upstream_bind_config().socket_options().size() >
0) {
auto socket_options = config.upstream_bind_config().socket_options().size() > 0
auto socket_options = !config.upstream_bind_config().socket_options().empty()
? config.upstream_bind_config().socket_options()
: bind_config.socket_options();
Network::Socket::appendOptions(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ Config::Config(const envoy::config::filter::http::header_to_metadata::v2::Config

bool Config::configToVector(const ProtobufRepeatedRule& proto_rules,
HeaderToMetadataRules& vector) {
if (proto_rules.size() == 0) {
if (proto_rules.empty()) {
ENVOY_LOG(debug, "no rules provided");
return false;
}
Expand Down Expand Up @@ -174,7 +174,7 @@ void HeaderToMetadataFilter::writeHeaderToMetadata(Http::HeaderMap& headers,
}

// Any matching rules?
if (structs_by_namespace.size() > 0) {
if (!structs_by_namespace.empty()) {
for (auto const& entry : structs_by_namespace) {
callbacks.streamInfo().setDynamicMetadata(entry.first, entry.second);
}
Expand Down
2 changes: 1 addition & 1 deletion source/extensions/filters/http/jwt_authn/verifier.cc
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ class ContextImpl : public Verifier::Context {
}

void setPayload() {
if (payload_.fields().size() > 0) {
if (!payload_.fields().empty()) {
callback_->setPayload(payload_);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ HttpConnectionManagerConfig::HttpConnectionManagerConfig(
throw EnvoyException(
fmt::format("Error: multiple upgrade configs with the same name: '{}'", name));
}
if (upgrade_config.filters().size() > 0) {
if (!upgrade_config.filters().empty()) {
std::unique_ptr<FilterFactoriesList> factories = std::make_unique<FilterFactoriesList>();
for (int32_t i = 0; i < upgrade_config.filters().size(); i++) {
processFilter(upgrade_config.filters(i), i, name, *factories);
Expand Down
2 changes: 1 addition & 1 deletion source/extensions/tracers/zipkin/span_context_extractor.cc
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ std::pair<SpanContext, bool> SpanContextExtractor::extractSpanContext(bool is_sa
}

auto b3_parent_id_entry = request_headers_.get(ZipkinCoreConstants::get().X_B3_PARENT_SPAN_ID);
if (b3_parent_id_entry && b3_parent_id_entry->value().size() > 0) {
if (b3_parent_id_entry && !b3_parent_id_entry->value().empty()) {
const std::string pspid = b3_parent_id_entry->value().c_str();
if (!StringUtil::atoull(pspid.c_str(), parent_id, 16)) {
throw ExtractorException(fmt::format("Invalid parent span id {}", pspid.c_str()));
Expand Down
2 changes: 1 addition & 1 deletion source/extensions/tracers/zipkin/util.cc
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ void Util::addArrayToJson(std::string& target, const std::vector<std::string>& j
const std::string& field_name) {
std::string stringified_json_array = "[";

if (json_array.size() > 0) {
if (!json_array.empty()) {
stringified_json_array += json_array[0];
for (auto it = json_array.begin() + 1; it != json_array.end(); it++) {
stringified_json_array += ",";
Expand Down
2 changes: 1 addition & 1 deletion source/extensions/tracers/zipkin/zipkin_core_types.cc
Original file line number Diff line number Diff line change
Expand Up @@ -253,7 +253,7 @@ void Span::finish() {
}

void Span::setTag(const std::string& name, const std::string& value) {
if (name.size() > 0 && value.size() > 0) {
if (!name.empty() && !value.empty()) {
addBinaryAnnotation(BinaryAnnotation(name, value));
}
}
Expand Down
2 changes: 1 addition & 1 deletion source/extensions/tracers/zipkin/zipkin_tracer_impl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ Driver::Driver(const envoy::config::trace::v2::ZipkinConfig& zipkin_config,
cluster_ = cm_.get(zipkin_config.collector_cluster())->info();

std::string collector_endpoint = ZipkinCoreConstants::get().DEFAULT_COLLECTOR_ENDPOINT;
if (zipkin_config.collector_endpoint().size() > 0) {
if (!zipkin_config.collector_endpoint().empty()) {
collector_endpoint = zipkin_config.collector_endpoint();
}

Expand Down
2 changes: 1 addition & 1 deletion source/server/http/admin.cc
Original file line number Diff line number Diff line change
Expand Up @@ -586,7 +586,7 @@ Http::Code AdminImpl::handlerLogging(absl::string_view url, Http::HeaderMap&,
Http::Utility::QueryParams query_params = Http::Utility::parseQueryString(url);

Http::Code rc = Http::Code::OK;
if (query_params.size() > 0 && !changeLogLevel(query_params)) {
if (!query_params.empty() && !changeLogLevel(query_params)) {
response.add("usage: /logging?<name>=<level> (change single level)\n");
response.add("usage: /logging?level=<level> (change all levels)\n");
response.add("levels: ");
Expand Down
2 changes: 1 addition & 1 deletion source/server/listener_manager_impl.cc
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ ListenerImpl::ListenerImpl(const envoy::api::v2::Listener& config, const std::st
config.tcp_fast_open_queue_length().value()));
}

if (config.socket_options().size() > 0) {
if (!config.socket_options().empty()) {
addListenSocketOptions(
Network::SocketOptionFactory::buildLiteralOptions(config.socket_options()));
}
Expand Down
2 changes: 1 addition & 1 deletion test/common/upstream/health_checker_impl_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2809,7 +2809,7 @@ class GrpcHealthCheckerImplTestBase {
}

void respondResponseSpec(size_t index, ResponseSpec&& spec) {
const bool trailers_empty = spec.trailers.size() == 0U;
const bool trailers_empty = spec.trailers.empty();
const bool end_stream_on_headers = spec.body_chunks.empty() && trailers_empty;
auto response_headers = std::make_unique<Http::TestHeaderMapImpl>();
for (const auto& header : spec.response_headers) {
Expand Down
2 changes: 1 addition & 1 deletion test/common/upstream/load_balancer_impl_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ TEST_P(LoadBalancerBaseTest, PrioritySelectionFuzz) {
// Either we selected one of the healthy hosts or we failed to select anything and defaulted
// to healthy.
EXPECT_TRUE(!hs.first.healthyHosts().empty() ||
(hs.first.healthyHosts().size() == 0 && hs.first.degradedHosts().size() == 0));
(hs.first.healthyHosts().empty() && hs.first.degradedHosts().empty()));
break;
case LoadBalancerBase::HostAvailability::Degraded:
EXPECT_FALSE(hs.first.degradedHosts().empty());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ class HeaderToMetadataTest : public testing::Test {

MATCHER_P(MapEq, rhs, "") {
const ProtobufWkt::Struct& obj = arg;
EXPECT_TRUE(rhs.size() > 0);
EXPECT_TRUE(!rhs.empty());
for (auto const& entry : rhs) {
EXPECT_EQ(obj.fields().at(entry.first).string_value(), entry.second);
}
Expand All @@ -61,7 +61,7 @@ MATCHER_P(MapEq, rhs, "") {

MATCHER_P(MapEqNum, rhs, "") {
const ProtobufWkt::Struct& obj = arg;
EXPECT_TRUE(rhs.size() > 0);
EXPECT_TRUE(!rhs.empty());
for (auto const& entry : rhs) {
EXPECT_EQ(obj.fields().at(entry.first).number_value(), entry.second);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ void BaseThriftIntegrationTest::preparePayloads(const PayloadOptions& options,
args.push_back(*options.service_name_);
}

if (options.headers_.size() > 0) {
if (!options.headers_.empty()) {
args.push_back("-H");

std::vector<std::string> headers;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ namespace NetworkFilters {
namespace ZooKeeperProxy {

bool protoMapEq(const ProtobufWkt::Struct& obj, const std::map<std::string, std::string>& rhs) {
EXPECT_TRUE(rhs.size() > 0);
EXPECT_TRUE(!rhs.empty());
for (auto const& entry : rhs) {
EXPECT_EQ(obj.fields().at(entry.first).string_value(), entry.second);
}
Expand Down
2 changes: 1 addition & 1 deletion test/integration/h1_capture_direct_response_fuzz_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ void H1FuzzIntegrationTest::initialize() {
}

DEFINE_PROTO_FUZZER(const test::integration::CaptureFuzzTestCase& input) {
RELEASE_ASSERT(TestEnvironment::getIpVersionsForTest().size() > 0, "");
RELEASE_ASSERT(!TestEnvironment::getIpVersionsForTest().empty(), "");
const auto ip_version = TestEnvironment::getIpVersionsForTest()[0];
H1FuzzIntegrationTest h1_fuzz_integration_test(ip_version);
h1_fuzz_integration_test.replay(input);
Expand Down
2 changes: 1 addition & 1 deletion test/integration/h1_capture_fuzz_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ void H1FuzzIntegrationTest::initialize() { HttpIntegrationTest::initialize(); }

DEFINE_PROTO_FUZZER(const test::integration::CaptureFuzzTestCase& input) {
// Pick an IP version to use for loopback, it doesn't matter which.
RELEASE_ASSERT(TestEnvironment::getIpVersionsForTest().size() > 0, "");
RELEASE_ASSERT(!TestEnvironment::getIpVersionsForTest().empty(), "");
const auto ip_version = TestEnvironment::getIpVersionsForTest()[0];
H1FuzzIntegrationTest h1_fuzz_integration_test(ip_version);
h1_fuzz_integration_test.replay(input);
Expand Down

0 comments on commit 814dd9f

Please sign in to comment.