From f9b867216ba2728ff993020599f5062e2f023de1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A5rten=20Nordheim?= Date: Wed, 12 May 2021 09:41:35 +0200 Subject: [PATCH] String API Symmetry: test for indexOf with large negative offset Small change needed to make QString_char16 and QString_QChar return -1 in this case, but other combinations already returns -1. [ChangeLog][QtCore][Behavior Change] QString::indexOf(QChar) and QString::indexOf(char16_t) now treat a negative start-position, from, bigger than the string's size as invalid. It previously clipped such start-positions to the start of the string, inconsistently with other QString indexOf overloads. Change-Id: Ic56c8a558bf40a94845c649647db569892d4df02 Reviewed-by: Edward Welbourne --- src/corelib/text/qstring.cpp | 2 ++ .../corelib/text/qstringapisymmetry/tst_qstringapisymmetry.cpp | 3 +++ tests/auto/corelib/tools/collections/tst_collections.cpp | 2 +- 3 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/corelib/text/qstring.cpp b/src/corelib/text/qstring.cpp index 89abbcbff3..3e4d95188d 100644 --- a/src/corelib/text/qstring.cpp +++ b/src/corelib/text/qstring.cpp @@ -10157,6 +10157,8 @@ char16_t valueTypeToUtf16(char t) static inline qsizetype qFindChar(QStringView str, QChar ch, qsizetype from, Qt::CaseSensitivity cs) noexcept { + if (-from > str.size()) + return -1; if (from < 0) from = qMax(from + str.size(), qsizetype(0)); if (from < str.size()) { diff --git a/tests/auto/corelib/text/qstringapisymmetry/tst_qstringapisymmetry.cpp b/tests/auto/corelib/text/qstringapisymmetry/tst_qstringapisymmetry.cpp index 48855592dc..32c2576b86 100644 --- a/tests/auto/corelib/text/qstringapisymmetry/tst_qstringapisymmetry.cpp +++ b/tests/auto/corelib/text/qstringapisymmetry/tst_qstringapisymmetry.cpp @@ -2268,6 +2268,9 @@ void tst_QStringApiSymmetry::indexOf_data(bool rhsHasVariableLength) << a << QLatin1String("a") << zeroPos << minus1Pos << minus1Pos; QTest::addRow("haystack: null, needle: a") << null << QLatin1String() << a << QLatin1String("a") << zeroPos << minus1Pos << minus1Pos; + QTest::addRow("haystack: anything, needle: a, large negative offset") + << "anything" << QLatin1String("anything") << a << QLatin1String("a") << qsizetype(-500) + << minus1Pos << minus1Pos; #define ROW(h, n, st, cs, cis) \ QTest::addRow("haystack: %s, needle: %s", #h, #n) << h << QLatin1String(#h) \ diff --git a/tests/auto/corelib/tools/collections/tst_collections.cpp b/tests/auto/corelib/tools/collections/tst_collections.cpp index 34a352c614..5b26ae5faa 100644 --- a/tests/auto/corelib/tools/collections/tst_collections.cpp +++ b/tests/auto/corelib/tools/collections/tst_collections.cpp @@ -1710,7 +1710,7 @@ void tst_Collections::qstring() QVERIFY (hello.contains('e') != false); QVERIFY(hello.indexOf('e') == 1); - QVERIFY(hello.indexOf('e', -10) == 1); + QVERIFY(hello.indexOf('e', -10) == -1); QVERIFY(hello.indexOf('l') == 2); QVERIFY(hello.indexOf('l',2) == 2); QVERIFY(hello.indexOf('l',3) == 3);