Bläddra i källkod

Enable bugprone-narrowing-conversions clang-tidy check

Signed-off-by: Kevin Ottens <kevin.ottens@nextcloud.com>
Kevin Ottens 5 år sedan
förälder
incheckning
80cc196f6f

+ 1 - 0
.clang-tidy

@@ -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,

+ 6 - 6
src/3rdparty/QProgressIndicator/QProgressIndicator.cpp

@@ -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();
     }
 }

+ 4 - 4
src/3rdparty/kmessagewidget/kmessagewidget.cpp

@@ -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();
 }
 

+ 4 - 3
src/3rdparty/qtokenizer/qtokenizer.h

@@ -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;

+ 4 - 4
src/common/ownsql.cpp

@@ -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;
     }
     }

+ 1 - 1
src/common/syncjournaldb.cpp

@@ -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);

+ 1 - 1
src/common/syncjournaldb.h

@@ -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;

+ 1 - 1
src/common/utility.cpp

@@ -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();

+ 1 - 1
src/common/utility.h

@@ -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);

+ 2 - 2
src/gui/creds/flow2auth.h

@@ -77,8 +77,8 @@ private:
     QString _pollToken;
     QString _pollEndpoint;
     QTimer _pollTimer;
-    int _secondsLeft;
-    int _secondsInterval;
+    qint64 _secondsLeft;
+    qint64 _secondsInterval;
     bool _isBusy;
     bool _hasToken;
 };

+ 1 - 1
src/gui/folderwatcher_linux.cpp

@@ -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);
 

+ 2 - 2
src/gui/settingsdialog.cpp

@@ -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)));
         }
     }
 }

+ 1 - 1
src/gui/sharedialog.cpp

@@ -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);

+ 1 - 1
src/gui/sharee.cpp

@@ -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));
         }
     }
 

+ 13 - 4
src/gui/socketapi.cpp

@@ -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;
 };
 

+ 3 - 1
src/gui/userinfo.cpp

@@ -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 {

+ 2 - 2
src/gui/wizard/postfixlineedit.cpp

@@ -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);

+ 3 - 3
src/libsync/bandwidthmanager.cpp

@@ -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);

+ 1 - 1
src/libsync/clientsideencryption.cpp

@@ -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;
         }

+ 2 - 2
src/libsync/progressdispatcher.cpp

@@ -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;
 }
 

+ 4 - 2
src/libsync/propagateupload.cpp

@@ -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)

+ 1 - 1
src/libsync/propagateupload.h

@@ -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,

+ 1 - 1
src/libsync/syncengine.cpp

@@ -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";

+ 1 - 1
src/libsync/wordlist.cpp

@@ -18,7 +18,7 @@ int getRandomNumber(int max) {
         num += c;
     }
 
-    return num % max;
+    return static_cast<int>(num % max);
 }
 
 QStringList getRandomWords(int nr)

+ 1 - 1
test/syncenginetestutils.h

@@ -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);