summaryrefslogtreecommitdiffstats
path: root/src/corelib/text
diff options
context:
space:
mode:
authorGiuseppe D'Angelo <giuseppe.dangelo@kdab.com>2021-08-23 20:28:44 +0200
committerQt Cherry-pick Bot <cherrypick_bot@qt-project.org>2021-08-26 07:34:33 +0000
commit2ecbc85454d56dfd85c4d4954eb74ed9c2673c71 (patch)
tree4561c8966e21abfd9185b98691e1f2e63f6809e9 /src/corelib/text
parentf0101e09d2a2d4987c5f89dcd339a02e7d3c8822 (diff)
QBA(V)/QS(V)::lastIndexOf: fix the search of 1-char needles
When a needle has length 1 (because it's a QChar/char16_t, or because it's a string-like of length 1) then an ad-hoc search algorithm is used. This algorithm had a off-by-one, by not allowing to match at the last position of a haystack (in case `from` was `haystack.size()`). That is inconsistent with the general search of substring needles (and what QByteArray does). Fix that case and amend wrong tests. This in turn unveiled the fact that the algorithm was unable to cope with 0-length haystacks (whops), so fix that as well. Drive-by, add a similar fix for QByteArray. Amends 6cee204d56205e250b0675c9c6d4dd8a2367f3c4. Change-Id: I6b3effc4ecd74bcbcd33dd2e550da2df7bf05ae3 Reviewed-by: Qt CI Bot <qt_ci_bot@qt-project.org> Reviewed-by: Edward Welbourne <edward.welbourne@qt.io> (cherry picked from commit f0c2c987e3e7eb046303892b1eee4f848759923a) Reviewed-by: Qt Cherry-pick Bot <cherrypick_bot@qt-project.org>
Diffstat (limited to 'src/corelib/text')
-rw-r--r--src/corelib/text/qbytearray.cpp2
-rw-r--r--src/corelib/text/qstring.cpp6
2 files changed, 6 insertions, 2 deletions
diff --git a/src/corelib/text/qbytearray.cpp b/src/corelib/text/qbytearray.cpp
index 74ea0cfc7d..c2601b0b0b 100644
--- a/src/corelib/text/qbytearray.cpp
+++ b/src/corelib/text/qbytearray.cpp
@@ -2506,6 +2506,8 @@ static qsizetype lastIndexOfHelper(const char *haystack, qsizetype l, const char
static inline qsizetype lastIndexOfCharHelper(QByteArrayView haystack, qsizetype from, char needle) noexcept
{
+ if (haystack.size() == 0)
+ return -1;
if (from < 0)
from += haystack.size();
else if (from > haystack.size())
diff --git a/src/corelib/text/qstring.cpp b/src/corelib/text/qstring.cpp
index 3c795e2a4b..d74ec6b132 100644
--- a/src/corelib/text/qstring.cpp
+++ b/src/corelib/text/qstring.cpp
@@ -10358,10 +10358,12 @@ template <typename Haystack>
static inline qsizetype qLastIndexOf(Haystack haystack, QChar needle,
qsizetype from, Qt::CaseSensitivity cs) noexcept
{
+ if (haystack.size() == 0)
+ return -1;
if (from < 0)
from += haystack.size();
- if (std::size_t(from) >= std::size_t(haystack.size()))
- return -1;
+ else if (std::size_t(from) > std::size_t(haystack.size()))
+ from = haystack.size() - 1;
if (from >= 0) {
char16_t c = needle.unicode();
const auto b = haystack.data();