Use slice method where applicable

These code segments already have its boundary checked and can thus be faster.

PR #22411.
This commit is contained in:
Chocobo1 2025-03-15 14:58:59 +08:00 committed by GitHub
parent d174bc75e4
commit 5a4b3b25d3
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
23 changed files with 113 additions and 63 deletions

View file

@ -659,7 +659,13 @@ void Application::runExternalProgram(const QString &programTemplate, const BitTo
{
// strip redundant quotes
if (arg.startsWith(u'"') && arg.endsWith(u'"'))
arg = arg.mid(1, (arg.size() - 2));
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
arg.slice(1, (arg.size() - 2));
#else
arg.removeLast().removeFirst();
#endif
}
arg = replaceVariables(arg);
}

View file

@ -465,13 +465,13 @@ QBtCommandLineParameters parseCommandLine(const QStringList &args)
return result;
}
QString wrapText(const QString &text, int initialIndentation = USAGE_TEXT_COLUMN, int wrapAtColumn = WRAP_AT_COLUMN)
QString wrapText(const QString &text, const int initialIndentation = USAGE_TEXT_COLUMN, const int wrapAtColumn = WRAP_AT_COLUMN)
{
QStringList words = text.split(u' ');
const QStringList words = text.split(u' ');
QStringList lines = {words.first()};
int currentLineMaxLength = wrapAtColumn - initialIndentation;
for (const QString &word : asConst(words.mid(1)))
for (const QString &word : asConst(words.sliced(1)))
{
if (lines.last().length() + word.length() + 1 < currentLineMaxLength)
{

View file

@ -39,7 +39,11 @@ PeerAddress PeerAddress::parse(const QStringView address)
if (address.startsWith(u'[') && address.contains(u"]:"))
{ // IPv6
ipPort = address.split(u"]:");
ipPort[0] = ipPort[0].mid(1); // chop '['
#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
ipPort[0].slice(1); // chop '['
#else
ipPort[0] = ipPort[0].sliced(1); // chop '['
#endif
}
else if (address.contains(u':'))
{ // IPv4

View file

@ -365,7 +365,7 @@ QString Session::subcategoryName(const QString &category)
{
const int sepIndex = category.lastIndexOf(u'/');
if (sepIndex >= 0)
return category.mid(sepIndex + 1);
return category.sliced(sepIndex + 1);
return category;
}
@ -374,7 +374,7 @@ QString Session::parentCategoryName(const QString &category)
{
const int sepIndex = category.lastIndexOf(u'/');
if (sepIndex >= 0)
return category.left(sepIndex);
return category.first(sepIndex);
return {};
}
@ -385,7 +385,7 @@ QStringList Session::expandCategory(const QString &category)
int index = 0;
while ((index = category.indexOf(u'/', index)) >= 0)
{
result << category.left(index);
result << category.first(index);
++index;
}
result << category;

View file

@ -155,7 +155,11 @@ void Connection::read()
sendResponse(resp);
}
#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
m_receivedData.slice(result.frameSize);
#else
m_receivedData.remove(0, result.frameSize);
#endif
}
break;

View file

@ -69,8 +69,8 @@ namespace
return false;
}
const QString name = line.left(i).trimmed().toString().toLower();
const QString value = line.mid(i + 1).trimmed().toString();
const QString name = line.first(i).trimmed().toString().toLower();
const QString value = line.sliced(i + 1).trimmed().toString();
out[name] = value;
return true;
@ -206,13 +206,13 @@ bool RequestParser::parseRequestLine(const QString &line)
// Request Target
const QByteArray url {match.captured(2).toLatin1()};
const int sepPos = url.indexOf('?');
const QByteArrayView pathComponent = ((sepPos == -1) ? url : QByteArrayView(url).mid(0, sepPos));
const QByteArrayView pathComponent = ((sepPos == -1) ? url : QByteArrayView(url).first(sepPos));
m_request.path = QString::fromUtf8(QByteArray::fromPercentEncoding(asQByteArray(pathComponent)));
if (sepPos >= 0)
{
const QByteArrayView query = QByteArrayView(url).mid(sepPos + 1);
const QByteArrayView query = QByteArrayView(url).sliced(sepPos + 1);
// [rfc3986] 2.4 When to Encode or Decode
// URL components should be separated before percent-decoding
@ -221,8 +221,8 @@ bool RequestParser::parseRequestLine(const QString &line)
const int eqCharPos = param.indexOf('=');
if (eqCharPos <= 0) continue; // ignores params without name
const QByteArrayView nameComponent = param.mid(0, eqCharPos);
const QByteArrayView valueComponent = param.mid(eqCharPos + 1);
const QByteArrayView nameComponent = param.first(eqCharPos);
const QByteArrayView valueComponent = param.sliced(eqCharPos + 1);
const QString paramName = QString::fromUtf8(
QByteArray::fromPercentEncoding(asQByteArray(nameComponent)).replace('+', ' '));
const QByteArray paramValue = QByteArray::fromPercentEncoding(asQByteArray(valueComponent)).replace('+', ' ');
@ -270,7 +270,7 @@ bool RequestParser::parsePostMessage(const QByteArrayView data)
return false;
}
const QByteArray delimiter = Utils::String::unquote(QStringView(contentType).mid(idx + boundaryFieldName.size())).toLatin1();
const QByteArray delimiter = Utils::String::unquote(QStringView(contentType).sliced(idx + boundaryFieldName.size())).toLatin1();
if (delimiter.isEmpty())
{
qWarning() << Q_FUNC_INFO << "boundary delimiter field empty!";
@ -310,8 +310,8 @@ bool RequestParser::parseFormData(const QByteArrayView data)
return false;
}
const QString headers = QString::fromLatin1(data.mid(0, eohPos));
const QByteArrayView payload = viewWithoutEndingWith(data.mid((eohPos + EOH.size()), data.size()), CRLF);
const QString headers = QString::fromLatin1(data.first(eohPos));
const QByteArrayView payload = viewWithoutEndingWith(data.sliced((eohPos + EOH.size())), CRLF);
HeaderMap headersMap;
const QList<QStringView> headerLines = QStringView(headers).split(QString::fromLatin1(CRLF), Qt::SkipEmptyParts);
@ -328,8 +328,8 @@ bool RequestParser::parseFormData(const QByteArrayView data)
if (idx < 0)
continue;
const QString name = directive.left(idx).trimmed().toString().toLower();
const QString value = Utils::String::unquote(directive.mid(idx + 1).trimmed()).toString();
const QString name = directive.first(idx).trimmed().toString().toLower();
const QString value = Utils::String::unquote(directive.sliced(idx + 1).trimmed()).toString();
headersMap[name] = value;
}
}

View file

@ -148,8 +148,7 @@ void Smtp::sendMail(const QString &from, const QString &to, const QString &subje
// Encode the body in base64
QString crlfBody = body;
const QByteArray b = crlfBody.replace(u"\n"_s, u"\r\n"_s).toUtf8().toBase64();
const int ct = b.length();
for (int i = 0; i < ct; i += 78)
for (int i = 0, end = b.length(); i < end; i += 78)
m_message += b.mid(i, 78);
m_from = from;
m_rcpt = to;
@ -190,8 +189,12 @@ void Smtp::readyRead()
{
const int pos = m_buffer.indexOf("\r\n");
if (pos < 0) return; // Loop exit condition
const QByteArray line = m_buffer.left(pos);
const QByteArray line = m_buffer.first(pos);
#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
m_buffer.slice(pos + 2);
#else
m_buffer.remove(0, (pos + 2));
#endif
qDebug() << "Response line:" << line;
// Extract response code
const QByteArray code = line.left(3);

View file

@ -94,7 +94,13 @@ bool Path::isValid() const
#if defined(Q_OS_WIN)
QStringView view = m_pathStr;
if (hasDriveLetter(view))
view = view.mid(3);
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
view.slice(3);
#else
view = view.sliced(3);
#endif
}
// \\37 is using base-8 number system
const QRegularExpression regex {u"[\\0-\\37:?\"*<>|]"_s};
@ -147,9 +153,9 @@ Path Path::rootItem() const
#ifdef Q_OS_WIN
// should be `c:/` instead of `c:`
if ((slashIndex == 2) && hasDriveLetter(m_pathStr))
return createUnchecked(m_pathStr.left(slashIndex + 1));
return createUnchecked(m_pathStr.first(slashIndex + 1));
#endif
return createUnchecked(m_pathStr.left(slashIndex));
return createUnchecked(m_pathStr.first(slashIndex));
}
Path Path::parentPath() const
@ -167,9 +173,9 @@ Path Path::parentPath() const
// should be `c:/` instead of `c:`
// Windows "drive letter" is limited to one alphabet
if ((slashIndex == 2) && hasDriveLetter(m_pathStr))
return (m_pathStr.size() == 3) ? Path() : createUnchecked(m_pathStr.left(slashIndex + 1));
return (m_pathStr.size() == 3) ? Path() : createUnchecked(m_pathStr.first(slashIndex + 1));
#endif
return createUnchecked(m_pathStr.left(slashIndex));
return createUnchecked(m_pathStr.first(slashIndex));
}
QString Path::filename() const
@ -178,7 +184,7 @@ QString Path::filename() const
if (slashIndex == -1)
return m_pathStr;
return m_pathStr.mid(slashIndex + 1);
return m_pathStr.sliced(slashIndex + 1);
}
QString Path::extension() const
@ -188,9 +194,9 @@ QString Path::extension() const
return (u"." + suffix);
const int slashIndex = m_pathStr.lastIndexOf(u'/');
const auto filename = QStringView(m_pathStr).mid(slashIndex + 1);
const auto filename = QStringView(m_pathStr).sliced(slashIndex + 1);
const int dotIndex = filename.lastIndexOf(u'.', -2);
return ((dotIndex == -1) ? QString() : filename.mid(dotIndex).toString());
return ((dotIndex == -1) ? QString() : filename.sliced(dotIndex).toString());
}
bool Path::hasExtension(const QStringView ext) const
@ -293,7 +299,7 @@ Path Path::commonPath(const Path &left, const Path &right)
if (commonItemsCount > 0)
commonPathSize += (commonItemsCount - 1); // size of intermediate separators
return Path::createUnchecked(left.m_pathStr.left(commonPathSize));
return Path::createUnchecked(left.m_pathStr.first(commonPathSize));
}
Path Path::findRootFolder(const PathList &filePaths)
@ -322,7 +328,13 @@ void Path::stripRootFolder(PathList &filePaths)
return;
for (Path &filePath : filePaths)
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
filePath.m_pathStr.slice(commonRootFolder.m_pathStr.size() + 1);
#else
filePath.m_pathStr.remove(0, (commonRootFolder.m_pathStr.size() + 1));
#endif
}
}
void Path::addRootFolder(PathList &filePaths, const Path &rootFolder)

View file

@ -304,7 +304,13 @@ bool AutoDownloadRule::matchesEpisodeFilterExpression(const QString &articleTitl
// We need to trim leading zeroes, but if it's all zeros then we want episode zero.
while ((episode.size() > 1) && episode.startsWith(u'0'))
episode = episode.right(episode.size() - 1);
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
episode.slice(1);
#else
episode.remove(0, 1);
#endif
}
if (episode.indexOf(u'-') != -1)
{ // Range detected
@ -328,7 +334,7 @@ bool AutoDownloadRule::matchesEpisodeFilterExpression(const QString &articleTitl
if (episode.endsWith(u'-'))
{ // Infinite range
const int episodeOurs {QStringView(episode).left(episode.size() - 1).toInt()};
const int episodeOurs {QStringView(episode).chopped(1).toInt()};
if (((seasonTheirs == seasonOurs) && (episodeTheirs >= episodeOurs)) || (seasonTheirs > seasonOurs))
return true;
}

View file

@ -97,7 +97,7 @@ QStringList Item::expandPath(const QString &path)
int index = 0;
while ((index = path.indexOf(Item::PathSeparator, index)) >= 0)
{
result << path.left(index);
result << path.first(index);
++index;
}
result << path;
@ -108,11 +108,11 @@ QStringList Item::expandPath(const QString &path)
QString Item::parentPath(const QString &path)
{
const int pos = path.lastIndexOf(Item::PathSeparator);
return (pos >= 0) ? path.left(pos) : QString();
return (pos >= 0) ? path.first(pos) : QString();
}
QString Item::relativeName(const QString &path)
{
int pos;
return ((pos = path.lastIndexOf(Item::PathSeparator)) >= 0 ? path.right(path.size() - (pos + 1)) : path);
const int pos = path.lastIndexOf(Item::PathSeparator);
return (pos >= 0) ? path.sliced(pos + 1) : path;
}

View file

@ -385,8 +385,14 @@ void Session::loadLegacy()
uint i = 0;
for (QString legacyPath : legacyFeedPaths)
{
if (Item::PathSeparator == legacyPath[0])
if (legacyPath.startsWith(Item::PathSeparator))
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
legacyPath.slice(1);
#else
legacyPath.remove(0, 1);
#endif
}
const QString parentFolderPath = Item::parentPath(legacyPath);
const QString feedUrl = Item::relativeName(legacyPath);

View file

@ -469,9 +469,9 @@ void SearchPluginManager::pluginDownloadFinished(const Net::DownloadResult &resu
}
else
{
const QString url = result.url;
QString pluginName = url.mid(url.lastIndexOf(u'/') + 1);
pluginName.replace(u".py"_s, u""_s, Qt::CaseInsensitive);
const QString &url = result.url;
const QString pluginName = url.sliced(url.lastIndexOf(u'/') + 1)
.replace(u".py"_s, u""_s, Qt::CaseInsensitive);
if (pluginInfo(pluginName))
emit pluginUpdateFailed(pluginName, tr("Failed to download the plugin file. %1").arg(result.errorString));
@ -653,7 +653,7 @@ PluginVersion SearchPluginManager::getPluginVersion(const Path &filePath)
const auto line = QString::fromUtf8(pluginFile.readLine(lineMaxLength)).remove(u' ');
if (!line.startsWith(u"#VERSION:", Qt::CaseInsensitive)) continue;
const QString versionStr = line.mid(9);
const QString versionStr = line.sliced(9);
const auto version = PluginVersion::fromString(versionStr);
if (version.isValid())
return version;

View file

@ -64,7 +64,7 @@ int Utils::Compare::naturalCompare(const QString &left, const QString &right, co
const int start = pos;
while ((pos < str.size()) && str[pos].isDigit())
++pos;
return str.mid(start, (pos - start));
return str.sliced(start, (pos - start));
};
const QStringView numViewL = numberView(left, posL);

View file

@ -49,12 +49,13 @@ namespace Utils::String
template <typename T>
T unquote(const T &str, const QString &quotes = u"\""_s)
{
if (str.length() < 2) return str;
if (str.length() < 2)
return str;
for (const QChar quote : quotes)
{
if (str.startsWith(quote) && str.endsWith(quote))
return str.mid(1, (str.length() - 2));
return str.sliced(1, (str.length() - 2));
}
return str;

View file

@ -122,7 +122,7 @@ namespace
fsPathEdit->setCurrentIndex(existingIndex);
}
void updatePathHistory(const QString &settingsKey, const Path &path, const int maxLength)
void updatePathHistory(const QString &settingsKey, const Path &path, const qsizetype maxLength)
{
// Add last used save path to the front of history
@ -134,7 +134,10 @@ namespace
else
pathList.prepend(path.toString());
settings()->storeValue(settingsKey, QStringList(pathList.mid(0, maxLength)));
if (pathList.size() > maxLength)
pathList.resize(maxLength);
settings()->storeValue(settingsKey, pathList);
}
}
@ -375,8 +378,7 @@ AddNewTorrentDialog::AddNewTorrentDialog(const BitTorrent::TorrentDescriptor &to
connect(Preferences::instance(), &Preferences::changed, []
{
const int length = Preferences::instance()->addNewTorrentDialogSavePathHistoryLength();
settings()->storeValue(KEY_SAVEPATHHISTORY
, QStringList(settings()->loadValue<QStringList>(KEY_SAVEPATHHISTORY).mid(0, length)));
settings()->storeValue(KEY_SAVEPATHHISTORY, settings()->loadValue<QStringList>(KEY_SAVEPATHHISTORY).mid(0, length));
});
setCurrentContext(std::make_shared<Context>(Context {torrentDescr, inParams}));

View file

@ -234,14 +234,14 @@ void FileSystemPathEdit::setFileNameFilter(const QString &val)
const int closeBracePos = val.indexOf(u')', (openBracePos + 1));
if ((openBracePos > 0) && (closeBracePos > 0) && (closeBracePos > openBracePos + 2))
{
QString filterString = val.mid(openBracePos + 1, closeBracePos - openBracePos - 1);
const QString filterString = val.sliced((openBracePos + 1), (closeBracePos - openBracePos - 1));
if (filterString == u"*")
{ // no filters
d->m_editor->setFilenameFilters({});
}
else
{
QStringList filters = filterString.split(u' ', Qt::SkipEmptyParts);
const QStringList filters = filterString.split(u' ', Qt::SkipEmptyParts);
d->m_editor->setFilenameFilters(filters);
}
}

View file

@ -1859,10 +1859,10 @@ void OptionsDialog::setLocale(const QString &localeStr)
if (index < 0)
{
//Attempt to find a language match without a country
int pos = name.indexOf(u'_');
const int pos = name.indexOf(u'_');
if (pos > -1)
{
QString lang = name.left(pos);
const QString lang = name.first(pos);
index = m_ui->comboLanguage->findData(lang, Qt::UserRole);
}
}

View file

@ -82,7 +82,13 @@ namespace
QString relativePath = match.captured(6);
if (relativePath.startsWith(u'/'))
relativePath = relativePath.mid(1);
{
#if QT_VERSION >= QT_VERSION_CHECK(6, 8, 0)
relativePath.slice(1);
#else
relativePath.remove(0, 1);
#endif
}
const QString absoluteUrl = !host.isEmpty()
? QString(defaultScheme + u':' + host) : (normalizedBaseUrl + relativePath);

View file

@ -46,7 +46,7 @@ void SearchSortModel::setNameFilter(const QString &searchTerm)
{
m_searchTerm = searchTerm;
if ((searchTerm.length() > 2) && searchTerm.startsWith(u'"') && searchTerm.endsWith(u'"'))
m_searchTermWords = QStringList(m_searchTerm.mid(1, m_searchTerm.length() - 2));
m_searchTermWords = QStringList(m_searchTerm.sliced(1, (m_searchTerm.length() - 2)));
else
m_searchTermWords = searchTerm.split(u' ', Qt::SkipEmptyParts);
}

View file

@ -675,7 +675,7 @@ void SearchWidget::loadHistory()
}
if (history.size() > m_historyLength)
history = history.mid(history.size() - m_historyLength);
history.remove(0, (history.size() - m_historyLength));
m_searchPatternCompleterModel->setStringList(history);
});

View file

@ -174,9 +174,9 @@ namespace
{
QString shortName(const QString &fullName)
{
int pos = fullName.lastIndexOf(u'/');
const int pos = fullName.lastIndexOf(u'/');
if (pos >= 0)
return fullName.mid(pos + 1);
return fullName.sliced(pos + 1);
return fullName;
}
}

View file

@ -555,7 +555,7 @@ void TrackersFilterWidget::handleFavicoDownloadFinished(const Net::DownloadResul
{
if (result.url.endsWith(u".ico", Qt::CaseInsensitive))
{
const QString faviconURL = result.url.left(result.url.size() - 4) + u".png";
const QString faviconURL = QStringView(result.url).chopped(4) + u".png";
for (const auto &trackerHost : trackerHosts)
{
if (m_trackers.contains(trackerHost))

View file

@ -89,8 +89,8 @@ namespace
if (idx < 0)
continue;
const QString name = cookie.left(idx).trimmed().toString();
const QString value = Utils::String::unquote(cookie.mid(idx + 1).trimmed()).toString();
const QString name = cookie.first(idx).trimmed().toString();
const QString value = Utils::String::unquote(cookie.sliced(idx + 1).trimmed()).toString();
ret.insert(name, value);
}
return ret;
@ -469,8 +469,8 @@ void WebApplication::configure()
continue;
}
const QString header = line.left(idx).trimmed().toString();
const QString value = line.mid(idx + 1).trimmed().toString();
const QString header = line.first(idx).trimmed().toString();
const QString value = line.sliced(idx + 1).trimmed().toString();
m_prebuiltHeaders.push_back({header, value});
}
}