Network examples: cleanup foreach usage

Replace deprecated foreach macro with range-based for loop

Change-Id: I0d1f2cfd557d02ccc48b41b3fea137baa2962fc1
Reviewed-by: André Hartmann <aha_1980@gmx.de>
Reviewed-by: Timur Pocheptsov <timur.pocheptsov@qt.io>
This commit is contained in:
Christian Ehrlicher 2018-12-31 17:41:11 +01:00
parent 0c54e0251f
commit 7984327c40
13 changed files with 69 additions and 56 deletions

View File

@ -142,7 +142,8 @@ void BearerMonitor::configurationAdded(const QNetworkConfiguration &config, QTre
treeWidget->addTopLevelItem(item);
if (config.type() == QNetworkConfiguration::ServiceNetwork) {
foreach (const QNetworkConfiguration &child, config.children())
const QList<QNetworkConfiguration> children = config.children();
for (const QNetworkConfiguration &child : children)
configurationAdded(child, item);
}
}
@ -181,7 +182,8 @@ void BearerMonitor::configurationChanged(const QNetworkConfiguration &config)
void BearerMonitor::updateSnapConfiguration(QTreeWidgetItem *parent, const QNetworkConfiguration &snap)
{
QMap<QString, QTreeWidgetItem *> itemMap;
foreach (QTreeWidgetItem *item, parent->takeChildren())
const QList<QTreeWidgetItem *> children = parent->takeChildren();
for (QTreeWidgetItem *item : children)
itemMap.insert(item->data(0, Qt::UserRole).toString(), item);
QList<QNetworkConfiguration> allConfigurations = snap.children();

View File

@ -172,35 +172,43 @@ void DnsManager::showResults()
printf("Error: %i (%s)\n", dns->error(), qPrintable(dns->errorString()));
// CNAME records
foreach (const QDnsDomainNameRecord &record, dns->canonicalNameRecords())
const QList<QDnsDomainNameRecord> cnameRecords = dns->canonicalNameRecords();
for (const QDnsDomainNameRecord &record : cnameRecords)
printf("%s\t%i\tIN\tCNAME\t%s\n", qPrintable(record.name()), record.timeToLive(), qPrintable(record.value()));
// A and AAAA records
foreach (const QDnsHostAddressRecord &record, dns->hostAddressRecords()) {
const QList<QDnsHostAddressRecord> aRecords = dns->hostAddressRecords();
for (const QDnsHostAddressRecord &record : aRecords) {
const char *type = (record.value().protocol() == QAbstractSocket::IPv6Protocol) ? "AAAA" : "A";
printf("%s\t%i\tIN\t%s\t%s\n", qPrintable(record.name()), record.timeToLive(), type, qPrintable(record.value().toString()));
}
// MX records
foreach (const QDnsMailExchangeRecord &record, dns->mailExchangeRecords())
const QList<QDnsMailExchangeRecord> mxRecords = dns->mailExchangeRecords();
for (const QDnsMailExchangeRecord &record : mxRecords)
printf("%s\t%i\tIN\tMX\t%u %s\n", qPrintable(record.name()), record.timeToLive(), record.preference(), qPrintable(record.exchange()));
// NS records
foreach (const QDnsDomainNameRecord &record, dns->nameServerRecords())
const QList<QDnsDomainNameRecord> nsRecords = dns->nameServerRecords();
for (const QDnsDomainNameRecord &record : nsRecords)
printf("%s\t%i\tIN\tNS\t%s\n", qPrintable(record.name()), record.timeToLive(), qPrintable(record.value()));
// PTR records
foreach (const QDnsDomainNameRecord &record, dns->pointerRecords())
const QList<QDnsDomainNameRecord> ptrRecords = dns->pointerRecords();
for (const QDnsDomainNameRecord &record : ptrRecords)
printf("%s\t%i\tIN\tPTR\t%s\n", qPrintable(record.name()), record.timeToLive(), qPrintable(record.value()));
// SRV records
foreach (const QDnsServiceRecord &record, dns->serviceRecords())
const QList<QDnsServiceRecord> srvRecords = dns->serviceRecords();
for (const QDnsServiceRecord &record : srvRecords)
printf("%s\t%i\tIN\tSRV\t%u %u %u %s\n", qPrintable(record.name()), record.timeToLive(), record.priority(), record.weight(), record.port(), qPrintable(record.target()));
// TXT records
foreach (const QDnsTextRecord &record, dns->textRecords()) {
const QList<QDnsTextRecord> txtRecords = dns->textRecords();
for (const QDnsTextRecord &record : txtRecords) {
QStringList values;
foreach (const QByteArray &ba, record.values())
const QList<QByteArray> dnsRecords = record.values();
for (const QByteArray &ba : dnsRecords)
values << "\"" + QString::fromLatin1(ba) + "\"";
printf("%s\t%i\tIN\tTXT\t%s\n", qPrintable(record.name()), record.timeToLive(), qPrintable(values.join(' ')));
}

View File

@ -319,7 +319,7 @@ void HttpWindow::slotAuthenticationRequired(QNetworkReply *, QAuthenticator *aut
void HttpWindow::sslErrors(QNetworkReply *, const QList<QSslError> &errors)
{
QString errorString;
foreach (const QSslError &error, errors) {
for (const QSslError &error : errors) {
if (!errorString.isEmpty())
errorString += '\n';
errorString += error.errorString();

View File

@ -71,8 +71,7 @@ void Client::sendMessage(const QString &message)
if (message.isEmpty())
return;
QList<Connection *> connections = peers.values();
foreach (Connection *connection, connections)
for (Connection *connection : qAsConst(peers))
connection->sendMessage(message);
}
@ -90,8 +89,8 @@ bool Client::hasConnection(const QHostAddress &senderIp, int senderPort) const
if (!peers.contains(senderIp))
return false;
QList<Connection *> connections = peers.values(senderIp);
foreach (Connection *connection, connections) {
const QList<Connection *> connections = peers.values(senderIp);
for (const Connection *connection : connections) {
if (connection->peerPort() == senderPort)
return true;
}

View File

@ -104,9 +104,9 @@ void PeerManager::startBroadcasting()
broadcastTimer.start();
}
bool PeerManager::isLocalHostAddress(const QHostAddress &address)
bool PeerManager::isLocalHostAddress(const QHostAddress &address) const
{
foreach (QHostAddress localAddress, ipAddresses) {
for (const QHostAddress &localAddress : ipAddresses) {
if (address.isEqual(localAddress))
return true;
}
@ -125,7 +125,7 @@ void PeerManager::sendBroadcastDatagram()
}
bool validBroadcastAddresses = true;
foreach (QHostAddress address, broadcastAddresses) {
for (const QHostAddress &address : qAsConst(broadcastAddresses)) {
if (broadcastSocket.writeDatagram(datagram, address,
broadcastPort) == -1)
validBroadcastAddresses = false;
@ -182,8 +182,10 @@ void PeerManager::updateAddresses()
{
broadcastAddresses.clear();
ipAddresses.clear();
foreach (QNetworkInterface interface, QNetworkInterface::allInterfaces()) {
foreach (QNetworkAddressEntry entry, interface.addressEntries()) {
const QList<QNetworkInterface> interfaces = QNetworkInterface::allInterfaces();
for (const QNetworkInterface &interface : interfaces) {
const QList<QNetworkAddressEntry> entries = interface.addressEntries();
for (const QNetworkAddressEntry &entry : entries) {
QHostAddress broadcastAddress = entry.broadcast();
if (broadcastAddress != QHostAddress::Null && entry.ip() != QHostAddress::LocalHost) {
broadcastAddresses << broadcastAddress;

View File

@ -70,7 +70,7 @@ public:
void setServerPort(int port);
QString userName() const;
void startBroadcasting();
bool isLocalHostAddress(const QHostAddress &address);
bool isLocalHostAddress(const QHostAddress &address) const;
signals:
void newConnection(Connection *connection);

View File

@ -148,7 +148,8 @@ void AddTorrentDialog::setTorrent(const QString &torrentFile)
ui.torrentContents->setHtml(metaInfo.singleFile().name);
} else {
QString html;
foreach (MetaInfoMultiFile file, metaInfo.multiFiles()) {
const QList<MetaInfoMultiFile> multiFiles = metaInfo.multiFiles();
for (const MetaInfoMultiFile &file : multiFiles) {
QString name = metaInfo.name();
if (!name.isEmpty()) {
html += name;

View File

@ -77,7 +77,7 @@ FileManager::~FileManager()
cond.wakeOne();
wait();
foreach (QFile *file, files) {
for (QFile *file : qAsConst(files)) {
file->close();
delete file;
}
@ -285,7 +285,8 @@ bool FileManager::generateFiles()
return false;
}
foreach (const MetaInfoMultiFile &entry, metaInfo.multiFiles()) {
const QList<MetaInfoMultiFile> multiFiles = metaInfo.multiFiles();
for (const MetaInfoMultiFile &entry : multiFiles) {
QString filePath = QFileInfo(prefix + entry.path).path();
if (!QFile::exists(filePath)) {
if (!dir.mkpath(filePath)) {
@ -437,7 +438,7 @@ void FileManager::verifyFileContents()
}
// Verify all pending pieces
foreach (int index, newPendingVerificationRequests)
for (int index : qAsConst(newPendingVerificationRequests))
emit pieceVerified(index, verifySinglePiece(index));
}

View File

@ -239,7 +239,7 @@ int MainWindow::rowOfClient(TorrentClient *client) const
// Return the row that displays this client's status, or -1 if the
// client is not known.
int row = 0;
foreach (Job job, jobs) {
for (const Job &job : jobs) {
if (job.client == client)
return row;
++row;
@ -358,7 +358,7 @@ bool MainWindow::addTorrent(const QString &fileName, const QString &destinationF
const QByteArray &resumeState)
{
// Check if the torrent is already being downloaded.
foreach (Job job, jobs) {
for (const Job &job : qAsConst(jobs)) {
if (job.torrentFileName == fileName && job.destinationDirectory == destinationFolder) {
QMessageBox::warning(this, tr("Already downloading"),
tr("The torrent file %1 is "
@ -684,7 +684,7 @@ void MainWindow::closeEvent(QCloseEvent *)
// them to signal that they have stopped.
jobsToStop = 0;
jobsStopped = 0;
foreach (Job job, jobs) {
for (const Job &job : qAsConst(jobs)) {
++jobsToStop;
TorrentClient *client = job.client;
client->disconnect();

View File

@ -101,10 +101,10 @@ bool MetaInfo::parse(const QByteArray &data)
QList<QVariant> files = info.value("files").toList();
for (int i = 0; i < files.size(); ++i) {
QMap<QByteArray, QVariant> file = qvariant_cast<Dictionary>(files.at(i));
QList<QVariant> pathElements = file.value("path").toList();
const QMap<QByteArray, QVariant> file = qvariant_cast<Dictionary>(files.at(i));
const QList<QVariant> pathElements = file.value("path").toList();
QByteArray path;
foreach (QVariant p, pathElements) {
for (const QVariant &p : pathElements) {
if (!path.isEmpty())
path += '/';
path += p.toByteArray();
@ -221,7 +221,7 @@ qint64 MetaInfo::totalSize() const
return singleFile().length;
qint64 size = 0;
foreach (MetaInfoMultiFile file, multiFiles())
for (const MetaInfoMultiFile &file : metaInfoMultiFiles)
size += file.length;
return size;
}

View File

@ -78,7 +78,7 @@ void RateController::removeSocket(PeerWireClient *socket)
void RateController::setDownloadLimit(int bytesPerSecond)
{
downLimit = bytesPerSecond;
foreach (PeerWireClient *socket, sockets)
for (PeerWireClient *socket : qAsConst(sockets))
socket->setReadBufferSize(downLimit * 4);
}
@ -108,7 +108,7 @@ void RateController::transfer()
}
QSet<PeerWireClient *> pendingSockets;
foreach (PeerWireClient *client, sockets) {
for (PeerWireClient *client : qAsConst(sockets)) {
if (client->canTransferMore())
pendingSockets << client;
}

View File

@ -383,7 +383,7 @@ qint64 TorrentClient::uploadedBytes() const
int TorrentClient::connectedPeerCount() const
{
int tmp = 0;
foreach (PeerWireClient *client, d->connections) {
for (PeerWireClient *client : d->connections) {
if (client->state() == QAbstractSocket::ConnectedState)
++tmp;
}
@ -393,7 +393,7 @@ int TorrentClient::connectedPeerCount() const
int TorrentClient::seedCount() const
{
int tmp = 0;
foreach (PeerWireClient *client, d->connections) {
for (PeerWireClient *client : d->connections) {
if (client->availablePieces().count(true) == d->pieceCount)
++tmp;
}
@ -464,7 +464,7 @@ void TorrentClient::stop()
}
// Abort all existing connections
foreach (PeerWireClient *client, d->connections) {
for (PeerWireClient *client : qAsConst(d->connections)) {
RateController::instance()->removeSocket(client);
ConnectionManager::instance()->removeConnection(client);
client->abort();
@ -487,7 +487,7 @@ void TorrentClient::setPaused(bool paused)
// connections to 0. Keep the list of peers, so we can quickly
// resume later.
d->setState(Paused);
foreach (PeerWireClient *client, d->connections)
for (PeerWireClient *client : qAsConst(d->connections))
client->abort();
d->connections.clear();
TorrentServer::instance()->removeClient(this);
@ -622,7 +622,7 @@ void TorrentClient::pieceVerified(int pieceIndex, bool ok)
}
// Update the peer list so we know who's still interesting.
foreach (TorrentPeer *peer, d->peers) {
for (TorrentPeer *peer : qAsConst(d->peers)) {
if (!peer->interesting)
continue;
bool interesting = false;
@ -642,7 +642,7 @@ void TorrentClient::pieceVerified(int pieceIndex, bool ok)
d->incompletePieces.clearBit(pieceIndex);
// Notify connected peers.
foreach (PeerWireClient *client, d->connections) {
for (PeerWireClient *client : qAsConst(d->connections)) {
if (client->state() == QAbstractSocket::ConnectedState
&& !client->availablePieces().testBit(pieceIndex)) {
client->sendPieceNotification(pieceIndex);
@ -720,9 +720,9 @@ QList<TorrentPeer *> TorrentClient::weighedFreePeers() const
qint64 now = QDateTime::currentSecsSinceEpoch();
QList<TorrentPeer *> freePeers;
QMap<QString, int> connectionsPerPeer;
foreach (TorrentPeer *peer, d->peers) {
for (TorrentPeer *peer : d->peers) {
bool busy = false;
foreach (PeerWireClient *client, d->connections) {
for (PeerWireClient *client : d->connections) {
if (client->state() == PeerWireClient::ConnectedState
&& client->peerAddress() == peer->address
&& client->peerPort() == peer->port) {
@ -742,7 +742,7 @@ QList<TorrentPeer *> TorrentClient::weighedFreePeers() const
// Assign points based on connection speed and pieces available.
QList<QPair<int, TorrentPeer *> > points;
foreach (TorrentPeer *peer, freePeers) {
for (TorrentPeer *peer : qAsConst(freePeers)) {
int tmp = 0;
if (peer->interesting) {
tmp += peer->numCompletedPieces;
@ -765,7 +765,7 @@ QList<TorrentPeer *> TorrentClient::weighedFreePeers() const
QMultiMap<int, TorrentPeer *> pointMap;
int lowestScore = 0;
int lastIndex = 0;
foreach (PointPair point, points) {
for (const PointPair &point : qAsConst(points)) {
if (point.first > lowestScore) {
lowestScore = point.first;
++lastIndex;
@ -816,7 +816,7 @@ void TorrentClient::setupOutgoingConnection()
PeerWireClient *client = qobject_cast<PeerWireClient *>(sender());
// Update connection statistics.
foreach (TorrentPeer *peer, d->peers) {
for (TorrentPeer *peer : qAsConst(d->peers)) {
if (peer->port == client->peerPort() && peer->address == client->peerAddress()) {
peer->connectTime = peer->lastVisited - peer->connectStart;
break;
@ -1085,7 +1085,7 @@ void TorrentClient::scheduleUploads()
// no use in unchoking them.
QList<PeerWireClient *> allClients = d->connections;
QMultiMap<int, PeerWireClient *> transferSpeeds;
foreach (PeerWireClient *client, allClients) {
for (PeerWireClient *client : qAsConst(allClients)) {
if (client->state() == QAbstractSocket::ConnectedState
&& client->availablePieces().count(true) != d->pieceCount) {
if (d->state == Seeding) {
@ -1143,7 +1143,7 @@ void TorrentClient::scheduleDownloads()
// Check what each client is doing, and assign payloads to those
// who are either idle or done.
foreach (PeerWireClient *client, d->connections)
for (PeerWireClient *client : qAsConst(d->connections))
schedulePieceForClient(client);
}
@ -1222,7 +1222,7 @@ void TorrentClient::schedulePieceForClient(PeerWireClient *client)
incompletePiecesAvailableToClient &= client->availablePieces();
// Remove all pieces that this client has already requested.
foreach (int i, currentPieces)
for (int i : qAsConst(currentPieces))
incompletePiecesAvailableToClient.clearBit(i);
// Only continue if more pieces can be scheduled. If no pieces
@ -1258,7 +1258,7 @@ void TorrentClient::schedulePieceForClient(PeerWireClient *client)
memset(occurrences, 0, d->pieceCount * sizeof(int));
// Count how many of each piece are available.
foreach (PeerWireClient *peer, d->connections) {
for (PeerWireClient *peer : qAsConst(d->connections)) {
QBitArray peerPieces = peer->availablePieces();
int peerPiecesSize = peerPieces.size();
for (int i = 0; i < peerPiecesSize; ++i) {
@ -1356,7 +1356,7 @@ void TorrentClient::requestMore(PeerWireClient *client)
// Starting with the first piece that we're waiting for, request
// blocks until the quota is filled up.
foreach (TorrentPiece *piece, piecesInProgress) {
for (TorrentPiece *piece : qAsConst(piecesInProgress)) {
numBlocksInProgress += requestBlocks(client, piece, maxInProgress - numBlocksInProgress);
if (numBlocksInProgress == maxInProgress)
break;
@ -1450,8 +1450,8 @@ void TorrentClient::peerUnchoked()
void TorrentClient::addToPeerList(const QList<TorrentPeer> &peerList)
{
// Add peers we don't already know of to our list of peers.
QList<QHostAddress> addresses = QNetworkInterface::allAddresses();
foreach (TorrentPeer peer, peerList) {
const QList<QHostAddress> addresses = QNetworkInterface::allAddresses();
for (const TorrentPeer &peer : peerList) {
if (addresses.contains(peer.address)
&& peer.port == TorrentServer::instance()->serverPort()) {
// Skip our own server.
@ -1459,7 +1459,7 @@ void TorrentClient::addToPeerList(const QList<TorrentPeer> &peerList)
}
bool known = false;
foreach (TorrentPeer *knownPeer, d->peers) {
for (const TorrentPeer *knownPeer : qAsConst(d->peers)) {
if (knownPeer->port == peer.port
&& knownPeer->address == peer.address) {
known = true;
@ -1486,8 +1486,8 @@ void TorrentClient::addToPeerList(const QList<TorrentPeer> &peerList)
if (d->peers.size() > maxPeers) {
// Find what peers are currently connected & active
QSet<TorrentPeer *> activePeers;
foreach (TorrentPeer *peer, d->peers) {
foreach (PeerWireClient *client, d->connections) {
for (TorrentPeer *peer : qAsConst(d->peers)) {
for (const PeerWireClient *client : qAsConst(d->connections)) {
if (client->peer() == peer && (client->downloadSpeed() + client->uploadSpeed()) > 1024)
activePeers << peer;
}

View File

@ -102,7 +102,7 @@ void TorrentServer::removeClient()
void TorrentServer::processInfoHash(const QByteArray &infoHash)
{
PeerWireClient *peer = qobject_cast<PeerWireClient *>(sender());
foreach (TorrentClient *client, clients) {
for (TorrentClient *client : qAsConst(clients)) {
if (client->state() >= TorrentClient::Searching && client->infoHash() == infoHash) {
peer->disconnect(peer, 0, this, 0);
client->setupIncomingConnection(peer);