QByteArray: make replace() consistent with QString's

Assuming QString has seen a lot more effort put into this, simply copy
the preamble of QString::replace(ptr, n, ptr, n, cs) over to the
corresponding QByteArray::replace(view, view) function, so they behave
the same.

On reviewer request, change d.size == 0 to isEmpty(), in both functions'
preambles.

[ChangeLog][QtCore][Important Behavior Changes][QByteArray] replace()
is now consistent with QString::replace() in its treatment of empty
haystacks and needles.

Fixes: QTBUG-134079
Change-Id: I2366febee7de4646d6b33c39d2338760b58f2ec4
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
Reviewed-by: Ahmad Samir <a.samirh78@gmail.com>
This commit is contained in:
Marc Mutz 2025-02-26 10:39:22 +01:00
parent 61c2d3f101
commit 57d91d8029
4 changed files with 11 additions and 20 deletions

View File

@ -2532,12 +2532,19 @@ QByteArray &QByteArray::replace(QByteArrayView before, QByteArrayView after)
const char *a = after.data();
qsizetype asize = after.size();
if (isEmpty()) {
if (bsize)
return *this;
} else {
if (b == a && bsize == asize)
return *this;
}
if (asize == 0 && bsize == 0)
return *this;
if (bsize == 1 && asize == 1)
return replace(*b, *a); // use the fast char-char algorithm
if (isNull() || (b == a && bsize == asize))
return *this;
// protect against before or after being part of this
std::string pinnedNeedle, pinnedReplacement;
if (QtPrivate::q_points_into_range(a, d)) {

View File

@ -3864,7 +3864,7 @@ QString &QString::replace(const QChar *before, qsizetype blen,
const QChar *after, qsizetype alen,
Qt::CaseSensitivity cs)
{
if (d.size == 0) {
if (isEmpty()) {
if (blen)
return *this;
} else {

View File

@ -1590,15 +1590,7 @@ void tst_QByteArray::replaceWithEmptyNeedleInsertsBeforeEachChar()
// shared
auto copy = haystack;
copy.replace(needle, replacement);
if (isByteArray) {
QEXPECT_FAIL("/<null>/<null>/a/", "QTBUG-134079", Continue);
QEXPECT_FAIL("/<null>//a/", "QTBUG-134079", Continue);
}
QCOMPARE(copy.isNull(), result.isNull());
if (isByteArray) {
QEXPECT_FAIL("/<null>/<null>/a/", "QTBUG-134079", Continue);
QEXPECT_FAIL("/<null>//a/", "QTBUG-134079", Continue);
}
QCOMPARE(copy, result);
}
{

View File

@ -2543,19 +2543,11 @@ void tst_QStringApiSymmetry::replace_split_impl() const
{
auto copy = haystack;
copy.replace(needle, replacement);
if constexpr (std::is_same_v<Haystack, QByteArray>) {
QEXPECT_FAIL("null ~= null$", "QTBUG-134079", Continue);
QEXPECT_FAIL("null ~= empty$", "QTBUG-134079", Continue);
}
QCOMPARE(copy, result);
}
{
auto copy = detached(haystack);
copy.replace(needle, replacement);
if constexpr (std::is_same_v<Haystack, QByteArray>) {
QEXPECT_FAIL("null ~= null$", "QTBUG-134079", Continue);
QEXPECT_FAIL("null ~= empty$", "QTBUG-134079", Continue);
}
QCOMPARE(copy, result);
}
}