QByteArray: make replace(pos, len, view) consistent with QString's

Return early if `pos` is out-of-bounds.

Amends 57d91d8029064b592dee8adf819bde676763df28 (also part of this
commit message was borrowed from it).

[ChangeLog][QtCore][Important Behavior Changes][QByteArray] replace()
is now consistent with QString::replace() in its treatment of
out-of-bounds indexes.

Change-Id: Iae8cf795364654fd6438b2a4ed3162925a73cb9e
Reviewed-by: Ivan Solovev <ivan.solovev@qt.io>
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
This commit is contained in:
Ahmad Samir 2025-05-07 11:19:19 +03:00
parent 2da64908c2
commit a15639a3ab
2 changed files with 8 additions and 2 deletions

View File

@ -2477,11 +2477,17 @@ QByteArray &QByteArray::remove(qsizetype pos, qsizetype len)
QByteArray &QByteArray::replace(qsizetype pos, qsizetype len, QByteArrayView after)
{
if (size_t(pos) > size_t(this->size()))
return *this;
if (len > this->size() - pos)
len = this->size() - pos;
if (QtPrivate::q_points_into_range(after.data(), d)) {
QVarLengthArray copy(after.data(), after.data() + after.size());
return replace(pos, len, QByteArrayView{copy});
}
if (len == after.size() && (pos + len <= size())) {
if (len == after.size()) {
// same size: in-place replacement possible
if (len > 0) {
detach();

View File

@ -1481,7 +1481,7 @@ void tst_QByteArray::replace_data()
QTest::newRow("4") << QByteArray() << 0 << 0 << QByteArray() << QByteArray() << QByteArray();
// index out of range
QTest::newRow("5") << QByteArray() << 3 << 0 << QByteArray() << QByteArray("hi")
<< QByteArray(" hi");
<< QByteArray();
// Optimized path
QTest::newRow("6") << QByteArray("abcdef") << 3 << 12 << QByteArray()
<< QByteArray("abcdefghijkl") << QByteArray("abcabcdefghijkl");