From ebaae45ea17efc230209ed90d94596647cf6cb48 Mon Sep 17 00:00:00 2001 From: Andreas Buhr Date: Thu, 19 Nov 2020 14:26:18 +0100 Subject: [PATCH] Fix logic error in QString::replace(ch, after, cs) Coverage analysis showed that an if-branch marked "Q_LIKELY" was never taken. It turns out the code was incorrect, but behaved correctly. This patch fixes the logic and adds a unit test. Pick-to: 5.15 Change-Id: I9b4ba76392b52f07b8e21188496e23f98dba95a9 Reviewed-by: Thiago Macieira --- src/corelib/text/qstring.cpp | 2 +- tests/auto/corelib/text/qstring/tst_qstring.cpp | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/corelib/text/qstring.cpp b/src/corelib/text/qstring.cpp index 091f44736e..dd00456fb2 100644 --- a/src/corelib/text/qstring.cpp +++ b/src/corelib/text/qstring.cpp @@ -3382,7 +3382,7 @@ QString& QString::replace(QChar ch, const QString &after, Qt::CaseSensitivity cs replace_helper(indices, pos, 1, after.constData(), after.size()); - if (Q_LIKELY(index == -1)) // Nothing left to replace + if (Q_LIKELY(index == size())) // Nothing left to replace break; // The call to replace_helper just moved what index points at: index += pos*(after.size() - 1); diff --git a/tests/auto/corelib/text/qstring/tst_qstring.cpp b/tests/auto/corelib/text/qstring/tst_qstring.cpp index 47470abd6f..e6d73c6ef1 100644 --- a/tests/auto/corelib/text/qstring/tst_qstring.cpp +++ b/tests/auto/corelib/text/qstring/tst_qstring.cpp @@ -2876,6 +2876,17 @@ void tst_QString::replace_string_extra() s.replace( QString("BBB"), smallReplacement ); QCOMPARE( s, smallReplacement ); } + + { + QString s(QLatin1String("BBB")); + QString expected(QLatin1String("BBB")); + for (int i = 0; i < 1028; ++i) { + s.append("X"); + expected.append("GXU"); + } + s.replace(QChar('X'), "GXU"); + QCOMPARE(s, expected); + } } void tst_QString::replace_regexp()