Skip to content

Commit ab51310

Browse files
committed
Merge bitcoin#33192: refactor: unify container presence checks
d9319b0 refactor: unify container presence checks - non-trivial counts (Lőrinc) 0393075 refactor: unify container presence checks - trivial counts (Lőrinc) 8bb9219 refactor: unify container presence checks - find (Lőrinc) Pull request description: ### Summary Instead of counting occurrences in sets and maps, the C++20 `::contains` method expresses the intent unambiguously and can return early on first encounter. ### Context Applied clang‑tidy's [readability‑container‑contains](https://clang.llvm.org/extra/clang-tidy/checks/readability/container-contains.html) check, though many cases required manual changes since tidy couldn't fix them automatically. ### Changes The changes made here were: | From | To | |------------------------|------------------| | `m.find(k) == m.end()` | `!m.contains(k)` | | `m.find(k) != m.end()` | `m.contains(k)` | | `m.count(k)` | `m.contains(k)` | | `!m.count(k)` | `!m.contains(k)` | | `m.count(k) == 0` | `!m.contains(k)` | | `m.count(k) != 1` | `!m.contains(k)` | | `m.count(k) == 1` | `m.contains(k)` | | `m.count(k) < 1` | `!m.contains(k)` | | `m.count(k) > 0` | `m.contains(k)` | | `m.count(k) != 0` | `m.contains(k)` | > Note that `== 1`/`!= 1`/`< 1` only apply to simple [maps](https://en.cppreference.com/w/cpp/container/map/contains)/[sets](https://en.cppreference.com/w/cpp/container/set/contains) and had to be changed manually. There are many other cases that could have been changed, but we've reverted most of those to reduce conflict with other open PRs. ----- <details> <summary>clang-tidy command on Mac</summary> ```bash rm -rfd build && \ cmake -B build \ -DCMAKE_C_COMPILER="$(brew --prefix llvm)/bin/clang" \ -DCMAKE_CXX_COMPILER="$(brew --prefix llvm)/bin/clang++" \ -DCMAKE_OSX_SYSROOT="$(xcrun --show-sdk-path)" \ -DCMAKE_C_FLAGS="-target arm64-apple-macos11" \ -DCMAKE_CXX_FLAGS="-target arm64-apple-macos11" \ -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -DBUILD_BENCH=ON -DBUILD_FUZZ_BINARY=ON -DBUILD_FOR_FUZZING=ON "$(brew --prefix llvm)/bin/run-clang-tidy" -quiet -p build -j$(nproc) -checks='-*,readability-container-contains' | grep -v 'clang-tidy' ``` </details> Note: this is a take 2 of bitcoin#33094 with fewer contentious changes. ACKs for top commit: optout21: reACK d9319b0 sedited: ACK d9319b0 janb84: re ACK d9319b0 pablomartin4btc: re-ACK d9319b0 ryanofsky: Code review ACK d9319b0. I manually reviewed the full change, and it seems there are a lot of positive comments about this and no more very significant conflicts, so I will merge it shortly. Tree-SHA512: e4415221676cfb88413ccc446e5f4369df7a55b6642347277667b973f515c3c8ee5bfa9ee0022479c8de945c89fbc9ff61bd8ba086e70f30298cbc1762610fe1
2 parents fe0e31f + d9319b0 commit ab51310

63 files changed

Lines changed: 184 additions & 184 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

src/addrman.cpp

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -457,7 +457,7 @@ void AddrManImpl::Delete(nid_type nId)
457457
{
458458
AssertLockHeld(cs);
459459

460-
assert(mapInfo.count(nId) != 0);
460+
assert(mapInfo.contains(nId));
461461
AddrInfo& info = mapInfo[nId];
462462
assert(!info.fInTried);
463463
assert(info.nRefCount == 0);
@@ -516,7 +516,7 @@ void AddrManImpl::MakeTried(AddrInfo& info, nid_type nId)
516516
if (vvTried[nKBucket][nKBucketPos] != -1) {
517517
// find an item to evict
518518
nid_type nIdEvict = vvTried[nKBucket][nKBucketPos];
519-
assert(mapInfo.count(nIdEvict) == 1);
519+
assert(mapInfo.contains(nIdEvict));
520520
AddrInfo& infoOld = mapInfo[nIdEvict];
521521

522522
// Remove the to-be-evicted item from the tried set.
@@ -919,7 +919,7 @@ void AddrManImpl::ResolveCollisions_()
919919
bool erase_collision = false;
920920

921921
// If id_new not found in mapInfo remove it from m_tried_collisions
922-
if (mapInfo.count(id_new) != 1) {
922+
if (!mapInfo.contains(id_new)) {
923923
erase_collision = true;
924924
} else {
925925
AddrInfo& info_new = mapInfo[id_new];
@@ -985,7 +985,7 @@ std::pair<CAddress, NodeSeconds> AddrManImpl::SelectTriedCollision_()
985985
nid_type id_new = *it;
986986

987987
// If id_new not found in mapInfo remove it from m_tried_collisions
988-
if (mapInfo.count(id_new) != 1) {
988+
if (!mapInfo.contains(id_new)) {
989989
m_tried_collisions.erase(it);
990990
return {};
991991
}
@@ -1115,7 +1115,7 @@ int AddrManImpl::CheckAddrman() const
11151115
for (int n = 0; n < ADDRMAN_TRIED_BUCKET_COUNT; n++) {
11161116
for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
11171117
if (vvTried[n][i] != -1) {
1118-
if (!setTried.count(vvTried[n][i]))
1118+
if (!setTried.contains(vvTried[n][i]))
11191119
return -11;
11201120
const auto it{mapInfo.find(vvTried[n][i])};
11211121
if (it == mapInfo.end() || it->second.GetTriedBucket(nKey, m_netgroupman) != n) {
@@ -1132,7 +1132,7 @@ int AddrManImpl::CheckAddrman() const
11321132
for (int n = 0; n < ADDRMAN_NEW_BUCKET_COUNT; n++) {
11331133
for (int i = 0; i < ADDRMAN_BUCKET_SIZE; i++) {
11341134
if (vvNew[n][i] != -1) {
1135-
if (!mapNew.count(vvNew[n][i]))
1135+
if (!mapNew.contains(vvNew[n][i]))
11361136
return -12;
11371137
const auto it{mapInfo.find(vvNew[n][i])};
11381138
if (it == mapInfo.end() || it->second.GetBucketPosition(nKey, true, n) != i) {

src/bitcoin-cli.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1128,7 +1128,7 @@ static void ParseGetInfoResult(UniValue& result)
11281128
const std::string proxy = network["proxy"].getValStr();
11291129
if (proxy.empty()) continue;
11301130
// Add proxy to ordered_proxy if has not been processed
1131-
if (proxy_networks.find(proxy) == proxy_networks.end()) ordered_proxies.push_back(proxy);
1131+
if (!proxy_networks.contains(proxy)) ordered_proxies.push_back(proxy);
11321132

11331133
proxy_networks[proxy].push_back(network["name"].getValStr());
11341134
}

src/bitcoin-tx.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -588,7 +588,7 @@ static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
588588
CCoinsView viewDummy;
589589
CCoinsViewCache view(&viewDummy);
590590

591-
if (!registers.count("privatekeys"))
591+
if (!registers.contains("privatekeys"))
592592
throw std::runtime_error("privatekeys register variable must be set.");
593593
FillableSigningProvider tempKeystore;
594594
UniValue keysObj = registers["privatekeys"];
@@ -604,7 +604,7 @@ static void MutateTxSign(CMutableTransaction& tx, const std::string& flagStr)
604604
}
605605

606606
// Add previous txouts given in the RPC call:
607-
if (!registers.count("prevtxs"))
607+
if (!registers.contains("prevtxs"))
608608
throw std::runtime_error("prevtxs register variable must be set.");
609609
UniValue prevtxsObj = registers["prevtxs"];
610610
{

src/common/args.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@ std::list<SectionInfo> ArgsManager::GetUnrecognizedSections() const
164164

165165
LOCK(cs_args);
166166
std::list<SectionInfo> unrecognized = m_config_sections;
167-
unrecognized.remove_if([](const SectionInfo& appeared){ return available_sections.find(appeared.m_name) != available_sections.end(); });
167+
unrecognized.remove_if([](const SectionInfo& appeared){ return available_sections.contains(appeared.m_name); });
168168
return unrecognized;
169169
}
170170

@@ -832,7 +832,7 @@ std::variant<ChainType, std::string> ArgsManager::GetChainArg() const
832832

833833
bool ArgsManager::UseDefaultSection(const std::string& arg) const
834834
{
835-
return m_network == ChainTypeToString(ChainType::MAIN) || m_network_only_args.count(arg) == 0;
835+
return m_network == ChainTypeToString(ChainType::MAIN) || !m_network_only_args.contains(arg);
836836
}
837837

838838
common::SettingsValue ArgsManager::GetSetting(const std::string& arg) const

src/httprpc.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ static bool HTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
142142
jreq.URI = req->GetURI();
143143

144144
UniValue reply;
145-
bool user_has_whitelist = g_rpc_whitelist.count(jreq.authUser);
145+
bool user_has_whitelist = g_rpc_whitelist.contains(jreq.authUser);
146146
if (!user_has_whitelist && g_rpc_whitelist_default) {
147147
LogWarning("RPC User %s not allowed to call any methods", jreq.authUser);
148148
req->WriteReply(HTTP_FORBIDDEN);
@@ -151,7 +151,7 @@ static bool HTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
151151
// singleton request
152152
} else if (valRequest.isObject()) {
153153
jreq.parse(valRequest);
154-
if (user_has_whitelist && !g_rpc_whitelist[jreq.authUser].count(jreq.strMethod)) {
154+
if (user_has_whitelist && !g_rpc_whitelist[jreq.authUser].contains(jreq.strMethod)) {
155155
LogWarning("RPC User %s not allowed to call method %s", jreq.authUser, jreq.strMethod);
156156
req->WriteReply(HTTP_FORBIDDEN);
157157
return false;
@@ -181,7 +181,7 @@ static bool HTTPReq_JSONRPC(const std::any& context, HTTPRequest* req)
181181
const UniValue& request = valRequest[reqIdx].get_obj();
182182
// Parse method
183183
std::string strMethod = request.find_value("method").get_str();
184-
if (!g_rpc_whitelist[jreq.authUser].count(strMethod)) {
184+
if (!g_rpc_whitelist[jreq.authUser].contains(strMethod)) {
185185
LogWarning("RPC User %s not allowed to call method %s", jreq.authUser, strMethod);
186186
req->WriteReply(HTTP_FORBIDDEN);
187187
return false;
@@ -307,7 +307,7 @@ static bool InitRPCAuthentication()
307307
for (const std::string& strRPCWhitelist : gArgs.GetArgs("-rpcwhitelist")) {
308308
auto pos = strRPCWhitelist.find(':');
309309
std::string strUser = strRPCWhitelist.substr(0, pos);
310-
bool intersect = g_rpc_whitelist.count(strUser);
310+
bool intersect = g_rpc_whitelist.contains(strUser);
311311
std::set<std::string>& whitelist = g_rpc_whitelist[strUser];
312312
if (pos != std::string::npos) {
313313
std::string strWhitelist = strRPCWhitelist.substr(pos + 1);

src/init.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -968,7 +968,7 @@ bool AppInitParameterInteraction(const ArgsManager& args)
968968

969969
// Signal NODE_COMPACT_FILTERS if peerblockfilters and basic filters index are both enabled.
970970
if (args.GetBoolArg("-peerblockfilters", DEFAULT_PEERBLOCKFILTERS)) {
971-
if (g_enabled_filter_types.count(BlockFilterType::BASIC) != 1) {
971+
if (!g_enabled_filter_types.contains(BlockFilterType::BASIC)) {
972972
return InitError(_("Cannot set -peerblockfilters without -blockfilterindex."));
973973
}
974974

src/merkleblock.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter* filter, const std:
4040
for (unsigned int i = 0; i < block.vtx.size(); i++)
4141
{
4242
const Txid& hash{block.vtx[i]->GetHash()};
43-
if (txids && txids->count(hash)) {
43+
if (txids && txids->contains(hash)) {
4444
vMatch.push_back(true);
4545
} else if (filter && filter->IsRelevantAndUpdate(*block.vtx[i])) {
4646
vMatch.push_back(true);

src/net.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,7 @@ bool SeenLocal(const CService& addr)
329329
bool IsLocal(const CService& addr)
330330
{
331331
LOCK(g_maplocalhost_mutex);
332-
return mapLocalHost.count(addr) > 0;
332+
return mapLocalHost.contains(addr);
333333
}
334334

335335
bool CConnman::AlreadyConnectedToHost(std::string_view host) const
@@ -2629,7 +2629,7 @@ void CConnman::ThreadOpenConnections(const std::vector<std::string> connect, std
26292629
// (e.g. in case of -onlynet changes by the user), fixed seeds will
26302630
// be loaded only for networks for which we have no addresses.
26312631
seed_addrs.erase(std::remove_if(seed_addrs.begin(), seed_addrs.end(),
2632-
[&fixed_seed_networks](const CAddress& addr) { return fixed_seed_networks.count(addr.GetNetwork()) == 0; }),
2632+
[&fixed_seed_networks](const CAddress& addr) { return !fixed_seed_networks.contains(addr.GetNetwork()); }),
26332633
seed_addrs.end());
26342634
CNetAddr local;
26352635
local.SetInternal("fixedseeds");
@@ -2776,7 +2776,7 @@ void CConnman::ThreadOpenConnections(const std::vector<std::string> connect, std
27762776
m_anchors.pop_back();
27772777
if (!addr.IsValid() || IsLocal(addr) || !g_reachable_nets.Contains(addr) ||
27782778
!m_msgproc->HasAllDesirableServiceFlags(addr.nServices) ||
2779-
outbound_ipv46_peer_netgroups.count(m_netgroupman.GetGroup(addr))) continue;
2779+
outbound_ipv46_peer_netgroups.contains(m_netgroupman.GetGroup(addr))) continue;
27802780
addrConnect = addr;
27812781
LogDebug(BCLog::NET, "Trying to make an anchor connection to %s\n", addrConnect.ToStringAddrPort());
27822782
break;
@@ -2822,7 +2822,7 @@ void CConnman::ThreadOpenConnections(const std::vector<std::string> connect, std
28222822
}
28232823

28242824
// Require outbound IPv4/IPv6 connections, other than feelers, to be to distinct network groups
2825-
if (!fFeeler && outbound_ipv46_peer_netgroups.count(m_netgroupman.GetGroup(addr))) {
2825+
if (!fFeeler && outbound_ipv46_peer_netgroups.contains(m_netgroupman.GetGroup(addr))) {
28262826
continue;
28272827
}
28282828

src/net_processing.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1159,7 +1159,7 @@ std::chrono::microseconds PeerManagerImpl::NextInvToInbounds(std::chrono::micros
11591159

11601160
bool PeerManagerImpl::IsBlockRequested(const uint256& hash)
11611161
{
1162-
return mapBlocksInFlight.count(hash);
1162+
return mapBlocksInFlight.contains(hash);
11631163
}
11641164

11651165
bool PeerManagerImpl::IsBlockRequestedFromOutbound(const uint256& hash)

src/netbase.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -132,7 +132,7 @@ class ReachableNets {
132132
{
133133
AssertLockNotHeld(m_mutex);
134134
LOCK(m_mutex);
135-
return m_reachable.count(net) > 0;
135+
return m_reachable.contains(net);
136136
}
137137

138138
[[nodiscard]] bool Contains(const CNetAddr& addr) const EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)

0 commit comments

Comments
 (0)