Don't create temporary containers just to iterate over them

Stops temporary containers being created needlessly due to API misuse.
For example, it’s common for developers to assume QHash::values() and
QHash::keys() are free and abuse them, failing to realize their
implementation internally actually iterates the whole container, allocates
memory, and fills a new QList.

Added a removeIf generic algorithm, similar to std ones. We can't use std
algorithms with Qt dictionaries because Qt iterators have different
behavior from the std ones.

Found using clazy.
This commit is contained in:
Luís Pereira 2018-03-06 14:50:10 +00:00 committed by Vladimir Golovnev (Glassez)
parent e22946ef61
commit ac42ccb5e4
No known key found for this signature in database
GPG key ID: 52A2C7DEE2DFA6F7
14 changed files with 121 additions and 61 deletions

View file

@ -12,6 +12,7 @@
#endif
#endif
#include "algorithm.h"
#include "base/bittorrent/magneturi.h"
#include "base/bittorrent/torrentinfo.h"
#include "base/preferences.h"
@ -145,22 +146,24 @@ void FileSystemWatcher::processPartialTorrents()
QStringList noLongerPartial;
// Check which torrents are still partial
foreach (const QString &torrentPath, m_partialTorrents.keys()) {
if (!QFile::exists(torrentPath)) {
m_partialTorrents.remove(torrentPath);
}
else if (BitTorrent::TorrentInfo::loadFromFile(torrentPath).isValid()) {
Dict::removeIf(m_partialTorrents, [&noLongerPartial](const QString &torrentPath, int &value)
{
if (!QFile::exists(torrentPath))
return true;
if (BitTorrent::TorrentInfo::loadFromFile(torrentPath).isValid()) {
noLongerPartial << torrentPath;
m_partialTorrents.remove(torrentPath);
return true;
}
else if (m_partialTorrents[torrentPath] >= MAX_PARTIAL_RETRIES) {
m_partialTorrents.remove(torrentPath);
if (value >= MAX_PARTIAL_RETRIES) {
QFile::rename(torrentPath, torrentPath + ".invalid");
return true;
}
else {
++m_partialTorrents[torrentPath];
}
}
++value;
return false;
});
// Stop the partial timer if necessary
if (m_partialTorrents.empty()) {