Enable bugprone-narrowing-conversions clang-tidy check
authorKevin Ottens <kevin.ottens@nextcloud.com>
Tue, 18 Aug 2020 19:46:30 +0000 (21:46 +0200)
committerKevin Ottens (Rebase PR Action) <er-vin@users.noreply.github.com>
Tue, 1 Sep 2020 06:37:03 +0000 (06:37 +0000)
Signed-off-by: Kevin Ottens <kevin.ottens@nextcloud.com>
25 files changed:
.clang-tidy
src/3rdparty/QProgressIndicator/QProgressIndicator.cpp
src/3rdparty/kmessagewidget/kmessagewidget.cpp
src/3rdparty/qtokenizer/qtokenizer.h
src/common/ownsql.cpp
src/common/syncjournaldb.cpp
src/common/syncjournaldb.h
src/common/utility.cpp
src/common/utility.h
src/gui/creds/flow2auth.h
src/gui/folderwatcher_linux.cpp
src/gui/settingsdialog.cpp
src/gui/sharedialog.cpp
src/gui/sharee.cpp
src/gui/socketapi.cpp
src/gui/userinfo.cpp
src/gui/wizard/postfixlineedit.cpp
src/libsync/bandwidthmanager.cpp
src/libsync/clientsideencryption.cpp
src/libsync/progressdispatcher.cpp
src/libsync/propagateupload.cpp
src/libsync/propagateupload.h
src/libsync/syncengine.cpp
src/libsync/wordlist.cpp
test/syncenginetestutils.h

index d8b14cd391896f28768d63336cf491937be802c8..9aa0cb88c2fa3daa58ea59e657ccbce2a0ea6281 100644 (file)
@@ -3,6 +3,7 @@ Checks: '-*,
     bugprone-branch-clone,
     bugprone-forward-declaration-namespace,
     bugprone-macro-parentheses,
+    bugprone-narrowing-conversions,
     cppcoreguidelines-init-variables,
     misc-*,
     -misc-non-private-member-variables-in-classes,
index f32eb6e2ffe34876a2fade21eb4569886c3657b6..cfdce199f48ebeaee7afe7b5fc9827405708f683 100644 (file)
@@ -113,23 +113,23 @@ void QProgressIndicator::paintEvent(QPaintEvent * /*event*/)
     QPainter p(this);
     p.setRenderHint(QPainter::Antialiasing);
     
-    int outerRadius = (width-1)*0.5;
-    int innerRadius = (width-1)*0.5*0.38;
+    int outerRadius = qRound((width - 1) * 0.5);
+    int innerRadius = qRound((width - 1) * 0.5 * 0.38);
 
     int capsuleHeight = outerRadius - innerRadius;
-    int capsuleWidth  = (width > 32 ) ? capsuleHeight *.23 : capsuleHeight *.35;
+    int capsuleWidth  = qRound((width > 32 ) ? capsuleHeight * 0.23 : capsuleHeight * 0.35);
     int capsuleRadius = capsuleWidth/2;
 
     for (int i=0; i<12; i++)
     {
         QColor color = m_color;
-        color.setAlphaF(1.0f - (i/12.0f));
+        color.setAlphaF(1.0f - (static_cast<float>(i) / 12.0f));
         p.setPen(Qt::NoPen);
         p.setBrush(color);       
         p.save();
         p.translate(rect().center());
-        p.rotate(m_angle - i*30.0f);
-        p.drawRoundedRect(-capsuleWidth*0.5, -(innerRadius+capsuleHeight), capsuleWidth, capsuleHeight, capsuleRadius, capsuleRadius);
+        p.rotate(m_angle - i * 30);
+        p.drawRoundedRect(qRound(-capsuleWidth * 0.5), -(innerRadius + capsuleHeight), capsuleWidth, capsuleHeight, capsuleRadius, capsuleRadius);
         p.restore();
     }
 }
index d2d0f12b76dc60813d194f63f33da798fabcc5ad..595a5fa339532fc13ab4e21443a8fdb2bf4f797d 100644 (file)
@@ -197,9 +197,9 @@ void KMessageWidgetPrivate::applyStyleSheet()
     const QColor border = bgBaseColor;
 
     // Generate a final background color from overlaying bgBaseColor over windowColor
-    const int newRed = (bgBaseColor.red() * bgBaseColorAlpha) + (windowColor.red() * (1 - bgBaseColorAlpha));
-    const int newGreen = (bgBaseColor.green() * bgBaseColorAlpha) + (windowColor.green() * (1 - bgBaseColorAlpha));
-    const int newBlue = (bgBaseColor.blue() * bgBaseColorAlpha) + (windowColor.blue() * (1 - bgBaseColorAlpha));
+    const int newRed = qRound(bgBaseColor.red() * bgBaseColorAlpha) + qRound(windowColor.red() * (1 - bgBaseColorAlpha));
+    const int newGreen = qRound(bgBaseColor.green() * bgBaseColorAlpha) + qRound(windowColor.green() * (1 - bgBaseColorAlpha));
+    const int newBlue = qRound(bgBaseColor.blue() * bgBaseColorAlpha) + qRound(windowColor.blue() * (1 - bgBaseColorAlpha));
 
     const QColor bgFinalColor = QColor(newRed, newGreen, newBlue);
 
@@ -241,7 +241,7 @@ void KMessageWidgetPrivate::updateSnapShot()
 
 void KMessageWidgetPrivate::slotTimeLineChanged(qreal value)
 {
-    q->setFixedHeight(qMin(value * 2, qreal(1.0)) * content->height());
+    q->setFixedHeight(qMin(qRound(value * 2.0), 1) * content->height());
     q->update();
 }
 
index d8ca3d53f4ab1776a824de933d88c3b36bf88823..c317c42a918fed6b3b00d2a079709b9d273e4764 100644 (file)
@@ -220,7 +220,7 @@ public:
        Use \c hasNext() to fetch the next token.
      */
     T next() const {
-        int len = d->tokenEnd-d->tokenBegin;
+        int len = std::distance(d->tokenBegin, d->tokenEnd);
         const_iterator tmpStart = d->tokenBegin;
         if (!d->returnQuotes && len > 1 && d->isQuote(*d->tokenBegin)) {
             tmpStart++;
@@ -243,8 +243,9 @@ public:
      * @return A reference to the token within the string
      */
     QStringRef stringRef() {
-        int begin = d->tokenBegin-d->begin;
-        int end = d->tokenEnd-d->tokenBegin;
+        // If those differences overflow an int we'd have a veeeeeery long string in memory
+        int begin = std::distance(d->begin, d->tokenBegin);
+        int end = std::distance(d->tokenBegin, d->tokenEnd);
         if (!d->returnQuotes && d->isQuote(*d->tokenBegin)) {
             begin++;
             end -= 2;
index 04ec4106df468858c70fd953d795b1ae9959298b..b9a71dd3e18fbaa7bea1525e33aa7232f7ab9df3 100644 (file)
@@ -367,14 +367,14 @@ void SqlQuery::bindValue(int pos, const QVariant &value)
         const QDateTime dateTime = value.toDateTime();
         const QString str = dateTime.toString(QLatin1String("yyyy-MM-ddThh:mm:ss.zzz"));
         res = sqlite3_bind_text16(_stmt, pos, str.utf16(),
-            str.size() * sizeof(ushort), SQLITE_TRANSIENT);
+            str.size() * static_cast<int>(sizeof(ushort)), SQLITE_TRANSIENT);
         break;
     }
     case QVariant::Time: {
         const QTime time = value.toTime();
         const QString str = time.toString(QLatin1String("hh:mm:ss.zzz"));
         res = sqlite3_bind_text16(_stmt, pos, str.utf16(),
-            str.size() * sizeof(ushort), SQLITE_TRANSIENT);
+            str.size() * static_cast<int>(sizeof(ushort)), SQLITE_TRANSIENT);
         break;
     }
     case QVariant::String: {
@@ -382,7 +382,7 @@ void SqlQuery::bindValue(int pos, const QVariant &value)
             // lifetime of string == lifetime of its qvariant
             const auto *str = static_cast<const QString *>(value.constData());
             res = sqlite3_bind_text16(_stmt, pos, str->utf16(),
-                (str->size()) * sizeof(QChar), SQLITE_TRANSIENT);
+                (str->size()) * static_cast<int>(sizeof(QChar)), SQLITE_TRANSIENT);
         } else {
             res = sqlite3_bind_null(_stmt, pos);
         }
@@ -397,7 +397,7 @@ void SqlQuery::bindValue(int pos, const QVariant &value)
         QString str = value.toString();
         // SQLITE_TRANSIENT makes sure that sqlite buffers the data
         res = sqlite3_bind_text16(_stmt, pos, str.utf16(),
-            (str.size()) * sizeof(QChar), SQLITE_TRANSIENT);
+            (str.size()) * static_cast<int>(sizeof(QChar)), SQLITE_TRANSIENT);
         break;
     }
     }
index 01db818eda2a65d354b542b64f6419f49c811988..d13f855d5825b00db0a6ae5df522d7d1d02aee09 100644 (file)
@@ -1447,7 +1447,7 @@ SyncJournalDb::UploadInfo SyncJournalDb::getUploadInfo(const QString &file)
         if (_getUploadInfoQuery.next()) {
             bool ok = true;
             res._chunk = _getUploadInfoQuery.intValue(0);
-            res._transferid = _getUploadInfoQuery.intValue(1);
+            res._transferid = _getUploadInfoQuery.int64Value(1);
             res._errorCount = _getUploadInfoQuery.intValue(2);
             res._size = _getUploadInfoQuery.int64Value(3);
             res._modtime = _getUploadInfoQuery.int64Value(4);
index c6520cbd18a9d1b9254bbd076b654b60599bb58f..ef4feaf98342a182af1058d2ec88822d8cbf26f9 100644 (file)
@@ -94,7 +94,7 @@ public:
     struct UploadInfo
     {
         int _chunk = 0;
-        int _transferid = 0;
+        quint64 _transferid = 0;
         quint64 _size = 0; //currently unused
         qint64 _modtime = 0;
         int _errorCount = 0;
index 29b43cb5928ba2bf057901ad533408e5f80b6aa7..550c0b7b4c9e64124449abfbea575c5b90478b5c 100644 (file)
@@ -407,7 +407,7 @@ uint Utility::convertSizeToUint(size_t &convertVar)
     return static_cast<uint>(convertVar);
 }
 
-uint Utility::convertSizeToInt(size_t &convertVar)
+int Utility::convertSizeToInt(size_t &convertVar)
 {
     if (convertVar > INT_MAX) {
         //throw std::bad_cast();
index 6e973863135374a6549e88eb85e74f33cc97932c..fc83fd0a6a1b366bbc94bfc3f05379c519ca192d 100644 (file)
@@ -58,7 +58,7 @@ namespace Utility {
     OCSYNC_EXPORT bool hasLaunchOnStartup(const QString &appName);
     OCSYNC_EXPORT void setLaunchOnStartup(const QString &appName, const QString &guiName, bool launch);
     OCSYNC_EXPORT uint convertSizeToUint(size_t &convertVar);
-    OCSYNC_EXPORT uint convertSizeToInt(size_t &convertVar);
+    OCSYNC_EXPORT int convertSizeToInt(size_t &convertVar);
 
 #ifdef Q_OS_WIN
     OCSYNC_EXPORT DWORD convertSizeToDWORD(size_t &convertVar);
index e4deb203ef2ecbfc1a7e41b11201e6d9c177456c..c90dac5825890213363778dcddeeba14ec73ef13 100644 (file)
@@ -77,8 +77,8 @@ private:
     QString _pollToken;
     QString _pollEndpoint;
     QTimer _pollTimer;
-    int _secondsLeft;
-    int _secondsInterval;
+    qint64 _secondsLeft;
+    qint64 _secondsInterval;
     bool _isBusy;
     bool _hasToken;
 };
index 440927fbce16988ce18f2616393f95b9bf675b3c..9ab9ab8541c4bda5b59a911d3817cdb63d70de8b 100644 (file)
@@ -128,7 +128,7 @@ void FolderWatcherPrivate::slotReceivedNotification(int fd)
 {
     int len = 0;
     struct inotify_event *event = nullptr;
-    int i = 0;
+    size_t i = 0;
     int error = 0;
     QVarLengthArray<char, 2048> buffer(2048);
 
index f63533897d9ff6f4b595f8ac3aca8b111074874a..20b145a3cc17b2283f4f110ea10facb6defc76e9 100644 (file)
@@ -215,7 +215,7 @@ void SettingsDialog::accountAdded(AccountState *s)
 
     if (!brandingSingleAccount) {
         accountAction->setToolTip(s->account()->displayName());
-        accountAction->setIconText(SettingsDialogCommon::shortDisplayNameForSettings(s->account().data(),  height * buttonSizeRatio));
+        accountAction->setIconText(SettingsDialogCommon::shortDisplayNameForSettings(s->account().data(), qRound(height * buttonSizeRatio)));
     }
 
     _toolBar->insertAction(_actionBefore, accountAction);
@@ -259,7 +259,7 @@ void SettingsDialog::slotAccountDisplayNameChanged()
             QString displayName = account->displayName();
             action->setText(displayName);
             auto height = _toolBar->sizeHint().height();
-            action->setIconText(SettingsDialogCommon::shortDisplayNameForSettings(account, height * buttonSizeRatio));
+            action->setIconText(SettingsDialogCommon::shortDisplayNameForSettings(account, qRound(height * buttonSizeRatio)));
         }
     }
 }
index 240cc0a9e8cf4c5f345d8daa9867b6bf68aeac65..709766a808a6bc802db0bc98855e9179ad281e3b 100644 (file)
@@ -76,7 +76,7 @@ ShareDialog::ShareDialog(QPointer<AccountState> accountState,
     QString fileName = lPath.fileName();
     _ui->label_name->setText(tr("%1").arg(fileName));
     QFont f(_ui->label_name->font());
-    f.setPointSize(f.pointSize() * 1.4);
+    f.setPointSize(qRound(f.pointSize() * 1.4));
     _ui->label_name->setFont(f);
 
     QString ocDir(_sharePath);
index aab3d00bfc1025ffd2f0899d38cf6d24a287c57f..f7a525807025cf3e9fd022e5f1599dca554c4677 100644 (file)
@@ -205,7 +205,7 @@ void ShareeModel::setNewSharees(const QVector<QSharedPointer<Sharee>> &newSharee
         if (it == _sharees.constEnd()) {
             newPersistant << QModelIndex();
         } else {
-            newPersistant << index(it - _sharees.constBegin());
+            newPersistant << index(std::distance(_sharees.constBegin(), it));
         }
     }
 
index bba8e41c034963299b13c612f1d34dd418323d78..198e24bb1a931e38536168a2826eceaa159daf69 100644 (file)
@@ -105,16 +105,25 @@ public:
 
     void storeHash(uint hash)
     {
-        hashBits.setBit((hash & 0xFFFF) % NumBits);
-        hashBits.setBit((hash >> 16) % NumBits);
+        int bits = bit_cast(hash);
+        hashBits.setBit((bits & 0xFFFF) % NumBits);
+        hashBits.setBit((bits >> 16) % NumBits);
     }
     bool isHashMaybeStored(uint hash) const
     {
-        return hashBits.testBit((hash & 0xFFFF) % NumBits)
-            && hashBits.testBit((hash >> 16) % NumBits);
+        int bits = bit_cast(hash);
+        return hashBits.testBit((bits & 0xFFFF) % NumBits)
+            && hashBits.testBit((bits >> 16) % NumBits);
     }
 
 private:
+    static int bit_cast(uint input)
+    {
+        int output = 0;
+        std::memcpy(&output, &input, sizeof(int));
+        return output;
+    }
+
     QBitArray hashBits;
 };
 
index d26bcab9c6e2d1967c47b6548f17355e83ee5048..2962d3355f489f6243ae6525f786d14e890b773e 100644 (file)
@@ -57,7 +57,9 @@ void UserInfo::setActive(bool active)
 void UserInfo::slotAccountStateChanged()
 {
     if (canGetInfo()) {
-        auto elapsed = _lastInfoReceived.msecsTo(QDateTime::currentDateTime());
+        // Obviously assumes there will never be more than thousand of hours between last info
+        // received and now, hence why we static_cast
+        auto elapsed = static_cast<int>(_lastInfoReceived.msecsTo(QDateTime::currentDateTime()));
         if (_lastInfoReceived.isNull() || elapsed >= defaultIntervalT) {
             slotFetchInfo();
         } else {
index 1cc44a248b1eaf4457d8f9fdc0d7aa89fb8e2104..6e4c860ab531a1014451477edce85a660c930951 100644 (file)
@@ -32,7 +32,7 @@ void PostfixLineEdit::setPostfix(const QString &postfix)
     _postfix = postfix;
     QFontMetricsF fm(font());
     QMargins tm = textMargins();
-    tm.setRight(tm.right() + fm.width(_postfix) + verticalMargin);
+    tm.setRight(tm.right() + qRound(fm.width(_postfix)) + verticalMargin);
     setTextMargins(tm);
 }
 
@@ -63,7 +63,7 @@ void PostfixLineEdit::paintEvent(QPaintEvent *pe)
     //
     p.setPen(palette().color(QPalette::Disabled, QPalette::Text));
     QFontMetricsF fm(font());
-    int start = rect().right() - fm.width(_postfix);
+    int start = rect().right() - qRound(fm.width(_postfix));
     QStyleOptionFrame panel;
     initStyleOption(&panel);
     QRect r = style()->subElementRect(QStyle::SE_LineEditContents, &panel, this);
index 79b19057f0eee3dcccd12713e60c9fef41a5b98e..4455514f87c5d8cf070b338cc049cc31cc1062b2 100644 (file)
@@ -169,7 +169,7 @@ void BandwidthManager::relativeUploadMeasuringTimerExpired()
     qCDebug(lcBandwidthManager) << _relativeUploadLimitProgressAtMeasuringRestart
                                 << relativeLimitProgressMeasured << relativeLimitProgressDifference;
 
-    qint64 speedkBPerSec = (relativeLimitProgressDifference / relativeLimitMeasuringTimerIntervalMsec * 1000.0) / 1024.0;
+    qint64 speedkBPerSec = (relativeLimitProgressDifference / relativeLimitMeasuringTimerIntervalMsec * 1000) / 1024;
     qCDebug(lcBandwidthManager) << relativeLimitProgressDifference / 1024 << "kB =>" << speedkBPerSec << "kB/sec on full speed ("
                                 << _relativeLimitCurrentMeasuredDevice->_readWithProgress << _relativeLimitCurrentMeasuredDevice->_read
                                 << qAbs(_relativeLimitCurrentMeasuredDevice->_readWithProgress
@@ -262,7 +262,7 @@ void BandwidthManager::relativeDownloadMeasuringTimerExpired()
     qCDebug(lcBandwidthManager) << _relativeDownloadLimitProgressAtMeasuringRestart
                                 << relativeLimitProgressMeasured << relativeLimitProgressDifference;
 
-    qint64 speedkBPerSec = (relativeLimitProgressDifference / relativeLimitMeasuringTimerIntervalMsec * 1000.0) / 1024.0;
+    qint64 speedkBPerSec = (relativeLimitProgressDifference / relativeLimitMeasuringTimerIntervalMsec * 1000) / 1024;
     qCDebug(lcBandwidthManager) << relativeLimitProgressDifference / 1024 << "kB =>" << speedkBPerSec << "kB/sec on full speed ("
                                 << _relativeLimitCurrentMeasuredJob->currentDownloadPosition();
 
@@ -287,7 +287,7 @@ void BandwidthManager::relativeDownloadMeasuringTimerExpired()
         qCInfo(lcBandwidthManager) << "ADJUSTING QUOTA FROM " << quota << " TO " << quota - 20 * 1024;
         quota -= 20 * 1024;
     }
-    qint64 quotaPerJob = quota / jobCount + 1.0;
+    qint64 quotaPerJob = quota / jobCount + 1;
     Q_FOREACH (GETFileJob *gfj, _downloadJobList) {
         gfj->setBandwidthLimited(true);
         gfj->setChoked(false);
index 2bcbffcca8c4411dd6996244b0736745016bea23..7d6c0ef4503dd7df84fa21015b9681c9e790377f 100644 (file)
@@ -1661,7 +1661,7 @@ bool EncryptionHelper::fileDecryption(const QByteArray &key, const QByteArray& i
 
     while(input->pos() < size) {
 
-        int toRead = size - input->pos();
+        auto toRead = size - input->pos();
         if (toRead > 1024) {
             toRead = 1024;
         }
index 4b571609fa28033226f45496694948bb0abc3bd4..1352801732e8aada5ba94688a071ff7a673f1e64 100644 (file)
@@ -362,7 +362,7 @@ ProgressInfo::Estimates ProgressInfo::Progress::estimates() const
     Estimates est;
     est.estimatedBandwidth = _progressPerSec;
     if (_progressPerSec != 0) {
-        est.estimatedEta = (_total - _completed) / _progressPerSec * 1000.0;
+        est.estimatedEta = qRound64(static_cast<double>(_total - _completed) / _progressPerSec) * 1000;
     } else {
         est.estimatedEta = 0; // looks better than quint64 max
     }
@@ -391,7 +391,7 @@ void ProgressInfo::Progress::update()
     // Therefore, smoothing starts at 0 and ramps up to its final value over time.
     const double smoothing = 0.9 * (1.0 - _initialSmoothing);
     _initialSmoothing *= 0.7; // goes from 1 to 0.03 in 10s
-    _progressPerSec = smoothing * _progressPerSec + (1.0 - smoothing) * (_completed - _prevCompleted);
+    _progressPerSec = smoothing * _progressPerSec + (1.0 - smoothing) * static_cast<double>(_completed - _prevCompleted);
     _prevCompleted = _completed;
 }
 
index 633d897d7e75080f7eecd8a27c0f3142542f7d28..035bd945fe189f5ff6dd4b80310bbdc46ff89954 100644 (file)
@@ -676,12 +676,14 @@ void PropagateUploadFileCommon::commonErrorHandling(AbstractNetworkJob *job)
 
 void PropagateUploadFileCommon::adjustLastJobTimeout(AbstractNetworkJob *job, quint64 fileSize)
 {
+    constexpr double threeMinutes = 3.0 * 60 * 1000;
+
     job->setTimeout(qBound(
         job->timeoutMsec(),
         // Calculate 3 minutes for each gigabyte of data
-        qint64((3 * 60 * 1000) * fileSize / 1e9),
+        qRound64(threeMinutes * fileSize / 1e9),
         // Maximum of 30 minutes
-        qint64(30 * 60 * 1000)));
+        static_cast<qint64>(30 * 60 * 1000)));
 }
 
 void PropagateUploadFileCommon::slotJobDestroyed(QObject *job)
index 87291e1854cc6a3d93069100ae0887aa2430bff2..591477f1eafafe14a4f791d56c93d8c7be8dc126 100644 (file)
@@ -334,7 +334,7 @@ private:
      */
     int _currentChunk = 0;
     int _chunkCount = 0; /// Total number of chunks for this file
-    int _transferId = 0; /// transfer id (part of the url)
+    quint64 _transferId = 0; /// transfer id (part of the url)
 
     quint64 chunkSize() const {
         // Old chunking does not use dynamic chunking algorithm, and does not adjusts the chunk size respectively,
index d479c15b6953380723cebee08125ac094a56622d..6ff093ff4c1c6716df1eeed132942afdedd940c0 100644 (file)
@@ -228,7 +228,7 @@ bool SyncEngine::checkErrorBlacklisting(SyncFileItem &item)
         }
     }
 
-    int waitSeconds = entry._lastTryTime + entry._ignoreDuration - now;
+    qint64 waitSeconds = entry._lastTryTime + entry._ignoreDuration - now;
     qCInfo(lcEngine) << "Item is on blacklist: " << entry._file
                      << "retries:" << entry._retryCount
                      << "for another" << waitSeconds << "s";
index 01b7b53280047ab5431c0f54f25f9092433c8168..ee71cd7deb352dc1be1a12f954dca48395d777c1 100644 (file)
@@ -18,7 +18,7 @@ int getRandomNumber(int max) {
         num += c;
     }
 
-    return num % max;
+    return static_cast<int>(num % max);
 }
 
 QStringList getRandomWords(int nr)
index 73bae5bbdf0a8ae977b5be6d1f105a9d5190f7cd..40dab44874e34f94d7b48fba3aac7607ce7be33d 100644 (file)
@@ -633,7 +633,7 @@ public:
         QString source = getFilePathFromUrl(request.url());
         Q_ASSERT(!source.isEmpty());
         Q_ASSERT(source.endsWith("/.file"));
-        source = source.left(source.length() - qstrlen("/.file"));
+        source = source.left(source.length() - static_cast<int>(qstrlen("/.file")));
         auto sourceFolder = uploadsFileInfo.find(source);
         Q_ASSERT(sourceFolder);
         Q_ASSERT(sourceFolder->isDir);