CoreLib: use const (and const APIs) more

For CoW types const methods will be called.

Mark store_persistent_indexes() as const,
because this method does not modify the object.

Change-Id: Ic867913b4fb5aaebfbaaffe1d3be45cf7b646403
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
This commit is contained in:
Anton Kudryavtsev 2016-04-13 14:45:11 +03:00
parent 777d46b403
commit f083830b8d
20 changed files with 44 additions and 40 deletions

View File

@ -149,7 +149,7 @@ static QCFType<CFPropertyListRef> macValue(const QVariant &value)
bool singleton = (values.count() == 1); bool singleton = (values.count() == 1);
if (singleton) { if (singleton) {
switch (values.first().type()) { switch (values.constFirst().type()) {
// should be same as above (look for LIST) // should be same as above (look for LIST)
case QVariant::List: case QVariant::List:
case QVariant::StringList: case QVariant::StringList:
@ -161,7 +161,7 @@ static QCFType<CFPropertyListRef> macValue(const QVariant &value)
} }
cfkeys[numUniqueKeys] = QCFString::toCFStringRef(key); cfkeys[numUniqueKeys] = QCFString::toCFStringRef(key);
cfvalues[numUniqueKeys] = singleton ? macValue(values.first()) : macList(values); cfvalues[numUniqueKeys] = singleton ? macValue(values.constFirst()) : macList(values);
++numUniqueKeys; ++numUniqueKeys;
} }

View File

@ -273,7 +273,7 @@ QString QStandardPaths::displayName(StandardLocation type)
return QCoreApplication::translate("QStandardPaths", "Applications"); return QCoreApplication::translate("QStandardPaths", "Applications");
if (QCFType<CFURLRef> url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, if (QCFType<CFURLRef> url = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
standardLocations(type).first().toCFString(), standardLocations(type).constFirst().toCFString(),
kCFURLPOSIXPathStyle, true)) { kCFURLPOSIXPathStyle, true)) {
QCFString name; QCFString name;
CFURLCopyResourcePropertyForKey(url, kCFURLLocalizedNameKey, &name, NULL); CFURLCopyResourcePropertyForKey(url, kCFURLLocalizedNameKey, &name, NULL);

View File

@ -58,8 +58,8 @@ QPersistentModelIndexData *QPersistentModelIndexData::create(const QModelIndex &
QPersistentModelIndexData *d = 0; QPersistentModelIndexData *d = 0;
QAbstractItemModel *model = const_cast<QAbstractItemModel *>(index.model()); QAbstractItemModel *model = const_cast<QAbstractItemModel *>(index.model());
QHash<QModelIndex, QPersistentModelIndexData *> &indexes = model->d_func()->persistent.indexes; QHash<QModelIndex, QPersistentModelIndexData *> &indexes = model->d_func()->persistent.indexes;
const QHash<QModelIndex, QPersistentModelIndexData *>::iterator it = indexes.find(index); const auto it = indexes.constFind(index);
if (it != indexes.end()) { if (it != indexes.cend()) {
d = (*it); d = (*it);
} else { } else {
d = new QPersistentModelIndexData(index); d = new QPersistentModelIndexData(index);
@ -603,13 +603,13 @@ void QAbstractItemModelPrivate::removePersistentIndexData(QPersistentModelIndexD
} }
// make sure our optimization still works // make sure our optimization still works
for (int i = persistent.moved.count() - 1; i >= 0; --i) { for (int i = persistent.moved.count() - 1; i >= 0; --i) {
int idx = persistent.moved[i].indexOf(data); int idx = persistent.moved.at(i).indexOf(data);
if (idx >= 0) if (idx >= 0)
persistent.moved[i].remove(idx); persistent.moved[i].remove(idx);
} }
// update the references to invalidated persistent indexes // update the references to invalidated persistent indexes
for (int i = persistent.invalidated.count() - 1; i >= 0; --i) { for (int i = persistent.invalidated.count() - 1; i >= 0; --i) {
int idx = persistent.invalidated[i].indexOf(data); int idx = persistent.invalidated.at(i).indexOf(data);
if (idx >= 0) if (idx >= 0)
persistent.invalidated[i].remove(idx); persistent.invalidated[i].remove(idx);
} }
@ -2544,13 +2544,13 @@ bool QAbstractItemModel::decodeData(int row, int column, const QModelIndex &pare
for (int i = 0; i < rows.count(); ++i) for (int i = 0; i < rows.count(); ++i)
rowsToInsert[rows.at(i)] = 1; rowsToInsert[rows.at(i)] = 1;
for (int i = 0; i < rowsToInsert.count(); ++i) { for (int i = 0; i < rowsToInsert.count(); ++i) {
if (rowsToInsert[i] == 1){ if (rowsToInsert.at(i) == 1){
rowsToInsert[i] = dragRowCount; rowsToInsert[i] = dragRowCount;
++dragRowCount; ++dragRowCount;
} }
} }
for (int i = 0; i < rows.count(); ++i) for (int i = 0; i < rows.count(); ++i)
rows[i] = top + rowsToInsert[rows[i]]; rows[i] = top + rowsToInsert.at(rows.at(i));
QBitArray isWrittenTo(dragRowCount * dragColumnCount); QBitArray isWrittenTo(dragRowCount * dragColumnCount);

View File

@ -863,7 +863,7 @@ void QItemSelectionModelPrivate::_q_layoutAboutToBeChanged(const QList<QPersiste
// optimization for when all indexes are selected // optimization for when all indexes are selected
// (only if there is lots of items (1000) because this is not entirely correct) // (only if there is lots of items (1000) because this is not entirely correct)
if (ranges.isEmpty() && currentSelection.count() == 1) { if (ranges.isEmpty() && currentSelection.count() == 1) {
QItemSelectionRange range = currentSelection.first(); QItemSelectionRange range = currentSelection.constFirst();
QModelIndex parent = range.parent(); QModelIndex parent = range.parent();
tableRowCount = model->rowCount(parent); tableRowCount = model->rowCount(parent);
tableColCount = model->columnCount(parent); tableColCount = model->columnCount(parent);

View File

@ -275,7 +275,7 @@ public:
const QVector<int> &source_to_proxy, const QVector<int> &source_items, const QVector<int> &source_to_proxy, const QVector<int> &source_items,
int &proxy_low, int &proxy_high) const; int &proxy_low, int &proxy_high) const;
QModelIndexPairList store_persistent_indexes(); QModelIndexPairList store_persistent_indexes() const;
void update_persistent_indexes(const QModelIndexPairList &source_indexes); void update_persistent_indexes(const QModelIndexPairList &source_indexes);
void filter_about_to_be_changed(const QModelIndex &source_parent = QModelIndex()); void filter_about_to_be_changed(const QModelIndex &source_parent = QModelIndex());
@ -1014,9 +1014,9 @@ void QSortFilterProxyModelPrivate::build_source_to_proxy_mapping(
Maps the persistent proxy indexes to source indexes and Maps the persistent proxy indexes to source indexes and
returns the list of source indexes. returns the list of source indexes.
*/ */
QModelIndexPairList QSortFilterProxyModelPrivate::store_persistent_indexes() QModelIndexPairList QSortFilterProxyModelPrivate::store_persistent_indexes() const
{ {
Q_Q(QSortFilterProxyModel); Q_Q(const QSortFilterProxyModel);
QModelIndexPairList source_indexes; QModelIndexPairList source_indexes;
source_indexes.reserve(persistent.indexes.count()); source_indexes.reserve(persistent.indexes.count());
for (QPersistentModelIndexData *data : qAsConst(persistent.indexes)) { for (QPersistentModelIndexData *data : qAsConst(persistent.indexes)) {

View File

@ -59,12 +59,12 @@ int appCmdShow = 0;
Q_CORE_EXPORT QString qAppFileName() Q_CORE_EXPORT QString qAppFileName()
{ {
return QFileInfo(QCoreApplication::arguments().first()).filePath(); return QFileInfo(QCoreApplication::arguments().constFirst()).filePath();
} }
QString QCoreApplicationPrivate::appName() const QString QCoreApplicationPrivate::appName() const
{ {
return QFileInfo(QCoreApplication::arguments().first()).baseName(); return QFileInfo(QCoreApplication::arguments().constFirst()).baseName();
} }
#else #else

View File

@ -143,7 +143,7 @@ static gboolean timerSourceCheckHelper(GTimerSource *src)
|| (src->processEventsFlags & QEventLoop::X11ExcludeTimers)) || (src->processEventsFlags & QEventLoop::X11ExcludeTimers))
return false; return false;
if (src->timerList.updateCurrentTime() < src->timerList.first()->timeout) if (src->timerList.updateCurrentTime() < src->timerList.constFirst()->timeout)
return false; return false;
return true; return true;

View File

@ -591,7 +591,7 @@ int QTimerInfoList::activateTimers()
if (isEmpty()) if (isEmpty())
break; break;
QTimerInfo *currentTimerInfo = first(); QTimerInfo *currentTimerInfo = constFirst();
if (currentTime < currentTimerInfo->timeout) if (currentTime < currentTimerInfo->timeout)
break; // no timer has expired break; // no timer has expired

View File

@ -406,7 +406,7 @@ QMimeType QMimeDatabase::mimeTypeForFile(const QString &fileName, MatchMode mode
{ {
if (mode == MatchExtension) { if (mode == MatchExtension) {
QMutexLocker locker(&d->mutex); QMutexLocker locker(&d->mutex);
QStringList matches = d->mimeTypeForFileName(fileName); const QStringList matches = d->mimeTypeForFileName(fileName);
const int matchCount = matches.count(); const int matchCount = matches.count();
if (matchCount == 0) { if (matchCount == 0) {
return d->mimeTypeForName(d->defaultMimeType()); return d->mimeTypeForName(d->defaultMimeType());

View File

@ -205,7 +205,7 @@ bool QMimeBinaryProvider::isValid()
return false; return false;
// We found exactly one file; is it the user-modified mimes, or a system file? // We found exactly one file; is it the user-modified mimes, or a system file?
const QString foundFile = m_cacheFiles.first()->file.fileName(); const QString foundFile = m_cacheFiles.constFirst()->file.fileName();
const QString localCacheFile = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/mime/mime.cache"); const QString localCacheFile = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/mime/mime.cache");
return foundFile != localCacheFile; return foundFile != localCacheFile;
@ -629,7 +629,7 @@ void QMimeBinaryProvider::loadMimeTypePrivate(QMimeTypePrivate &data)
// Let's assume that shared-mime-info is at least version 0.70 // Let's assume that shared-mime-info is at least version 0.70
// Otherwise we would need 1) a version check, and 2) code for parsing patterns from the globs file. // Otherwise we would need 1) a version check, and 2) code for parsing patterns from the globs file.
#if 1 #if 1
if (!mainPattern.isEmpty() && (data.globPatterns.isEmpty() || data.globPatterns.first() != mainPattern)) { if (!mainPattern.isEmpty() && (data.globPatterns.isEmpty() || data.globPatterns.constFirst() != mainPattern)) {
// ensure it's first in the list of patterns // ensure it's first in the list of patterns
data.globPatterns.removeAll(mainPattern); data.globPatterns.removeAll(mainPattern);
data.globPatterns.prepend(mainPattern); data.globPatterns.prepend(mainPattern);
@ -637,7 +637,7 @@ void QMimeBinaryProvider::loadMimeTypePrivate(QMimeTypePrivate &data)
#else #else
const bool globsInXml = sharedMimeInfoVersion() >= QT_VERSION_CHECK(0, 70, 0); const bool globsInXml = sharedMimeInfoVersion() >= QT_VERSION_CHECK(0, 70, 0);
if (globsInXml) { if (globsInXml) {
if (!mainPattern.isEmpty() && data.globPatterns.first() != mainPattern) { if (!mainPattern.isEmpty() && data.globPatterns.constFirst() != mainPattern) {
// ensure it's first in the list of patterns // ensure it's first in the list of patterns
data.globPatterns.removeAll(mainPattern); data.globPatterns.removeAll(mainPattern);
data.globPatterns.prepend(mainPattern); data.globPatterns.prepend(mainPattern);

View File

@ -209,6 +209,11 @@ QAbstractState *QHistoryState::defaultState() const
return d->defaultTransition ? d->defaultTransition->targetState() : Q_NULLPTR; return d->defaultTransition ? d->defaultTransition->targetState() : Q_NULLPTR;
} }
static inline bool isSoleEntry(const QList<QAbstractState*> &states, const QAbstractState * state)
{
return states.size() == 1 && states.first() == state;
}
/*! /*!
Sets this history state's default state to be the given \a state. Sets this history state's default state to be the given \a state.
\a state must be a sibling of this history state. \a state must be a sibling of this history state.
@ -224,9 +229,7 @@ void QHistoryState::setDefaultState(QAbstractState *state)
"to this history state's group (%p)", state, parentState()); "to this history state's group (%p)", state, parentState());
return; return;
} }
if (!d->defaultTransition if (!d->defaultTransition || !isSoleEntry(d->defaultTransition->targetStates(), state)) {
|| d->defaultTransition->targetStates().size() != 1
|| d->defaultTransition->targetStates().first() != state) {
if (!d->defaultTransition || !qobject_cast<DefaultStateTransition*>(d->defaultTransition)) { if (!d->defaultTransition || !qobject_cast<DefaultStateTransition*>(d->defaultTransition)) {
d->defaultTransition = new DefaultStateTransition(this, state); d->defaultTransition = new DefaultStateTransition(this, state);
emit defaultTransitionChanged(QHistoryState::QPrivateSignal()); emit defaultTransitionChanged(QHistoryState::QPrivateSignal());

View File

@ -692,7 +692,7 @@ void QStateMachinePrivate::microstep(QEvent *event, const QList<QAbstractTransit
// Add "implicit" assignments for restored properties to the first // Add "implicit" assignments for restored properties to the first
// (outermost) entered state // (outermost) entered state
Q_ASSERT(!enteredStates.isEmpty()); Q_ASSERT(!enteredStates.isEmpty());
QAbstractState *s = enteredStates.first(); QAbstractState *s = enteredStates.constFirst();
assignmentsForEnteredStates[s] << restorablesToPropertyList(pendingRestorables); assignmentsForEnteredStates[s] << restorablesToPropertyList(pendingRestorables);
} }

View File

@ -121,7 +121,7 @@ public:
void addEvent(const QPostEvent &ev) { void addEvent(const QPostEvent &ev) {
int priority = ev.priority; int priority = ev.priority;
if (isEmpty() || if (isEmpty() ||
last().priority >= priority || constLast().priority >= priority ||
insertionOffset >= size()) { insertionOffset >= size()) {
// optimization: we can simply append if the last event in // optimization: we can simply append if the last event in
// the queue has higher or equal priority // the queue has higher or equal priority

View File

@ -228,7 +228,7 @@ int QThreadPoolPrivate::activeThreadCount() const
void QThreadPoolPrivate::tryToStartMoreThreads() void QThreadPoolPrivate::tryToStartMoreThreads()
{ {
// try to push tasks on the queue to any available threads // try to push tasks on the queue to any available threads
while (!queue.isEmpty() && tryStart(queue.first().first)) while (!queue.isEmpty() && tryStart(queue.constFirst().first))
queue.removeFirst(); queue.removeFirst();
} }

View File

@ -141,7 +141,7 @@ void QWaitConditionPrivate::post(QWaitConditionEvent *wce, bool ret)
// wakeups delivered after the timeout should be forwarded to the next waiter // wakeups delivered after the timeout should be forwarded to the next waiter
if (!ret && wce->wokenUp && !queue.isEmpty()) { if (!ret && wce->wokenUp && !queue.isEmpty()) {
QWaitConditionEvent *other = queue.first(); QWaitConditionEvent *other = queue.constFirst();
SetEvent(other->event); SetEvent(other->event);
other->wokenUp = true; other->wokenUp = true;
} }

View File

@ -887,7 +887,8 @@ QStringList QCommandLineParser::values(const QString &optionName) const
bool QCommandLineParser::isSet(const QCommandLineOption &option) const bool QCommandLineParser::isSet(const QCommandLineOption &option) const
{ {
// option.names() might be empty if the constructor failed // option.names() might be empty if the constructor failed
return !option.names().isEmpty() && isSet(option.names().first()); const auto names = option.names();
return !names.isEmpty() && isSet(names.first());
} }
/*! /*!
@ -905,7 +906,7 @@ bool QCommandLineParser::isSet(const QCommandLineOption &option) const
*/ */
QString QCommandLineParser::value(const QCommandLineOption &option) const QString QCommandLineParser::value(const QCommandLineOption &option) const
{ {
return value(option.names().first()); return value(option.names().constFirst());
} }
/*! /*!
@ -923,7 +924,7 @@ QString QCommandLineParser::value(const QCommandLineOption &option) const
*/ */
QStringList QCommandLineParser::values(const QCommandLineOption &option) const QStringList QCommandLineParser::values(const QCommandLineOption &option) const
{ {
return values(option.names().first()); return values(option.names().constFirst());
} }
/*! /*!

View File

@ -444,7 +444,7 @@ struct BezierEase : public QEasingCurveFunction
void init() void init()
{ {
if (_bezierCurves.last() == QPointF(1.0, 1.0)) { if (_bezierCurves.constLast() == QPointF(1.0, 1.0)) {
_init = true; _init = true;
_curveCount = _bezierCurves.count() / 3; _curveCount = _bezierCurves.count() / 3;

View File

@ -122,7 +122,7 @@ QLocale QSystemLocale::fallbackUiLocale() const
// the first part of LANGUAGE if LANGUAGE is set and has a first part: // the first part of LANGUAGE if LANGUAGE is set and has a first part:
QByteArray language = qgetenv("LANGUAGE"); QByteArray language = qgetenv("LANGUAGE");
if (!language.isEmpty()) { if (!language.isEmpty()) {
language = language.split(':').first(); language = language.split(':').constFirst();
if (!language.isEmpty()) if (!language.isEmpty())
return QLocale(QString::fromLatin1(language)); return QLocale(QString::fromLatin1(language));
} }

View File

@ -74,14 +74,14 @@ void QRingBuffer::free(qint64 bytes)
Q_ASSERT(bytes <= bufferSize); Q_ASSERT(bytes <= bufferSize);
while (bytes > 0) { while (bytes > 0) {
const qint64 blockSize = buffers.first().size() - head; const qint64 blockSize = buffers.constFirst().size() - head;
if (tailBuffer == 0 || blockSize > bytes) { if (tailBuffer == 0 || blockSize > bytes) {
// keep a single block around if it does not exceed // keep a single block around if it does not exceed
// the basic block size, to avoid repeated allocations // the basic block size, to avoid repeated allocations
// between uses of the buffer // between uses of the buffer
if (bufferSize <= bytes) { if (bufferSize <= bytes) {
if (buffers.first().size() <= basicBlockSize) { if (buffers.constFirst().size() <= basicBlockSize) {
bufferSize = 0; bufferSize = 0;
head = tail = 0; head = tail = 0;
} else { } else {
@ -114,8 +114,8 @@ char *QRingBuffer::reserve(qint64 bytes)
} else { } else {
const qint64 newSize = bytes + tail; const qint64 newSize = bytes + tail;
// if need buffer reallocation // if need buffer reallocation
if (newSize > buffers.last().size()) { if (newSize > buffers.constLast().size()) {
if (newSize > buffers.last().capacity() && (tail >= basicBlockSize if (newSize > buffers.constLast().capacity() && (tail >= basicBlockSize
|| newSize >= MaxByteArraySize)) { || newSize >= MaxByteArraySize)) {
// shrink this buffer to its current size // shrink this buffer to its current size
buffers.last().resize(tail); buffers.last().resize(tail);
@ -180,7 +180,7 @@ void QRingBuffer::chop(qint64 bytes)
// the basic block size, to avoid repeated allocations // the basic block size, to avoid repeated allocations
// between uses of the buffer // between uses of the buffer
if (bufferSize <= bytes) { if (bufferSize <= bytes) {
if (buffers.first().size() <= basicBlockSize) { if (buffers.constFirst().size() <= basicBlockSize) {
bufferSize = 0; bufferSize = 0;
head = tail = 0; head = tail = 0;
} else { } else {
@ -198,7 +198,7 @@ void QRingBuffer::chop(qint64 bytes)
bytes -= tail; bytes -= tail;
buffers.removeLast(); buffers.removeLast();
--tailBuffer; --tailBuffer;
tail = buffers.last().size(); tail = buffers.constLast().size();
} }
} }

View File

@ -243,7 +243,7 @@ QTimeZonePrivate::Data QMacTimeZonePrivate::previousTransition(qint64 beforeMSec
} }
} }
if (secsList.size() >= 1) if (secsList.size() >= 1)
return data(qint64(secsList.last()) * 1000); return data(qint64(secsList.constLast()) * 1000);
else else
return invalidData(); return invalidData();
} }