Skip to content

Commit

Permalink
Merge bitcoin#13249: Make objects in range declarations immutable by …
Browse files Browse the repository at this point in the history
…default. Avoid unnecessary copying of objects in range declarations.

f34c8c4 Make objects in range declarations immutable by default. Avoid unnecessary copying of objects in range declarations. (practicalswift)

Pull request description:

  Make objects in range declarations immutable by default.

  Rationale:
  * Immutable objects are easier to reason about.
  * Prevents accidental or hard-to-notice change of value.

Tree-SHA512: cad69d35f0cf8a938b848e65dd537c621d96fe3369be306b65ef0cd1baf6cc0a9f28bc230e1e383d810c555a6743d08cb6b2b0bd51856d4611f537a12e5abb8b
  • Loading branch information
laanwj authored and PastaPastaPasta committed Jul 19, 2021
1 parent eeae2fc commit a45bab1
Show file tree
Hide file tree
Showing 33 changed files with 71 additions and 71 deletions.
4 changes: 2 additions & 2 deletions src/bech32.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ uint32_t PolyMod(const data& v)
// v, it corresponds to x^2 + v0*x + v1 mod g(x). As 1 mod g(x) = 1, that is the starting value
// for `c`.
uint32_t c = 1;
for (auto v_i : v) {
for (const auto v_i : v) {
// We want to update `c` to correspond to a polynomial with one extra term. If the initial
// value of `c` consists of the coefficients of c(x) = f(x) mod g(x), we modify it to
// correspond to c'(x) = (f(x) * x + v_i) mod g(x), where v_i is the next input to
Expand Down Expand Up @@ -149,7 +149,7 @@ std::string Encode(const std::string& hrp, const data& values) {
data combined = Cat(values, checksum);
std::string ret = hrp + '1';
ret.reserve(ret.size() + combined.size());
for (auto c : combined) {
for (const auto c : combined) {
ret += CHARSET[c];
}
return ret;
Expand Down
6 changes: 3 additions & 3 deletions src/cuckoocache.h
Original file line number Diff line number Diff line change
Expand Up @@ -396,15 +396,15 @@ class cache
std::array<uint32_t, 8> locs = compute_hashes(e);
// Make sure we have not already inserted this element
// If we have, make sure that it does not get deleted
for (uint32_t loc : locs)
for (const uint32_t loc : locs)
if (table[loc] == e) {
please_keep(loc);
epoch_flags[loc] = last_epoch;
return;
}
for (uint8_t depth = 0; depth < depth_limit; ++depth) {
// First try to insert to an empty slot, if one exists
for (uint32_t loc : locs) {
for (const uint32_t loc : locs) {
if (!collection_flags.bit_is_set(loc))
continue;
table[loc] = std::move(e);
Expand Down Expand Up @@ -468,7 +468,7 @@ class cache
inline bool contains(const Element& e, const bool erase) const
{
std::array<uint32_t, 8> locs = compute_hashes(e);
for (uint32_t loc : locs)
for (const uint32_t loc : locs)
if (table[loc] == e) {
if (erase)
allow_erase(loc);
Expand Down
8 changes: 4 additions & 4 deletions src/net.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ CNode* CConnman::FindNode(const CService& addr, bool fExcludeDisconnecting)
bool CConnman::CheckIncomingNonce(uint64_t nonce)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
for (const CNode* pnode : vNodes) {
if (!pnode->fSuccessfullyConnected && !pnode->fInbound && pnode->GetLocalNonce() == nonce)
return false;
}
Expand Down Expand Up @@ -2203,7 +2203,7 @@ void CConnman::ThreadDNSAddressSeed()

LOCK(cs_vNodes);
int nRelevant = 0;
for (auto pnode : vNodes) {
for (const CNode* pnode : vNodes) {
nRelevant += pnode->fSuccessfullyConnected && !pnode->fFeeler && !pnode->fOneShot && !pnode->m_manual_connection && !pnode->fInbound && !pnode->m_masternode_probe_connection;
}
if (nRelevant >= 2) {
Expand Down Expand Up @@ -2316,7 +2316,7 @@ int CConnman::GetExtraOutboundCount()
int nOutbound = 0;
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
for (const CNode* pnode : vNodes) {
// don't count outbound masternodes
if (pnode->m_masternode_connection) {
continue;
Expand Down Expand Up @@ -2391,7 +2391,7 @@ void CConnman::ThreadOpenConnections(const std::vector<std::string> connect)
std::set<std::vector<unsigned char> > setConnected;
if (!Params().AllowMultipleAddressesFromGroup()) {
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
for (const CNode* pnode : vNodes) {
if (!pnode->fInbound && !pnode->m_masternode_connection && !pnode->m_manual_connection) {
// Netgroups for inbound and addnode peers are not excluded because our goal here
// is to not use multiple of our limited outbound slots on a single netgroup
Expand Down
2 changes: 1 addition & 1 deletion src/net_processing.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1163,7 +1163,7 @@ void PeerLogicValidation::BlockConnected(const std::shared_ptr<const CBlock>& pb
// Erase orphan transactions included or precluded by this block
if (vOrphanErase.size()) {
int nErased = 0;
for (uint256 &orphanHash : vOrphanErase) {
for (const uint256& orphanHash : vOrphanErase) {
nErased += EraseOrphanTx(orphanHash);
}
LogPrint(BCLog::MEMPOOL, "Erased %d orphan tx included or conflicted by block\n", nErased);
Expand Down
2 changes: 1 addition & 1 deletion src/qt/bitcoingui.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1839,7 +1839,7 @@ void UnitDisplayStatusBarControl::mousePressEvent(QMouseEvent *event)
void UnitDisplayStatusBarControl::createContextMenu()
{
menu = new QMenu(this);
for (BitcoinUnits::Unit u : BitcoinUnits::availableUnits())
for (const BitcoinUnits::Unit u : BitcoinUnits::availableUnits())
{
QAction *menuAction = new QAction(QString(BitcoinUnits::name(u)), this);
menuAction->setData(QVariant(u));
Expand Down
2 changes: 1 addition & 1 deletion src/qt/dash.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -423,7 +423,7 @@ void BitcoinApplication::requestShutdown()

#ifdef ENABLE_WALLET
window->removeAllWallets();
for (WalletModel *walletModel : m_wallet_models) {
for (const WalletModel* walletModel : m_wallet_models) {
delete walletModel;
}
m_wallet_models.clear();
Expand Down
2 changes: 1 addition & 1 deletion src/qt/peertablemodel.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ class PeerTablePriv
node.getNodesStats(nodes_stats);
cachedNodeStats.reserve(nodes_stats.size());

for (auto& node_stats : nodes_stats)
for (const auto& node_stats : nodes_stats)
{
CNodeCombinedStats stats;
stats.nodeStats = std::get<0>(node_stats);
Expand Down
2 changes: 1 addition & 1 deletion src/qt/sendcoinsdialog.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -422,7 +422,7 @@ void SendCoinsDialog::send(QList<SendCoinsRecipient> recipients)
questionString.append("<hr />");
CAmount totalAmount = currentTransaction.getTotalTransactionAmount() + txFee;
QStringList alternativeUnits;
for (BitcoinUnits::Unit u : BitcoinUnits::availableUnits())
for (const BitcoinUnits::Unit u : BitcoinUnits::availableUnits())
{
if(u != model->getOptionsModel()->getDisplayUnit())
alternativeUnits.append(BitcoinUnits::formatHtmlWithUnit(u, totalAmount));
Expand Down
2 changes: 1 addition & 1 deletion src/qt/splashscreen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ void SplashScreen::unsubscribeFromCoreSignals()
#ifdef ENABLE_WALLET
m_handler_load_wallet->disconnect();
#endif // ENABLE_WALLET
for (auto& handler : m_connected_wallet_handlers) {
for (const auto& handler : m_connected_wallet_handlers) {
handler->disconnect();
}
m_connected_wallet_handlers.clear();
Expand Down
4 changes: 2 additions & 2 deletions src/qt/transactiondesc.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -164,13 +164,13 @@ QString TransactionDesc::toHTML(interfaces::Node& node, interfaces::Wallet& wall
else
{
isminetype fAllFromMe = ISMINE_SPENDABLE;
for (isminetype mine : wtx.txin_is_mine)
for (const isminetype mine : wtx.txin_is_mine)
{
if(fAllFromMe > mine) fAllFromMe = mine;
}

isminetype fAllToMe = ISMINE_SPENDABLE;
for (isminetype mine : wtx.txout_is_mine)
for (const isminetype mine : wtx.txout_is_mine)
{
if(fAllToMe > mine) fAllToMe = mine;
}
Expand Down
4 changes: 2 additions & 2 deletions src/qt/transactionrecord.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -82,14 +82,14 @@ QList<TransactionRecord> TransactionRecord::decomposeTransaction(interfaces::Wal
{
bool involvesWatchAddress = false;
isminetype fAllFromMe = ISMINE_SPENDABLE;
for (isminetype mine : wtx.txin_is_mine)
for (const isminetype mine : wtx.txin_is_mine)
{
if(mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true;
if(fAllFromMe > mine) fAllFromMe = mine;
}

isminetype fAllToMe = ISMINE_SPENDABLE;
for (isminetype mine : wtx.txout_is_mine)
for (const isminetype mine : wtx.txout_is_mine)
{
if(mine & ISMINE_WATCH_ONLY) involvesWatchAddress = true;
if(fAllToMe > mine) fAllToMe = mine;
Expand Down
2 changes: 1 addition & 1 deletion src/rpc/blockchain.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,7 @@ static void entryToJSON(UniValue &info, const CTxMemPoolEntry &e) EXCLUSIVE_LOCK
UniValue spent(UniValue::VARR);
const CTxMemPool::txiter &it = mempool.mapTx.find(tx.GetHash());
const CTxMemPool::setEntries &setChildren = mempool.GetMemPoolChildren(it);
for (const CTxMemPool::txiter &childiter : setChildren) {
for (CTxMemPool::txiter childiter : setChildren) {
spent.push_back(childiter->GetTx().GetHash().ToString());
}

Expand Down
2 changes: 1 addition & 1 deletion src/rpc/mining.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -910,7 +910,7 @@ static UniValue estimaterawfee(const JSONRPCRequest& request)

UniValue result(UniValue::VOBJ);

for (FeeEstimateHorizon horizon : {FeeEstimateHorizon::SHORT_HALFLIFE, FeeEstimateHorizon::MED_HALFLIFE, FeeEstimateHorizon::LONG_HALFLIFE}) {
for (const FeeEstimateHorizon horizon : {FeeEstimateHorizon::SHORT_HALFLIFE, FeeEstimateHorizon::MED_HALFLIFE, FeeEstimateHorizon::LONG_HALFLIFE}) {
CFeeRate feeRate;
EstimationResult buckets;

Expand Down
2 changes: 1 addition & 1 deletion src/rpc/net.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ static UniValue getpeerinfo(const JSONRPCRequest& request)
obj.pushKV("synced_headers", statestats.nSyncHeight);
obj.pushKV("synced_blocks", statestats.nCommonHeight);
UniValue heights(UniValue::VARR);
for (int height : statestats.vHeightInFlight) {
for (const int height : statestats.vHeightInFlight) {
heights.push_back(height);
}
obj.pushKV("inflight", heights);
Expand Down
4 changes: 2 additions & 2 deletions src/test/checkqueue_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ static void Correct_Queue_range(std::vector<size_t> range)
small_queue->StartWorkerThreads(SCRIPT_CHECK_THREADS);
// Make vChecks here to save on malloc (this test can be slow...)
std::vector<FakeCheckCheckCompletion> vChecks;
for (auto i : range) {
for (const size_t i : range) {
size_t total = i;
FakeCheckCheckCompletion::n_calls = 0;
CCheckQueueControl<FakeCheckCheckCompletion> control(small_queue.get());
Expand Down Expand Up @@ -240,7 +240,7 @@ BOOST_AUTO_TEST_CASE(test_CheckQueue_Recovers_From_Failure)
fail_queue->StartWorkerThreads(SCRIPT_CHECK_THREADS);

for (auto times = 0; times < 10; ++times) {
for (bool end_fails : {true, false}) {
for (const bool end_fails : {true, false}) {
CCheckQueueControl<FailingCheck> control(fail_queue.get());
{
std::vector<FailingCheck> vChecks;
Expand Down
10 changes: 5 additions & 5 deletions src/test/coins_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -741,7 +741,7 @@ static void CheckAddCoinBase(CAmount base_value, CAmount cache_value, CAmount mo
template <typename... Args>
static void CheckAddCoin(Args&&... args)
{
for (CAmount base_value : {ABSENT, PRUNED, VALUE1})
for (const CAmount base_value : {ABSENT, PRUNED, VALUE1})
CheckAddCoinBase(base_value, std::forward<Args>(args)...);
}

Expand Down Expand Up @@ -853,10 +853,10 @@ BOOST_AUTO_TEST_CASE(ccoins_write)
// they would be too repetitive (the parent cache is never updated in these
// cases). The loop below covers these cases and makes sure the parent cache
// is always left unchanged.
for (CAmount parent_value : {ABSENT, PRUNED, VALUE1})
for (CAmount child_value : {ABSENT, PRUNED, VALUE2})
for (char parent_flags : parent_value == ABSENT ? ABSENT_FLAGS : FLAGS)
for (char child_flags : child_value == ABSENT ? ABSENT_FLAGS : CLEAN_FLAGS)
for (const CAmount parent_value : {ABSENT, PRUNED, VALUE1})
for (const CAmount child_value : {ABSENT, PRUNED, VALUE2})
for (const char parent_flags : parent_value == ABSENT ? ABSENT_FLAGS : FLAGS)
for (const char child_flags : child_value == ABSENT ? ABSENT_FLAGS : CLEAN_FLAGS)
CheckWriteCoins(parent_value, child_value, parent_value, parent_flags, child_flags, parent_flags);
}

Expand Down
6 changes: 3 additions & 3 deletions src/test/cuckoocache_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,11 @@ static double test_cache(size_t megabytes, double load)
*/
std::vector<uint256> hashes_insert_copy = hashes;
/** Do the insert */
for (uint256& h : hashes_insert_copy)
for (const uint256& h : hashes_insert_copy)
set.insert(h);
/** Count the hits */
uint32_t count = 0;
for (uint256& h : hashes)
for (const uint256& h : hashes)
count += set.contains(h, false);
double hit_rate = ((double)count) / ((double)n_insert);
return hit_rate;
Expand Down Expand Up @@ -324,7 +324,7 @@ static void test_cache_generations()
reads.push_back(inserts[i]);
for (uint32_t i = n_insert - (n_insert / 4); i < n_insert; ++i)
reads.push_back(inserts[i]);
for (auto h : inserts)
for (const auto& h : inserts)
c.insert(h);
}
};
Expand Down
10 changes: 5 additions & 5 deletions src/test/dbwrapper_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ BOOST_FIXTURE_TEST_SUITE(dbwrapper_tests, BasicTestingSetup)
BOOST_AUTO_TEST_CASE(dbwrapper)
{
// Perform tests both obfuscated and non-obfuscated.
for (bool obfuscate : {false, true}) {
for (const bool obfuscate : {false, true}) {
fs::path ph = SetDataDir(std::string("dbwrapper").append(obfuscate ? "_true" : "_false"));
CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate);
char key = 'k';
Expand Down Expand Up @@ -126,7 +126,7 @@ BOOST_AUTO_TEST_CASE(dbwrapper_basic_data)
BOOST_AUTO_TEST_CASE(dbwrapper_batch)
{
// Perform tests both obfuscated and non-obfuscated.
for (bool obfuscate : {false, true}) {
for (const bool obfuscate : {false, true}) {
fs::path ph = SetDataDir(std::string("dbwrapper_batch").append(obfuscate ? "_true" : "_false"));
CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate);

Expand Down Expand Up @@ -162,7 +162,7 @@ BOOST_AUTO_TEST_CASE(dbwrapper_batch)
BOOST_AUTO_TEST_CASE(dbwrapper_iterator)
{
// Perform tests both obfuscated and non-obfuscated.
for (bool obfuscate : {false, true}) {
for (const bool obfuscate : {false, true}) {
fs::path ph = SetDataDir(std::string("dbwrapper_iterator").append(obfuscate ? "_true" : "_false"));
CDBWrapper dbw(ph, (1 << 20), true, false, obfuscate);

Expand Down Expand Up @@ -296,7 +296,7 @@ BOOST_AUTO_TEST_CASE(iterator_ordering)
if (x & 1) BOOST_CHECK(dbw.Write(key, value));
}

for (int seek_start : {0x00, 0x80}) {
for (const int seek_start : {0x00, 0x80}) {
it->Seek((uint8_t)seek_start);
for (unsigned int x=seek_start; x<255; ++x) {
uint8_t key;
Expand Down Expand Up @@ -373,7 +373,7 @@ BOOST_AUTO_TEST_CASE(iterator_string_ordering)
}

std::unique_ptr<CDBIterator> it(const_cast<CDBWrapper&>(dbw).NewIterator());
for (int seek_start : {0, 5}) {
for (const int seek_start : {0, 5}) {
snprintf(buf, sizeof(buf), "%d", seek_start);
StringContentsSerializer seek_key(buf);
it->Seek(seek_key);
Expand Down
2 changes: 1 addition & 1 deletion src/test/getarg_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ static void ResetArgs(const std::string& strArg)

// Convert to char*:
std::vector<const char*> vecChar;
for (std::string& s : vecArg)
for (const std::string& s : vecArg)
vecChar.push_back(s.c_str());

std::string error;
Expand Down
2 changes: 1 addition & 1 deletion src/test/key_io_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ BOOST_AUTO_TEST_CASE(key_io_invalid)
std::string exp_base58string = test[0].get_str();

// must be invalid as public and as private key
for (auto chain : { CBaseChainParams::MAIN, CBaseChainParams::TESTNET, CBaseChainParams::REGTEST }) {
for (const auto& chain : { CBaseChainParams::MAIN, CBaseChainParams::TESTNET, CBaseChainParams::REGTEST }) {
SelectParams(chain);
destination = DecodeDestination(exp_base58string);
BOOST_CHECK_MESSAGE(!IsValidDestination(destination), "IsValid pubkey in mainnet:" + strTest);
Expand Down
2 changes: 1 addition & 1 deletion src/test/skiplist_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ BOOST_AUTO_TEST_CASE(findearliestatleast_test)
BOOST_AUTO_TEST_CASE(findearliestatleast_edge_test)
{
std::list<CBlockIndex> blocks;
for (unsigned int timeMax : {100, 100, 100, 200, 200, 200, 300, 300, 300}) {
for (const unsigned int timeMax : {100, 100, 100, 200, 200, 200, 300, 300, 300}) {
CBlockIndex* prev = blocks.empty() ? nullptr : &blocks.back();
blocks.emplace_back();
blocks.back().nHeight = prev ? prev->nHeight + 1 : 0;
Expand Down
2 changes: 1 addition & 1 deletion src/test/transaction_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ unsigned int ParseScriptFlags(std::string strFlags)
std::vector<std::string> words;
boost::algorithm::split(words, strFlags, boost::algorithm::is_any_of(","));

for (std::string word : words)
for (const std::string& word : words)
{
if (!mapFlagNames.count(word))
BOOST_ERROR("Bad test: unknown verification flag '" << word << "'");
Expand Down
4 changes: 2 additions & 2 deletions src/test/util_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -191,7 +191,7 @@ BOOST_AUTO_TEST_CASE(util_GetBoolArg)
testArgs.ParseParameters(7, (char**)argv_test, error);

// Each letter should be set.
for (char opt : "abcdef")
for (const char opt : "abcdef")
BOOST_CHECK(testArgs.IsArgSet({'-', opt}) || !opt);

// Nothing else should be in the map
Expand Down Expand Up @@ -340,7 +340,7 @@ BOOST_AUTO_TEST_CASE(util_ReadConfigStream)
&& test_args.GetArg("-iii", "xxx") == "xxx"
);

for (bool def : {false, true}) {
for (const bool def : {false, true}) {
BOOST_CHECK(test_args.GetBoolArg("-a", def)
&& test_args.GetBoolArg("-b", def)
&& !test_args.GetBoolArg("-ccc", def)
Expand Down
4 changes: 2 additions & 2 deletions src/timedata.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample)
{
// If nobody has a time different than ours but within 5 minutes of ours, give a warning
bool fMatch = false;
for (int64_t nOffset : vSorted)
for (const int64_t nOffset : vSorted)
if (nOffset != 0 && abs64(nOffset) < 5 * 60)
fMatch = true;

Expand All @@ -109,7 +109,7 @@ void AddTimeData(const CNetAddr& ip, int64_t nOffsetSample)
}

if (LogAcceptCategory(BCLog::NET)) {
for (int64_t n : vSorted) {
for (const int64_t n : vSorted) {
LogPrint(BCLog::NET, "%+d ", n); /* Continued */
}
LogPrint(BCLog::NET, "| "); /* Continued */
Expand Down
Loading

0 comments on commit a45bab1

Please sign in to comment.