QString: don't detach in insert(qsizetype, QUtf8StringView)

If the string is shared, instead of detaching (which would copy the
whole string data before doing the insertion), create a new string and
copy characters to it as needed then swap it with "this".

[ChangeLog][QtCore][QString] Inserting Utf8 data (e.g. a
QUtf8StringView) into a currently shared QString is now done more
efficiently.

Task-number: QTBUG-106186
Change-Id: I832bde1494108685cc2f630750dfe9b38cd96931
Reviewed-by: Thiago Macieira <thiago.macieira@intel.com>
bb10
Ahmad Samir 2022-12-11 15:35:34 +02:00
parent 5f73f48556
commit 3a3b76e040
1 changed files with 16 additions and 0 deletions

View File

@ -3031,6 +3031,22 @@ QString &QString::insert(qsizetype i, QUtf8StringView s)
if (Q_UNLIKELY(i > d.size))
difference = i - d.size;
const qsizetype newSize = d.size + difference + insert_size;
if (d.needsDetach() || needsReallocate(*this, newSize)) {
const auto cbegin = this->cbegin();
const auto insert_start = difference == 0 ? std::next(cbegin, i) : cend();
QString other;
other.reserve(newSize);
other.append(QStringView(cbegin, insert_start));
if (difference > 0)
other.resize(i, u' ');
other.append(s);
other.append(QStringView(insert_start, cend()));
swap(other);
return *this;
}
if (i >= d.size) {
d.detachAndGrow(QArrayData::GrowsAtEnd, difference + insert_size, nullptr, nullptr);
Q_CHECK_PTR(d.data());