summaryrefslogtreecommitdiffstats
path: root/src/corelib/text
diff options
context:
space:
mode:
authorAhmad Samir <a.samirh78@gmail.com>2022-12-11 15:35:34 +0200
committerAhmad Samir <a.samirh78@gmail.com>2023-02-09 16:50:02 +0200
commit3a3b76e040ec800e1f3214803c051afacfdb0f7b (patch)
tree874ed7dd87a00feab96c301228a2ade0ef3284c2 /src/corelib/text
parent5f73f485563719e133c849c8dbd93877095d5ff5 (diff)
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>
Diffstat (limited to 'src/corelib/text')
-rw-r--r--src/corelib/text/qstring.cpp16
1 files changed, 16 insertions, 0 deletions
diff --git a/src/corelib/text/qstring.cpp b/src/corelib/text/qstring.cpp
index b6c36e1b2f..e0415d65e0 100644
--- a/src/corelib/text/qstring.cpp
+++ b/src/corelib/text/qstring.cpp
@@ -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());