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
23 changed files with 113 additions and 63 deletions

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;