Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qstring.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 The Qt Company Ltd.
2// Copyright (C) 2022 Intel Corporation.
3// Copyright (C) 2019 Mail.ru Group.
4// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
5// Qt-Security score:critical reason:data-parser
6
7#include "qstringlist.h"
8#if QT_CONFIG(regularexpression)
9#include "qregularexpression.h"
10#endif
12#include <private/qstringconverter_p.h>
13#include <private/qtools_p.h>
15#include "private/qsimd_p.h"
16#include <qnumeric.h>
17#include <qdatastream.h>
18#include <qlist.h>
19#include "qlocale.h"
20#include "qlocale_p.h"
21#include "qspan.h"
22#include "qstringbuilder.h"
23#include "qstringmatcher.h"
25#include "qdebug.h"
26#include "qendian.h"
27#include "qcollator.h"
28#include "qttypetraits.h"
29
30#ifdef Q_OS_DARWIN
31#include <private/qcore_mac_p.h>
32#endif
33
34#include <private/qfunctions_p.h>
35
36#include <limits.h>
37#include <string.h>
38#include <stdlib.h>
39#include <stdio.h>
40#include <stdarg.h>
41#include <wchar.h>
42
43#include "qchar.cpp"
48
49#include <algorithm>
50#include <functional>
51
52#ifdef Q_OS_WIN
53# include <qt_windows.h>
54# if !defined(QT_BOOTSTRAPPED) && (defined(QT_NO_CAST_FROM_ASCII) || defined(QT_NO_CAST_TO_ASCII))
55// MSVC requires this, but let's apply it to MinGW compilers too, just in case
56# error "This file cannot be compiled with QT_NO_CAST_{TO,FROM}_ASCII, "
57 "otherwise some QString functions will not get exported."
58# endif
59#endif
60
61#ifdef truncate
62# undef truncate
63#endif
64
65#define REHASH(a)
66 if (sl_minus_1 < sizeof(sl_minus_1) * CHAR_BIT)
67 hashHaystack -= decltype(hashHaystack)(a) << sl_minus_1;
68 hashHaystack <<= 1
69
71
72using namespace Qt::StringLiterals;
73using namespace QtMiscUtils;
74
75const char16_t QString::_empty = 0;
76
77// in qstringmatcher.cpp
78qsizetype qFindStringBoyerMoore(QStringView haystack, qsizetype from, QStringView needle, Qt::CaseSensitivity cs);
79
80namespace {
81enum StringComparisonMode {
82 CompareStringsForEquality,
83 CompareStringsForOrdering
84};
85
86template <typename Pointer>
87char32_t foldCaseHelper(Pointer ch, Pointer start) = delete;
88
89template <>
90char32_t foldCaseHelper<const QChar*>(const QChar* ch, const QChar* start)
91{
92 return foldCase(reinterpret_cast<const char16_t*>(ch),
93 reinterpret_cast<const char16_t*>(start));
94}
95
96template <>
97char32_t foldCaseHelper<const char*>(const char* ch, const char*)
98{
99 return foldCase(char16_t(uchar(*ch)));
100}
101
102template <typename T>
103char16_t valueTypeToUtf16(T t) = delete;
104
105template <>
106char16_t valueTypeToUtf16<QChar>(QChar t)
107{
108 return t.unicode();
109}
110
111template <>
112char16_t valueTypeToUtf16<char>(char t)
113{
114 return char16_t{uchar(t)};
115}
116
117template <typename T>
118static inline bool foldAndCompare(const T a, const T b)
119{
120 return foldCase(a) == b;
121}
122
123/*!
124 \internal
125
126 Returns the index position of the first occurrence of the
127 character \a ch in the string given by \a str and \a len,
128 searching forward from index
129 position \a from. Returns -1 if \a ch could not be found.
130*/
131template <typename Haystack>
132static inline qsizetype qLastIndexOf(Haystack haystack, QChar needle,
133 qsizetype from, Qt::CaseSensitivity cs) noexcept
134{
135 if (haystack.size() == 0)
136 return -1;
137 if (from < 0)
138 from += haystack.size();
139 else if (std::size_t(from) > std::size_t(haystack.size()))
140 from = haystack.size() - 1;
141 if (from >= 0) {
142 char16_t c = needle.unicode();
143 const auto b = haystack.data();
144 auto n = b + from;
145 if (cs == Qt::CaseSensitive) {
146 for (; n >= b; --n)
147 if (valueTypeToUtf16(*n) == c)
148 return n - b;
149 } else {
150 c = foldCase(c);
151 for (; n >= b; --n)
152 if (foldCase(valueTypeToUtf16(*n)) == c)
153 return n - b;
154 }
155 }
156 return -1;
157}
158template <> qsizetype
159qLastIndexOf(QString, QChar, qsizetype, Qt::CaseSensitivity) noexcept = delete; // unwanted, would detach
160
161template<typename Haystack, typename Needle>
162static qsizetype qLastIndexOf(Haystack haystack0, qsizetype from,
163 Needle needle0, Qt::CaseSensitivity cs) noexcept
164{
165 const qsizetype sl = needle0.size();
166 if (sl == 1)
167 return qLastIndexOf(haystack0, needle0.front(), from, cs);
168
169 const qsizetype l = haystack0.size();
170 if (from < 0)
171 from += l;
172 if (from == l && sl == 0)
173 return from;
174 const qsizetype delta = l - sl;
175 if (std::size_t(from) > std::size_t(l) || delta < 0)
176 return -1;
177 if (from > delta)
178 from = delta;
179
180 auto sv = [sl](const typename Haystack::value_type *v) { return Haystack(v, sl); };
181
182 auto haystack = haystack0.data();
183 const auto needle = needle0.data();
184 const auto *end = haystack;
185 haystack += from;
186 const qregisteruint sl_minus_1 = sl ? sl - 1 : 0;
187 const auto *n = needle + sl_minus_1;
188 const auto *h = haystack + sl_minus_1;
189 qregisteruint hashNeedle = 0, hashHaystack = 0;
190
191 if (cs == Qt::CaseSensitive) {
192 for (qsizetype idx = 0; idx < sl; ++idx) {
193 hashNeedle = (hashNeedle << 1) + valueTypeToUtf16(*(n - idx));
194 hashHaystack = (hashHaystack << 1) + valueTypeToUtf16(*(h - idx));
195 }
196 hashHaystack -= valueTypeToUtf16(*haystack);
197
198 while (haystack >= end) {
199 hashHaystack += valueTypeToUtf16(*haystack);
200 if (hashHaystack == hashNeedle
201 && QtPrivate::compareStrings(needle0, sv(haystack), Qt::CaseSensitive) == 0)
202 return haystack - end;
203 --haystack;
204 REHASH(valueTypeToUtf16(haystack[sl]));
205 }
206 } else {
207 for (qsizetype idx = 0; idx < sl; ++idx) {
208 hashNeedle = (hashNeedle << 1) + foldCaseHelper(n - idx, needle);
209 hashHaystack = (hashHaystack << 1) + foldCaseHelper(h - idx, end);
210 }
211 hashHaystack -= foldCaseHelper(haystack, end);
212
213 while (haystack >= end) {
214 hashHaystack += foldCaseHelper(haystack, end);
215 if (hashHaystack == hashNeedle
216 && QtPrivate::compareStrings(sv(haystack), needle0, Qt::CaseInsensitive) == 0)
217 return haystack - end;
218 --haystack;
219 REHASH(foldCaseHelper(haystack + sl, end));
220 }
221 }
222 return -1;
223}
224
225template <typename Haystack, typename Needle>
226bool qt_starts_with_impl(Haystack haystack, Needle needle, Qt::CaseSensitivity cs) noexcept
227{
228 if (haystack.isNull())
229 return needle.isNull();
230 const auto haystackLen = haystack.size();
231 const auto needleLen = needle.size();
232 if (haystackLen == 0)
233 return needleLen == 0;
234 if (needleLen > haystackLen)
235 return false;
236
237 return QtPrivate::compareStrings(haystack.first(needleLen), needle, cs) == 0;
238}
239
240template <typename Haystack, typename Needle>
241bool qt_ends_with_impl(Haystack haystack, Needle needle, Qt::CaseSensitivity cs) noexcept
242{
243 if (haystack.isNull())
244 return needle.isNull();
245 const auto haystackLen = haystack.size();
246 const auto needleLen = needle.size();
247 if (haystackLen == 0)
248 return needleLen == 0;
249 if (haystackLen < needleLen)
250 return false;
251
252 return QtPrivate::compareStrings(haystack.last(needleLen), needle, cs) == 0;
253}
254
255template <typename T>
256static void append_helper(QString &self, T view)
257{
258 const auto strData = view.data();
259 const qsizetype strSize = view.size();
260 auto &d = self.data_ptr();
261 if (strData && strSize > 0) {
262 // the number of UTF-8 code units is always at a minimum equal to the number
263 // of equivalent UTF-16 code units
264 d.detachAndGrow(QArrayData::GrowsAtEnd, strSize, nullptr, nullptr);
265 Q_CHECK_PTR(d.data());
266 Q_ASSERT(strSize <= d.freeSpaceAtEnd());
267
268 auto dst = std::next(d.data(), d.size);
269 if constexpr (std::is_same_v<T, QUtf8StringView>) {
270 dst = QUtf8::convertToUnicode(dst, view);
271 } else if constexpr (std::is_same_v<T, QLatin1StringView>) {
272 QLatin1::convertToUnicode(dst, view);
273 dst += strSize;
274 } else {
275 static_assert(QtPrivate::type_dependent_false<T>(),
276 "Can only operate on UTF-8 and Latin-1");
277 }
278 self.resize(std::distance(d.begin(), dst));
279 } else if (d.isNull() && !view.isNull()) { // special case
280 self = QLatin1StringView("");
281 }
282}
283
284template <uint MaxCount> struct UnrollTailLoop
285{
286 template <typename RetType, typename Functor1, typename Functor2, typename Number>
287 static inline RetType exec(Number count, RetType returnIfExited, Functor1 loopCheck, Functor2 returnIfFailed, Number i = 0)
288 {
289 /* equivalent to:
290 * while (count--) {
291 * if (loopCheck(i))
292 * return returnIfFailed(i);
293 * }
294 * return returnIfExited;
295 */
296
297 if (!count)
298 return returnIfExited;
299
300 bool check = loopCheck(i);
301 if (check)
302 return returnIfFailed(i);
303
304 return UnrollTailLoop<MaxCount - 1>::exec(count - 1, returnIfExited, loopCheck, returnIfFailed, i + 1);
305 }
306
307 template <typename Functor, typename Number>
308 static inline void exec(Number count, Functor code)
309 {
310 /* equivalent to:
311 * for (Number i = 0; i < count; ++i)
312 * code(i);
313 */
314 exec(count, 0, [=](Number i) -> bool { code(i); return false; }, [](Number) { return 0; });
315 }
316};
317template <> template <typename RetType, typename Functor1, typename Functor2, typename Number>
318inline RetType UnrollTailLoop<0>::exec(Number, RetType returnIfExited, Functor1, Functor2, Number)
319{
320 return returnIfExited;
321}
322} // unnamed namespace
323
324/*
325 * Note on the use of SIMD in qstring.cpp:
326 *
327 * Several operations with strings are improved with the use of SIMD code,
328 * since they are repetitive. For MIPS, we have hand-written assembly code
329 * outside of qstring.cpp targeting MIPS DSP and MIPS DSPr2. For ARM and for
330 * x86, we can only use intrinsics and therefore everything is contained in
331 * qstring.cpp. We need to use intrinsics only for those platforms due to the
332 * different compilers and toolchains used, which have different syntax for
333 * assembly sources.
334 *
335 * ** SSE notes: **
336 *
337 * Whenever multiple alternatives are equivalent or near so, we prefer the one
338 * using instructions from SSE2, since SSE2 is guaranteed to be enabled for all
339 * 64-bit builds and we enable it for 32-bit builds by default. Use of higher
340 * SSE versions should be done when there is a clear performance benefit and
341 * requires fallback code to SSE2, if it exists.
342 *
343 * Performance measurement in the past shows that most strings are short in
344 * size and, therefore, do not benefit from alignment prologues. That is,
345 * trying to find a 16-byte-aligned boundary to operate on is often more
346 * expensive than executing the unaligned operation directly. In addition, note
347 * that the QString private data is designed so that the data is stored on
348 * 16-byte boundaries if the system malloc() returns 16-byte aligned pointers
349 * on its own (64-bit glibc on Linux does; 32-bit glibc on Linux returns them
350 * 50% of the time), so skipping the alignment prologue is actually optimizing
351 * for the common case.
352 */
353
354#if defined(__mips_dsp)
355// From qstring_mips_dsp_asm.S
356extern "C" void qt_fromlatin1_mips_asm_unroll4 (char16_t*, const char*, uint);
357extern "C" void qt_fromlatin1_mips_asm_unroll8 (char16_t*, const char*, uint);
358extern "C" void qt_toLatin1_mips_dsp_asm(uchar *dst, const char16_t *src, int length);
359#endif
360
361#if defined(__SSE2__) && defined(Q_CC_GNU)
362// We may overrun the buffer, but that's a false positive:
363// this won't crash nor produce incorrect results
364# define ATTRIBUTE_NO_SANITIZE __attribute__((__no_sanitize_address__, __no_sanitize_thread__))
365#else
366# define ATTRIBUTE_NO_SANITIZE
367#endif
368
369#ifdef __SSE2__
370static constexpr bool UseSse4_1 = bool(qCompilerCpuFeatures & CpuFeatureSSE4_1);
371static constexpr bool UseAvx2 = UseSse4_1 &&
372 (qCompilerCpuFeatures & CpuFeatureArchHaswell) == CpuFeatureArchHaswell;
373
374[[maybe_unused]]
375Q_ALWAYS_INLINE static __m128i mm_load8_zero_extend(const void *ptr)
376{
377 const __m128i *dataptr = static_cast<const __m128i *>(ptr);
378 if constexpr (UseSse4_1) {
379 // use a MOVQ followed by PMOVZXBW
380 // if AVX2 is present, these should combine into a single VPMOVZXBW instruction
381 __m128i data = _mm_loadl_epi64(dataptr);
382 return _mm_cvtepu8_epi16(data);
383 }
384
385 // use MOVQ followed by PUNPCKLBW
386 __m128i data = _mm_loadl_epi64(dataptr);
387 return _mm_unpacklo_epi8(data, _mm_setzero_si128());
388}
389
390[[maybe_unused]] ATTRIBUTE_NO_SANITIZE
391static qsizetype qustrlen_sse2(const char16_t *str) noexcept
392{
393 // find the 16-byte alignment immediately prior or equal to str
394 quintptr misalignment = quintptr(str) & 0xf;
395 Q_ASSERT((misalignment & 1) == 0);
396 const char16_t *ptr = str - (misalignment / 2);
397
398 // load 16 bytes and see if we have a null
399 // (aligned loads can never segfault)
400 const __m128i zeroes = _mm_setzero_si128();
401 __m128i data = _mm_load_si128(reinterpret_cast<const __m128i *>(ptr));
402 __m128i comparison = _mm_cmpeq_epi16(data, zeroes);
403 uint mask = _mm_movemask_epi8(comparison);
404
405 // ignore the result prior to the beginning of str
406 mask >>= misalignment;
407
408 // Have we found something in the first block? Need to handle it now
409 // because of the left shift above.
410 if (mask)
411 return qCountTrailingZeroBits(mask) / sizeof(char16_t);
412
413 constexpr qsizetype Step = sizeof(__m128i) / sizeof(char16_t);
414 qsizetype size = Step - misalignment / sizeof(char16_t);
415
416 size -= Step;
417 do {
418 size += Step;
419 data = _mm_load_si128(reinterpret_cast<const __m128i *>(str + size));
420
421 comparison = _mm_cmpeq_epi16(data, zeroes);
422 mask = _mm_movemask_epi8(comparison);
423 } while (mask == 0);
424
425 // found a null
426 return size + qCountTrailingZeroBits(mask) / sizeof(char16_t);
427}
428
429// Scans from \a ptr to \a end until \a maskval is non-zero. Returns true if
430// the no non-zero was found. Returns false and updates \a ptr to point to the
431// first 16-bit word that has any bit set (note: if the input is 8-bit, \a ptr
432// may be updated to one byte short).
433static bool simdTestMask(const char *&ptr, const char *end, quint32 maskval)
434{
435 auto updatePtr = [&](uint result) {
436 // found a character matching the mask
437 uint idx = qCountTrailingZeroBits(~result);
438 ptr += idx;
439 return false;
440 };
441
442 if constexpr (UseSse4_1) {
443# ifndef Q_OS_QNX // compiler fails in the code below
444 __m128i mask;
445 auto updatePtrSimd = [&](__m128i data) -> bool {
446 __m128i masked = _mm_and_si128(mask, data);
447 __m128i comparison = _mm_cmpeq_epi16(masked, _mm_setzero_si128());
448 uint result = _mm_movemask_epi8(comparison);
449 return updatePtr(result);
450 };
451
452 if constexpr (UseAvx2) {
453 // AVX2 implementation: test 32 bytes at a time
454 const __m256i mask256 = _mm256_broadcastd_epi32(_mm_cvtsi32_si128(maskval));
455 while (ptr + 32 <= end) {
456 __m256i data = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(ptr));
457 if (!_mm256_testz_si256(mask256, data)) {
458 // found a character matching the mask
459 __m256i masked256 = _mm256_and_si256(mask256, data);
460 __m256i comparison256 = _mm256_cmpeq_epi16(masked256, _mm256_setzero_si256());
461 return updatePtr(_mm256_movemask_epi8(comparison256));
462 }
463 ptr += 32;
464 }
465
466 mask = _mm256_castsi256_si128(mask256);
467 } else {
468 // SSE 4.1 implementation: test 32 bytes at a time (two 16-byte
469 // comparisons, unrolled)
470 mask = _mm_set1_epi32(maskval);
471 while (ptr + 32 <= end) {
472 __m128i data1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(ptr));
473 __m128i data2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(ptr + 16));
474 if (!_mm_testz_si128(mask, data1))
475 return updatePtrSimd(data1);
476
477 ptr += 16;
478 if (!_mm_testz_si128(mask, data2))
479 return updatePtrSimd(data2);
480 ptr += 16;
481 }
482 }
483
484 // AVX2 and SSE4.1: final 16-byte comparison
485 if (ptr + 16 <= end) {
486 __m128i data1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(ptr));
487 if (!_mm_testz_si128(mask, data1))
488 return updatePtrSimd(data1);
489 ptr += 16;
490 }
491
492 // and final 8-byte comparison
493 if (ptr + 8 <= end) {
494 __m128i data1 = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(ptr));
495 if (!_mm_testz_si128(mask, data1))
496 return updatePtrSimd(data1);
497 ptr += 8;
498 }
499
500 return true;
501# endif // QNX
502 }
503
504 // SSE2 implementation: test 16 bytes at a time.
505 const __m128i mask = _mm_set1_epi32(maskval);
506 while (ptr + 16 <= end) {
507 __m128i data = _mm_loadu_si128(reinterpret_cast<const __m128i *>(ptr));
508 __m128i masked = _mm_and_si128(mask, data);
509 __m128i comparison = _mm_cmpeq_epi16(masked, _mm_setzero_si128());
510 quint16 result = _mm_movemask_epi8(comparison);
511 if (result != 0xffff)
512 return updatePtr(result);
513 ptr += 16;
514 }
515
516 // and one 8-byte comparison
517 if (ptr + 8 <= end) {
518 __m128i data = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(ptr));
519 __m128i masked = _mm_and_si128(mask, data);
520 __m128i comparison = _mm_cmpeq_epi16(masked, _mm_setzero_si128());
521 quint8 result = _mm_movemask_epi8(comparison);
522 if (result != 0xff)
523 return updatePtr(result);
524 ptr += 8;
525 }
526
527 return true;
528}
529
530template <StringComparisonMode Mode, typename Char> [[maybe_unused]]
531static int ucstrncmp_sse2(const char16_t *a, const Char *b, size_t l)
532{
533 static_assert(std::is_unsigned_v<Char>);
534
535 // Using the PMOVMSKB instruction, we get two bits for each UTF-16 character
536 // we compare. This lambda helps extract the code unit.
537 static const auto codeUnitAt = [](const auto *n, qptrdiff idx) -> int {
538 constexpr int Stride = 2;
539 // this is the same as:
540 // return n[idx / Stride];
541 // but using pointer arithmetic to avoid the compiler dividing by two
542 // and multiplying by two in the case of char16_t (we know idx is even,
543 // but the compiler does not). This is not UB.
544
545 auto ptr = reinterpret_cast<const uchar *>(n);
546 ptr += idx / (Stride / sizeof(*n));
547 return *reinterpret_cast<decltype(n)>(ptr);
548 };
549 auto difference = [a, b](uint mask, qptrdiff offset) {
550 if (Mode == CompareStringsForEquality)
551 return 1;
552 uint idx = qCountTrailingZeroBits(mask);
553 return codeUnitAt(a + offset, idx) - codeUnitAt(b + offset, idx);
554 };
555
556 static const auto load8Chars = [](const auto *ptr) {
557 if (sizeof(*ptr) == 2)
558 return _mm_loadu_si128(reinterpret_cast<const __m128i *>(ptr));
559 __m128i chunk = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(ptr));
560 return _mm_unpacklo_epi8(chunk, _mm_setzero_si128());
561 };
562 static const auto load4Chars = [](const auto *ptr) {
563 if (sizeof(*ptr) == 2)
564 return _mm_loadl_epi64(reinterpret_cast<const __m128i *>(ptr));
565 __m128i chunk = _mm_cvtsi32_si128(qFromUnaligned<quint32>(ptr));
566 return _mm_unpacklo_epi8(chunk, _mm_setzero_si128());
567 };
568
569 // we're going to read a[0..15] and b[0..15] (32 bytes)
570 auto processChunk16Chars = [a, b](qptrdiff offset) -> uint {
571 if constexpr (UseAvx2) {
572 __m256i a_data = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(a + offset));
573 __m256i b_data;
574 if (sizeof(Char) == 1) {
575 // expand to UTF-16 via zero-extension
576 __m128i chunk = _mm_loadu_si128(reinterpret_cast<const __m128i *>(b + offset));
577 b_data = _mm256_cvtepu8_epi16(chunk);
578 } else {
579 b_data = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(b + offset));
580 }
581 __m256i result = _mm256_cmpeq_epi16(a_data, b_data);
582 return _mm256_movemask_epi8(result);
583 }
584
585 __m128i a_data1 = load8Chars(a + offset);
586 __m128i a_data2 = load8Chars(a + offset + 8);
587 __m128i b_data1, b_data2;
588 if (sizeof(Char) == 1) {
589 // expand to UTF-16 via unpacking
590 __m128i b_data = _mm_loadu_si128(reinterpret_cast<const __m128i *>(b + offset));
591 b_data1 = _mm_unpacklo_epi8(b_data, _mm_setzero_si128());
592 b_data2 = _mm_unpackhi_epi8(b_data, _mm_setzero_si128());
593 } else {
594 b_data1 = load8Chars(b + offset);
595 b_data2 = load8Chars(b + offset + 8);
596 }
597 __m128i result1 = _mm_cmpeq_epi16(a_data1, b_data1);
598 __m128i result2 = _mm_cmpeq_epi16(a_data2, b_data2);
599 return _mm_movemask_epi8(result1) | _mm_movemask_epi8(result2) << 16;
600 };
601
602 if (l >= sizeof(__m256i) / sizeof(char16_t)) {
603 qptrdiff offset = 0;
604 for ( ; l >= offset + sizeof(__m256i) / sizeof(char16_t); offset += sizeof(__m256i) / sizeof(char16_t)) {
605 uint mask = ~processChunk16Chars(offset);
606 if (mask)
607 return difference(mask, offset);
608 }
609
610 // maybe overlap the last 32 bytes
611 if (size_t(offset) < l) {
612 offset = l - sizeof(__m256i) / sizeof(char16_t);
613 uint mask = ~processChunk16Chars(offset);
614 return mask ? difference(mask, offset) : 0;
615 }
616 } else if (l >= 4) {
617 __m128i a_data1, b_data1;
618 __m128i a_data2, b_data2;
619 int width;
620 if (l >= 8) {
621 width = 8;
622 a_data1 = load8Chars(a);
623 b_data1 = load8Chars(b);
624 a_data2 = load8Chars(a + l - width);
625 b_data2 = load8Chars(b + l - width);
626 } else {
627 // we're going to read a[0..3] and b[0..3] (8 bytes)
628 width = 4;
629 a_data1 = load4Chars(a);
630 b_data1 = load4Chars(b);
631 a_data2 = load4Chars(a + l - width);
632 b_data2 = load4Chars(b + l - width);
633 }
634
635 __m128i result = _mm_cmpeq_epi16(a_data1, b_data1);
636 ushort mask = ~_mm_movemask_epi8(result);
637 if (mask)
638 return difference(mask, 0);
639
640 result = _mm_cmpeq_epi16(a_data2, b_data2);
641 mask = ~_mm_movemask_epi8(result);
642 if (mask)
643 return difference(mask, l - width);
644 } else {
645 // reset l
646 l &= 3;
647
648 const auto lambda = [=](size_t i) -> int {
649 return a[i] - b[i];
650 };
651 return UnrollTailLoop<3>::exec(l, 0, lambda, lambda);
652 }
653 return 0;
654}
655#endif
656
657Q_NEVER_INLINE
658qsizetype QtPrivate::qustrlen(const char16_t *str) noexcept
659{
660#if defined(__SSE2__) && !(defined(__SANITIZE_ADDRESS__) || __has_feature(address_sanitizer)) && !(defined(__SANITIZE_THREAD__) || __has_feature(thread_sanitizer))
661 return qustrlen_sse2(str);
662#endif
663
664 if (sizeof(wchar_t) == sizeof(char16_t))
665 return wcslen(reinterpret_cast<const wchar_t *>(str));
666
667 qsizetype result = 0;
668 while (*str++)
669 ++result;
670 return result;
671}
672
673qsizetype QtPrivate::qustrnlen(const char16_t *str, qsizetype maxlen) noexcept
674{
675 return qustrchr({ str, maxlen }, u'\0') - str;
676}
677
678/*!
679 * \internal
680 *
681 * Searches for character \a c in the string \a str and returns a pointer to
682 * it. Unlike strchr() and wcschr() (but like glibc's strchrnul()), if the
683 * character is not found, this function returns a pointer to the end of the
684 * string -- that is, \c{str.end()}.
685 */
687const char16_t *QtPrivate::qustrchr(QStringView str, char16_t c) noexcept
688{
689 const char16_t *n = str.utf16();
690 const char16_t *e = n + str.size();
691
692#ifdef __SSE2__
693 bool loops = true;
694 // Using the PMOVMSKB instruction, we get two bits for each character
695 // we compare.
696 __m128i mch;
697 if constexpr (UseAvx2) {
698 // we're going to read n[0..15] (32 bytes)
699 __m256i mch256 = _mm256_set1_epi32(c | (c << 16));
700 for (const char16_t *next = n + 16; next <= e; n = next, next += 16) {
701 __m256i data = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(n));
702 __m256i result = _mm256_cmpeq_epi16(data, mch256);
703 uint mask = uint(_mm256_movemask_epi8(result));
704 if (mask) {
705 uint idx = qCountTrailingZeroBits(mask);
706 return n + idx / 2;
707 }
708 }
709 loops = false;
710 mch = _mm256_castsi256_si128(mch256);
711 } else {
712 mch = _mm_set1_epi32(c | (c << 16));
713 }
714
715 auto hasMatch = [mch, &n](__m128i data, ushort validityMask) {
716 __m128i result = _mm_cmpeq_epi16(data, mch);
717 uint mask = uint(_mm_movemask_epi8(result));
718 if ((mask & validityMask) == 0)
719 return false;
720 uint idx = qCountTrailingZeroBits(mask);
721 n += idx / 2;
722 return true;
723 };
724
725 // we're going to read n[0..7] (16 bytes)
726 for (const char16_t *next = n + 8; next <= e; n = next, next += 8) {
727 __m128i data = _mm_loadu_si128(reinterpret_cast<const __m128i *>(n));
728 if (hasMatch(data, 0xffff))
729 return n;
730
731 if (!loops) {
732 n += 8;
733 break;
734 }
735 }
736
737# if !defined(__OPTIMIZE_SIZE__)
738 // we're going to read n[0..3] (8 bytes)
739 if (e - n > 3) {
740 __m128i data = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(n));
741 if (hasMatch(data, 0xff))
742 return n;
743
744 n += 4;
745 }
746
747 return UnrollTailLoop<3>::exec(e - n, e,
748 [=](qsizetype i) { return n[i] == c; },
749 [=](qsizetype i) { return n + i; });
750# endif
751#elif defined(__ARM_NEON__)
752 const uint16x8_t vmask = qvsetq_n_u16(1, 1 << 1, 1 << 2, 1 << 3, 1 << 4, 1 << 5, 1 << 6, 1 << 7);
753 const uint16x8_t ch_vec = vdupq_n_u16(c);
754 for (const char16_t *next = n + 8; next <= e; n = next, next += 8) {
755 uint16x8_t data = vld1q_u16(reinterpret_cast<const uint16_t *>(n));
756 uint mask = vaddvq_u16(vandq_u16(vceqq_u16(data, ch_vec), vmask));
757 if (ushort(mask)) {
758 // found a match
759 return n + qCountTrailingZeroBits(mask);
760 }
761 }
762#endif // aarch64
763
764 return std::find(n, e, c);
765}
766
767/*!
768 * \internal
769 *
770 * Searches case-insensitively for character \a c in the string \a str and
771 * returns a pointer to it. Iif the character is not found, this function
772 * returns a pointer to the end of the string -- that is, \c{str.end()}.
773 */
775const char16_t *QtPrivate::qustrcasechr(QStringView str, char16_t c) noexcept
776{
777 const QChar *n = str.begin();
778 const QChar *e = str.end();
779 c = foldCase(c);
780 auto it = std::find_if(n, e, [c](auto ch) { return foldAndCompare(ch, QChar(c)); });
781 return reinterpret_cast<const char16_t *>(it);
782}
783
784// Note: ptr on output may be off by one and point to a preceding US-ASCII
785// character. Usually harmless.
786bool qt_is_ascii(const char *&ptr, const char *end) noexcept
787{
788#if defined(__SSE2__)
789 // Testing for the high bit can be done efficiently with just PMOVMSKB
790 bool loops = true;
791 if constexpr (UseAvx2) {
792 while (ptr + 32 <= end) {
793 __m256i data = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(ptr));
794 quint32 mask = _mm256_movemask_epi8(data);
795 if (mask) {
796 uint idx = qCountTrailingZeroBits(mask);
797 ptr += idx;
798 return false;
799 }
800 ptr += 32;
801 }
802 loops = false;
803 }
804
805 while (ptr + 16 <= end) {
806 __m128i data = _mm_loadu_si128(reinterpret_cast<const __m128i *>(ptr));
807 quint32 mask = _mm_movemask_epi8(data);
808 if (mask) {
809 uint idx = qCountTrailingZeroBits(mask);
810 ptr += idx;
811 return false;
812 }
813 ptr += 16;
814
815 if (!loops)
816 break;
817 }
818 if (ptr + 8 <= end) {
819 __m128i data = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(ptr));
820 quint8 mask = _mm_movemask_epi8(data);
821 if (mask) {
822 uint idx = qCountTrailingZeroBits(mask);
823 ptr += idx;
824 return false;
825 }
826 ptr += 8;
827 }
828#endif
829
830 while (ptr + 4 <= end) {
831 quint32 data = qFromUnaligned<quint32>(ptr);
832 if (data &= 0x80808080U) {
833 uint idx = QSysInfo::ByteOrder == QSysInfo::BigEndian
834 ? qCountLeadingZeroBits(data)
835 : qCountTrailingZeroBits(data);
836 ptr += idx / 8;
837 return false;
838 }
839 ptr += 4;
840 }
841
842 while (ptr != end) {
843 if (quint8(*ptr) & 0x80)
844 return false;
845 ++ptr;
846 }
847 return true;
848}
849
850bool QtPrivate::isAscii(QLatin1StringView s) noexcept
851{
852 const char *ptr = s.begin();
853 const char *end = s.end();
854
855 return qt_is_ascii(ptr, end);
856}
857
858static bool isAscii_helper(const char16_t *&ptr, const char16_t *end)
859{
860#ifdef __SSE2__
861 const char *ptr8 = reinterpret_cast<const char *>(ptr);
862 const char *end8 = reinterpret_cast<const char *>(end);
863 bool ok = simdTestMask(ptr8, end8, 0xff80ff80);
864 ptr = reinterpret_cast<const char16_t *>(ptr8);
865 if (!ok)
866 return false;
867#endif
868
869 while (ptr != end) {
870 if (*ptr & 0xff80)
871 return false;
872 ++ptr;
873 }
874 return true;
875}
876
877bool QtPrivate::isAscii(QStringView s) noexcept
878{
879 const char16_t *ptr = s.utf16();
880 const char16_t *end = ptr + s.size();
881
882 return isAscii_helper(ptr, end);
883}
884
885bool QtPrivate::isLatin1(QStringView s) noexcept
886{
887 const char16_t *ptr = s.utf16();
888 const char16_t *end = ptr + s.size();
889
890#ifdef __SSE2__
891 const char *ptr8 = reinterpret_cast<const char *>(ptr);
892 const char *end8 = reinterpret_cast<const char *>(end);
893 if (!simdTestMask(ptr8, end8, 0xff00ff00))
894 return false;
895 ptr = reinterpret_cast<const char16_t *>(ptr8);
896#endif
897
898 while (ptr != end) {
899 if (*ptr++ > 0xff)
900 return false;
901 }
902 return true;
903}
904
905bool QtPrivate::isValidUtf16(QStringView s) noexcept
906{
907 constexpr char32_t InvalidCodePoint = UINT_MAX;
908
909 QStringIterator i(s);
910 while (i.hasNext()) {
911 const char32_t c = i.next(InvalidCodePoint);
912 if (c == InvalidCodePoint)
913 return false;
914 }
915
916 return true;
917}
918
919// conversion between Latin 1 and UTF-16
920Q_CORE_EXPORT void qt_from_latin1(char16_t *dst, const char *str, size_t size) noexcept
921{
922 /* SIMD:
923 * Unpacking with SSE has been shown to improve performance on recent CPUs
924 * The same method gives no improvement with NEON. On Aarch64, clang will do the vectorization
925 * itself in exactly the same way as one would do it with intrinsics.
926 */
927#if defined(__SSE2__)
928 // we're going to read str[offset..offset+15] (16 bytes)
929 const __m128i nullMask = _mm_setzero_si128();
930 auto processOneChunk = [=](qptrdiff offset) {
931 const __m128i chunk = _mm_loadu_si128((const __m128i*)(str + offset)); // load
932 if constexpr (UseAvx2) {
933 // zero extend to an YMM register
934 const __m256i extended = _mm256_cvtepu8_epi16(chunk);
935
936 // store
937 _mm256_storeu_si256((__m256i*)(dst + offset), extended);
938 } else {
939 // unpack the first 8 bytes, padding with zeros
940 const __m128i firstHalf = _mm_unpacklo_epi8(chunk, nullMask);
941 _mm_storeu_si128((__m128i*)(dst + offset), firstHalf); // store
942
943 // unpack the last 8 bytes, padding with zeros
944 const __m128i secondHalf = _mm_unpackhi_epi8 (chunk, nullMask);
945 _mm_storeu_si128((__m128i*)(dst + offset + 8), secondHalf); // store
946 }
947 };
948
949 const char *e = str + size;
950 if (size >= sizeof(__m128i)) {
951 qptrdiff offset = 0;
952 for ( ; str + offset + sizeof(__m128i) <= e; offset += sizeof(__m128i))
953 processOneChunk(offset);
954 if (str + offset < e)
955 processOneChunk(size - sizeof(__m128i));
956 return;
957 }
958
959# if !defined(__OPTIMIZE_SIZE__)
960 if (size >= 4) {
961 // two overlapped loads & stores, of either 64-bit or of 32-bit
962 if (size >= 8) {
963 const __m128i unpacked1 = mm_load8_zero_extend(str);
964 const __m128i unpacked2 = mm_load8_zero_extend(str + size - 8);
965 _mm_storeu_si128(reinterpret_cast<__m128i *>(dst), unpacked1);
966 _mm_storeu_si128(reinterpret_cast<__m128i *>(dst + size - 8), unpacked2);
967 } else {
968 const __m128i chunk1 = _mm_cvtsi32_si128(qFromUnaligned<quint32>(str));
969 const __m128i chunk2 = _mm_cvtsi32_si128(qFromUnaligned<quint32>(str + size - 4));
970 const __m128i unpacked1 = _mm_unpacklo_epi8(chunk1, nullMask);
971 const __m128i unpacked2 = _mm_unpacklo_epi8(chunk2, nullMask);
972 _mm_storel_epi64(reinterpret_cast<__m128i *>(dst), unpacked1);
973 _mm_storel_epi64(reinterpret_cast<__m128i *>(dst + size - 4), unpacked2);
974 }
975 return;
976 } else {
977 size = size % 4;
978 return UnrollTailLoop<3>::exec(qsizetype(size), [=](qsizetype i) { dst[i] = uchar(str[i]); });
979 }
980# endif
981#endif
982#if defined(__mips_dsp)
983 static_assert(sizeof(qsizetype) == sizeof(int),
984 "oops, the assembler implementation needs to be called in a loop");
985 if (size > 20)
986 qt_fromlatin1_mips_asm_unroll8(dst, str, size);
987 else
988 qt_fromlatin1_mips_asm_unroll4(dst, str, size);
989#else
990 while (size--)
991 *dst++ = (uchar)*str++;
992#endif
993}
994
995static QVarLengthArray<char16_t> qt_from_latin1_to_qvla(QLatin1StringView str)
996{
997 const qsizetype len = str.size();
998 QVarLengthArray<char16_t> arr(len);
999 qt_from_latin1(arr.data(), str.data(), len);
1000 return arr;
1001}
1002
1003template <bool Checked>
1004static void qt_to_latin1_internal(uchar *dst, const char16_t *src, qsizetype length)
1005{
1006#if defined(__SSE2__)
1007 auto questionMark256 = []() {
1008 if constexpr (UseAvx2)
1009 return _mm256_broadcastw_epi16(_mm_cvtsi32_si128('?'));
1010 else
1011 return 0;
1012 }();
1013 auto outOfRange256 = []() {
1014 if constexpr (UseAvx2)
1015 return _mm256_broadcastw_epi16(_mm_cvtsi32_si128(0x100));
1016 else
1017 return 0;
1018 }();
1019 __m128i questionMark, outOfRange;
1020 if constexpr (UseAvx2) {
1021 questionMark = _mm256_castsi256_si128(questionMark256);
1022 outOfRange = _mm256_castsi256_si128(outOfRange256);
1023 } else {
1024 questionMark = _mm_set1_epi16('?');
1025 outOfRange = _mm_set1_epi16(0x100);
1026 }
1027
1028 auto mergeQuestionMarks = [=](__m128i chunk) {
1029 if (!Checked)
1030 return chunk;
1031
1032 // SSE has no compare instruction for unsigned comparison.
1033 if constexpr (UseSse4_1) {
1034 // We use an unsigned uc = qMin(uc, 0x100) and then compare for equality.
1035 chunk = _mm_min_epu16(chunk, outOfRange);
1036 const __m128i offLimitMask = _mm_cmpeq_epi16(chunk, outOfRange);
1037 chunk = _mm_blendv_epi8(chunk, questionMark, offLimitMask);
1038 return chunk;
1039 }
1040 // The variables must be shiffted + 0x8000 to be compared
1041 const __m128i signedBitOffset = _mm_set1_epi16(short(0x8000));
1042 const __m128i thresholdMask = _mm_set1_epi16(short(0xff + 0x8000));
1043
1044 const __m128i signedChunk = _mm_add_epi16(chunk, signedBitOffset);
1045 const __m128i offLimitMask = _mm_cmpgt_epi16(signedChunk, thresholdMask);
1046
1047 // offLimitQuestionMark contains '?' for each 16 bits that was off-limit
1048 // the 16 bits that were correct contains zeros
1049 const __m128i offLimitQuestionMark = _mm_and_si128(offLimitMask, questionMark);
1050
1051 // correctBytes contains the bytes that were in limit
1052 // the 16 bits that were off limits contains zeros
1053 const __m128i correctBytes = _mm_andnot_si128(offLimitMask, chunk);
1054
1055 // merge offLimitQuestionMark and correctBytes to have the result
1056 chunk = _mm_or_si128(correctBytes, offLimitQuestionMark);
1057
1058 Q_UNUSED(outOfRange);
1059 return chunk;
1060 };
1061
1062 // we're going to read to src[offset..offset+15] (16 bytes)
1063 auto loadChunkAt = [=](qptrdiff offset) {
1064 __m128i chunk1, chunk2;
1065 if constexpr (UseAvx2) {
1066 __m256i chunk = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(src + offset));
1067 if (Checked) {
1068 // See mergeQuestionMarks lambda above for details
1069 chunk = _mm256_min_epu16(chunk, outOfRange256);
1070 const __m256i offLimitMask = _mm256_cmpeq_epi16(chunk, outOfRange256);
1071 chunk = _mm256_blendv_epi8(chunk, questionMark256, offLimitMask);
1072 }
1073
1074 chunk2 = _mm256_extracti128_si256(chunk, 1);
1075 chunk1 = _mm256_castsi256_si128(chunk);
1076 } else {
1077 chunk1 = _mm_loadu_si128((const __m128i*)(src + offset)); // load
1078 chunk1 = mergeQuestionMarks(chunk1);
1079
1080 chunk2 = _mm_loadu_si128((const __m128i*)(src + offset + 8)); // load
1081 chunk2 = mergeQuestionMarks(chunk2);
1082 }
1083
1084 // pack the two vector to 16 x 8bits elements
1085 return _mm_packus_epi16(chunk1, chunk2);
1086 };
1087
1088 if (size_t(length) >= sizeof(__m128i)) {
1089 // because of possible overlapping, we won't process the last chunk in the loop
1090 qptrdiff offset = 0;
1091 for ( ; offset + 2 * sizeof(__m128i) < size_t(length); offset += sizeof(__m128i))
1092 _mm_storeu_si128(reinterpret_cast<__m128i *>(dst + offset), loadChunkAt(offset));
1093
1094 // overlapped conversion of the last full chunk and the tail
1095 __m128i last1 = loadChunkAt(offset);
1096 __m128i last2 = loadChunkAt(length - sizeof(__m128i));
1097 _mm_storeu_si128(reinterpret_cast<__m128i *>(dst + offset), last1);
1098 _mm_storeu_si128(reinterpret_cast<__m128i *>(dst + length - sizeof(__m128i)), last2);
1099 return;
1100 }
1101
1102# if !defined(__OPTIMIZE_SIZE__)
1103 if (length >= 4) {
1104 // this code is fine even for in-place conversion because we load both
1105 // before any store
1106 if (length >= 8) {
1107 __m128i chunk1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(src));
1108 __m128i chunk2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(src + length - 8));
1109 chunk1 = mergeQuestionMarks(chunk1);
1110 chunk2 = mergeQuestionMarks(chunk2);
1111
1112 // pack, where the upper half is ignored
1113 const __m128i result1 = _mm_packus_epi16(chunk1, chunk1);
1114 const __m128i result2 = _mm_packus_epi16(chunk2, chunk2);
1115 _mm_storel_epi64(reinterpret_cast<__m128i *>(dst), result1);
1116 _mm_storel_epi64(reinterpret_cast<__m128i *>(dst + length - 8), result2);
1117 } else {
1118 __m128i chunk1 = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(src));
1119 __m128i chunk2 = _mm_loadl_epi64(reinterpret_cast<const __m128i *>(src + length - 4));
1120 chunk1 = mergeQuestionMarks(chunk1);
1121 chunk2 = mergeQuestionMarks(chunk2);
1122
1123 // pack, we'll zero the upper three quarters
1124 const __m128i result1 = _mm_packus_epi16(chunk1, chunk1);
1125 const __m128i result2 = _mm_packus_epi16(chunk2, chunk2);
1126 qToUnaligned(_mm_cvtsi128_si32(result1), dst);
1127 qToUnaligned(_mm_cvtsi128_si32(result2), dst + length - 4);
1128 }
1129 return;
1130 }
1131
1132 length = length % 4;
1133 return UnrollTailLoop<3>::exec(length, [=](qsizetype i) {
1134 if (Checked)
1135 dst[i] = (src[i]>0xff) ? '?' : (uchar) src[i];
1136 else
1137 dst[i] = src[i];
1138 });
1139# else
1140 length = length % 16;
1141# endif // optimize size
1142#elif defined(__ARM_NEON__)
1143 // Refer to the documentation of the SSE2 implementation.
1144 // This uses exactly the same method as for SSE except:
1145 // 1) neon has unsigned comparison
1146 // 2) packing is done to 64 bits (8 x 8bits component).
1147 if (length >= 16) {
1148 const qsizetype chunkCount = length >> 3; // divided by 8
1149 const uint16x8_t questionMark = vdupq_n_u16('?'); // set
1150 const uint16x8_t thresholdMask = vdupq_n_u16(0xff); // set
1151 for (qsizetype i = 0; i < chunkCount; ++i) {
1152 uint16x8_t chunk = vld1q_u16((uint16_t *)src); // load
1153 src += 8;
1154
1155 if (Checked) {
1156 const uint16x8_t offLimitMask = vcgtq_u16(chunk, thresholdMask); // chunk > thresholdMask
1157 const uint16x8_t offLimitQuestionMark = vandq_u16(offLimitMask, questionMark); // offLimitMask & questionMark
1158 const uint16x8_t correctBytes = vbicq_u16(chunk, offLimitMask); // !offLimitMask & chunk
1159 chunk = vorrq_u16(correctBytes, offLimitQuestionMark); // correctBytes | offLimitQuestionMark
1160 }
1161 const uint8x8_t result = vmovn_u16(chunk); // narrowing move->packing
1162 vst1_u8(dst, result); // store
1163 dst += 8;
1164 }
1165 length = length % 8;
1166 }
1167#endif
1168#if defined(__mips_dsp)
1169 static_assert(sizeof(qsizetype) == sizeof(int),
1170 "oops, the assembler implementation needs to be called in a loop");
1171 qt_toLatin1_mips_dsp_asm(dst, src, length);
1172#else
1173 while (length--) {
1174 if (Checked)
1175 *dst++ = (*src>0xff) ? '?' : (uchar) *src;
1176 else
1177 *dst++ = *src;
1178 ++src;
1179 }
1180#endif
1181}
1182
1183void qt_to_latin1(uchar *dst, const char16_t *src, qsizetype length)
1184{
1185 qt_to_latin1_internal<true>(dst, src, length);
1186}
1187
1188void qt_to_latin1_unchecked(uchar *dst, const char16_t *src, qsizetype length)
1189{
1190 qt_to_latin1_internal<false>(dst, src, length);
1191}
1192
1193// Unicode case-insensitive comparison (argument order matches QStringView)
1194Q_NEVER_INLINE static int ucstricmp(qsizetype alen, const char16_t *a, qsizetype blen, const char16_t *b)
1195{
1196 if (a == b)
1197 return qt_lencmp(alen, blen);
1198
1199 qsizetype l = qMin(alen, blen);
1200 qsizetype i;
1201 for (i = 0; i < l; ++i) {
1202// qDebug() << Qt::hex << alast << blast;
1203// qDebug() << Qt::hex << "*a=" << *a << "alast=" << alast << "folded=" << foldCase (*a, alast);
1204// qDebug() << Qt::hex << "*b=" << *b << "blast=" << blast << "folded=" << foldCase (*b, blast);
1205 int diff = foldCase(a + i, a) - foldCase(b + i, b);
1206 if ((diff))
1207 return diff;
1208 }
1209 if (i == alen) {
1210 if (i == blen)
1211 return 0;
1212 return -1;
1213 }
1214 return 1;
1215}
1216
1217// Case-insensitive comparison between a QStringView and a QLatin1StringView
1218// (argument order matches those types)
1219Q_NEVER_INLINE static int ucstricmp(qsizetype alen, const char16_t *a, qsizetype blen, const char *b)
1220{
1221 qsizetype l = qMin(alen, blen);
1222 qsizetype i;
1223 for (i = 0; i < l; ++i) {
1224 int diff = foldCase(a[i]) - foldCase(char16_t{uchar(b[i])});
1225 if ((diff))
1226 return diff;
1227 }
1228 if (i == alen) {
1229 if (i == blen)
1230 return 0;
1231 return -1;
1232 }
1233 return 1;
1234}
1235
1236// Case-insensitive comparison between a Unicode string and a UTF-8 string
1237Q_NEVER_INLINE static int ucstricmp8(const char *utf8, const char *utf8end, const QChar *utf16, const QChar *utf16end)
1238{
1239 auto src1 = reinterpret_cast<const qchar8_t *>(utf8);
1240 auto end1 = reinterpret_cast<const qchar8_t *>(utf8end);
1241 QStringIterator src2(utf16, utf16end);
1242
1243 while (src1 < end1 && src2.hasNext()) {
1244 char32_t uc1 = QChar::toCaseFolded(QUtf8Functions::nextUcs4FromUtf8(src1, end1));
1245 char32_t uc2 = QChar::toCaseFolded(src2.next());
1246 int diff = uc1 - uc2; // can't underflow
1247 if (diff)
1248 return diff;
1249 }
1250
1251 // the shorter string sorts first
1252 return (end1 > src1) - int(src2.hasNext());
1253}
1254
1255#if defined(__mips_dsp)
1256// From qstring_mips_dsp_asm.S
1257extern "C" int qt_ucstrncmp_mips_dsp_asm(const char16_t *a,
1258 const char16_t *b,
1259 unsigned len);
1260#endif
1261
1262// Unicode case-sensitive compare two same-sized strings
1263template <StringComparisonMode Mode>
1264static int ucstrncmp(const char16_t *a, const char16_t *b, size_t l)
1265{
1266 // This function isn't memcmp() because that can return the wrong sorting
1267 // result in little-endian architectures: 0x00ff must sort before 0x0100,
1268 // but the bytes in memory are FF 00 and 00 01.
1269
1270#ifndef __OPTIMIZE_SIZE__
1271# if defined(__mips_dsp)
1272 static_assert(sizeof(uint) == sizeof(size_t));
1273 if (l >= 8) {
1274 return qt_ucstrncmp_mips_dsp_asm(a, b, l);
1275 }
1276# elif defined(__SSE2__)
1277 return ucstrncmp_sse2<Mode>(a, b, l);
1278# elif defined(__ARM_NEON__)
1279 if (l >= 8) {
1280 const char16_t *end = a + l;
1281 const uint16x8_t mask = qvsetq_n_u16( 1, 1 << 1, 1 << 2, 1 << 3, 1 << 4, 1 << 5, 1 << 6, 1 << 7 );
1282 while (end - a > 7) {
1283 uint16x8_t da = vld1q_u16(reinterpret_cast<const uint16_t *>(a));
1284 uint16x8_t db = vld1q_u16(reinterpret_cast<const uint16_t *>(b));
1285
1286 uint8_t r = ~(uint8_t)vaddvq_u16(vandq_u16(vceqq_u16(da, db), mask));
1287 if (r) {
1288 // found a different QChar
1289 if (Mode == CompareStringsForEquality)
1290 return 1;
1291 uint idx = qCountTrailingZeroBits(r);
1292 return a[idx] - b[idx];
1293 }
1294 a += 8;
1295 b += 8;
1296 }
1297 l &= 7;
1298 }
1299 const auto lambda = [=](size_t i) -> int {
1300 return a[i] - b[i];
1301 };
1302 return UnrollTailLoop<7>::exec(l, 0, lambda, lambda);
1303# endif // MIPS DSP or __SSE2__ or __ARM_NEON__
1304#endif // __OPTIMIZE_SIZE__
1305
1306 if (Mode == CompareStringsForEquality || QSysInfo::ByteOrder == QSysInfo::BigEndian)
1307 return memcmp(a, b, l * sizeof(char16_t));
1308
1309 for (size_t i = 0; i < l; ++i) {
1310 if (int diff = a[i] - b[i])
1311 return diff;
1312 }
1313 return 0;
1314}
1315
1316template <StringComparisonMode Mode>
1317static int ucstrncmp(const char16_t *a, const char *b, size_t l)
1318{
1319 const uchar *c = reinterpret_cast<const uchar *>(b);
1320 const char16_t *uc = a;
1321 const char16_t *e = uc + l;
1322
1323#if defined(__SSE2__) && !defined(__OPTIMIZE_SIZE__)
1324 return ucstrncmp_sse2<Mode>(uc, c, l);
1325#endif
1326
1327 while (uc < e) {
1328 int diff = *uc - *c;
1329 if (diff)
1330 return diff;
1331 uc++, c++;
1332 }
1333
1334 return 0;
1335}
1336
1337// Unicode case-sensitive equality
1338template <typename Char2>
1339static bool ucstreq(const char16_t *a, size_t alen, const Char2 *b)
1340{
1341 return ucstrncmp<CompareStringsForEquality>(a, b, alen) == 0;
1342}
1343
1344// Unicode case-sensitive comparison
1345template <typename Char2>
1346static int ucstrcmp(const char16_t *a, size_t alen, const Char2 *b, size_t blen)
1347{
1348 const size_t l = qMin(alen, blen);
1349 int cmp = ucstrncmp<CompareStringsForOrdering>(a, b, l);
1350 return cmp ? cmp : qt_lencmp(alen, blen);
1351}
1352
1354
1355static int latin1nicmp(const char *lhsChar, qsizetype lSize, const char *rhsChar, qsizetype rSize)
1356{
1357 // We're called with QLatin1StringView's .data() and .size():
1358 Q_ASSERT(lSize >= 0 && rSize >= 0);
1359 if (!lSize)
1360 return rSize ? -1 : 0;
1361 if (!rSize)
1362 return 1;
1363 const qsizetype size = std::min(lSize, rSize);
1364
1365 Q_ASSERT(lhsChar && rhsChar); // since both lSize and rSize are positive
1366 for (qsizetype i = 0; i < size; i++) {
1367 if (int res = CaseInsensitiveL1::difference(lhsChar[i], rhsChar[i]))
1368 return res;
1369 }
1370 return qt_lencmp(lSize, rSize);
1371}
1372
1373bool QtPrivate::equalStrings(QStringView lhs, QStringView rhs) noexcept
1374{
1375 Q_ASSERT(lhs.size() == rhs.size());
1376 return ucstreq(lhs.utf16(), lhs.size(), rhs.utf16());
1377}
1378
1379bool QtPrivate::equalStrings(QStringView lhs, QLatin1StringView rhs) noexcept
1380{
1381 Q_ASSERT(lhs.size() == rhs.size());
1382 return ucstreq(lhs.utf16(), lhs.size(), rhs.latin1());
1383}
1384
1385bool QtPrivate::equalStrings(QLatin1StringView lhs, QStringView rhs) noexcept
1386{
1387 return QtPrivate::equalStrings(rhs, lhs);
1388}
1389
1390bool QtPrivate::equalStrings(QLatin1StringView lhs, QLatin1StringView rhs) noexcept
1391{
1392 Q_ASSERT(lhs.size() == rhs.size());
1393 return (!lhs.size() || memcmp(lhs.data(), rhs.data(), lhs.size()) == 0);
1394}
1395
1396bool QtPrivate::equalStrings(QBasicUtf8StringView<false> lhs, QStringView rhs) noexcept
1397{
1398 return QUtf8::compareUtf8(lhs, rhs) == 0;
1399}
1400
1401bool QtPrivate::equalStrings(QStringView lhs, QBasicUtf8StringView<false> rhs) noexcept
1402{
1403 return QtPrivate::equalStrings(rhs, lhs);
1404}
1405
1406bool QtPrivate::equalStrings(QLatin1StringView lhs, QBasicUtf8StringView<false> rhs) noexcept
1407{
1408 return QUtf8::compareUtf8(QByteArrayView(rhs), lhs) == 0;
1409}
1410
1411bool QtPrivate::equalStrings(QBasicUtf8StringView<false> lhs, QLatin1StringView rhs) noexcept
1412{
1413 return QtPrivate::equalStrings(rhs, lhs);
1414}
1415
1416bool QtPrivate::equalStrings(QBasicUtf8StringView<false> lhs, QBasicUtf8StringView<false> rhs) noexcept
1417{
1418#if QT_VERSION >= QT_VERSION_CHECK(7, 0, 0) || defined(QT_BOOTSTRAPPED) || defined(QT_STATIC)
1419 Q_ASSERT(lhs.size() == rhs.size());
1420#else
1421 // operator== didn't enforce size prior to Qt 6.2
1422 if (lhs.size() != rhs.size())
1423 return false;
1424#endif
1425 return (!lhs.size() || memcmp(lhs.data(), rhs.data(), lhs.size()) == 0);
1426}
1427
1428bool QAnyStringView::equal(QAnyStringView lhs, QAnyStringView rhs) noexcept
1429{
1430 if (lhs.size() != rhs.size() && lhs.isUtf8() == rhs.isUtf8())
1431 return false;
1432 return lhs.visit([rhs](auto lhs) {
1433 return rhs.visit([lhs](auto rhs) {
1434 return QtPrivate::equalStrings(lhs, rhs);
1435 });
1436 });
1437}
1438
1439/*!
1440 \relates QStringView
1441 \internal
1442 \since 5.10
1443
1444 Returns an integer that compares to 0 as \a lhs compares to \a rhs.
1445
1446 \include qstring.qdocinc {search-comparison-case-sensitivity} {comparison}
1447
1448 Case-sensitive comparison is based exclusively on the numeric Unicode values
1449 of the characters and is very fast, but is not what a human would expect.
1450 Consider sorting user-visible strings with QString::localeAwareCompare().
1451
1452 \sa {Comparing Strings}
1453*/
1454int QtPrivate::compareStrings(QStringView lhs, QStringView rhs, Qt::CaseSensitivity cs) noexcept
1455{
1456 if (cs == Qt::CaseSensitive)
1457 return ucstrcmp(lhs.utf16(), lhs.size(), rhs.utf16(), rhs.size());
1458 return ucstricmp(lhs.size(), lhs.utf16(), rhs.size(), rhs.utf16());
1459}
1460
1461/*!
1462 \relates QStringView
1463 \internal
1464 \since 5.10
1465 \overload
1466
1467 Returns an integer that compares to 0 as \a lhs compares to \a rhs.
1468
1469 \include qstring.qdocinc {search-comparison-case-sensitivity} {comparison}
1470
1471 Case-sensitive comparison is based exclusively on the numeric Unicode values
1472 of the characters and is very fast, but is not what a human would expect.
1473 Consider sorting user-visible strings with QString::localeAwareCompare().
1474
1475 \sa {Comparing Strings}
1476*/
1477int QtPrivate::compareStrings(QStringView lhs, QLatin1StringView rhs, Qt::CaseSensitivity cs) noexcept
1478{
1479 if (cs == Qt::CaseSensitive)
1480 return ucstrcmp(lhs.utf16(), lhs.size(), rhs.latin1(), rhs.size());
1481 return ucstricmp(lhs.size(), lhs.utf16(), rhs.size(), rhs.latin1());
1482}
1483
1484/*!
1485 \relates QStringView
1486 \internal
1487 \since 6.0
1488 \overload
1489*/
1490int QtPrivate::compareStrings(QStringView lhs, QBasicUtf8StringView<false> rhs, Qt::CaseSensitivity cs) noexcept
1491{
1492 return -compareStrings(rhs, lhs, cs);
1493}
1494
1495/*!
1496 \relates QStringView
1497 \internal
1498 \since 5.10
1499 \overload
1500*/
1501int QtPrivate::compareStrings(QLatin1StringView lhs, QStringView rhs, Qt::CaseSensitivity cs) noexcept
1502{
1503 return -compareStrings(rhs, lhs, cs);
1504}
1505
1506/*!
1507 \relates QStringView
1508 \internal
1509 \since 5.10
1510 \overload
1511
1512 Returns an integer that compares to 0 as \a lhs compares to \a rhs.
1513
1514 \include qstring.qdocinc {search-comparison-case-sensitivity} {comparison}
1515
1516 Case-sensitive comparison is based exclusively on the numeric Latin-1 values
1517 of the characters and is very fast, but is not what a human would expect.
1518 Consider sorting user-visible strings with QString::localeAwareCompare().
1519
1520 \sa {Comparing Strings}
1521*/
1522int QtPrivate::compareStrings(QLatin1StringView lhs, QLatin1StringView rhs, Qt::CaseSensitivity cs) noexcept
1523{
1524 if (lhs.isEmpty())
1525 return qt_lencmp(qsizetype(0), rhs.size());
1526 if (rhs.isEmpty())
1527 return qt_lencmp(lhs.size(), qsizetype(0));
1528 if (cs == Qt::CaseInsensitive)
1529 return latin1nicmp(lhs.data(), lhs.size(), rhs.data(), rhs.size());
1530 const auto l = std::min(lhs.size(), rhs.size());
1531 int r = memcmp(lhs.data(), rhs.data(), l);
1532 return r ? r : qt_lencmp(lhs.size(), rhs.size());
1533}
1534
1535/*!
1536 \relates QStringView
1537 \internal
1538 \since 6.0
1539 \overload
1540*/
1541int QtPrivate::compareStrings(QLatin1StringView lhs, QBasicUtf8StringView<false> rhs, Qt::CaseSensitivity cs) noexcept
1542{
1543 return -QUtf8::compareUtf8(QByteArrayView(rhs), lhs, cs);
1544}
1545
1546/*!
1547 \relates QStringView
1548 \internal
1549 \since 6.0
1550 \overload
1551*/
1552int QtPrivate::compareStrings(QBasicUtf8StringView<false> lhs, QStringView rhs, Qt::CaseSensitivity cs) noexcept
1553{
1554 if (cs == Qt::CaseSensitive)
1555 return QUtf8::compareUtf8(lhs, rhs);
1556 return ucstricmp8(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
1557}
1558
1559/*!
1560 \relates QStringView
1561 \internal
1562 \since 6.0
1563 \overload
1564*/
1565int QtPrivate::compareStrings(QBasicUtf8StringView<false> lhs, QLatin1StringView rhs, Qt::CaseSensitivity cs) noexcept
1566{
1567 return -compareStrings(rhs, lhs, cs);
1568}
1569
1570/*!
1571 \relates QStringView
1572 \internal
1573 \since 6.0
1574 \overload
1575*/
1576int QtPrivate::compareStrings(QBasicUtf8StringView<false> lhs, QBasicUtf8StringView<false> rhs, Qt::CaseSensitivity cs) noexcept
1577{
1578 return QUtf8::compareUtf8(QByteArrayView(lhs), QByteArrayView(rhs), cs);
1579}
1580
1581int QAnyStringView::compare(QAnyStringView lhs, QAnyStringView rhs, Qt::CaseSensitivity cs) noexcept
1582{
1583 return lhs.visit([rhs, cs](auto lhs) {
1584 return rhs.visit([lhs, cs](auto rhs) {
1585 return QtPrivate::compareStrings(lhs, rhs, cs);
1586 });
1587 });
1588}
1589
1590// ### Qt 7: do not allow anything but ASCII digits
1591// in arg()'s replacements.
1592#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0) && !defined(QT_BOOTSTRAPPED)
1593static bool supportUnicodeDigitValuesInArg()
1594{
1595 static const bool result = []() {
1596 static const char supportUnicodeDigitValuesEnvVar[]
1597 = "QT_USE_UNICODE_DIGIT_VALUES_IN_STRING_ARG";
1598
1599 if (qEnvironmentVariableIsSet(supportUnicodeDigitValuesEnvVar))
1600 return qEnvironmentVariableIntValue(supportUnicodeDigitValuesEnvVar) != 0;
1601
1602#if QT_VERSION < QT_VERSION_CHECK(6, 6, 0) // keep it in sync with the test
1603 return true;
1604#else
1605 return false;
1606#endif
1607 }();
1608
1609 return result;
1610}
1611#endif
1612
1613static int qArgDigitValue(QChar ch) noexcept
1614{
1615#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0) && !defined(QT_BOOTSTRAPPED)
1616 if (supportUnicodeDigitValuesInArg())
1617 return ch.digitValue();
1618#endif
1619 if (ch >= u'0' && ch <= u'9')
1620 return int(ch.unicode() - u'0');
1621 return -1;
1622}
1623
1624#if QT_CONFIG(regularexpression)
1625Q_DECL_COLD_FUNCTION
1626static void qtWarnAboutInvalidRegularExpression(const QRegularExpression &re, const char *cls, const char *method)
1627{
1628 extern void qtWarnAboutInvalidRegularExpression(const QString &pattern, const char *cls, const char *method);
1629 qtWarnAboutInvalidRegularExpression(re.pattern(), cls, method);
1630}
1631#endif
1632
1633/*!
1634 \macro QT_RESTRICTED_CAST_FROM_ASCII
1635 \relates QString
1636
1637 Disables most automatic conversions from source literals and 8-bit data
1638 to unicode QStrings, but allows the use of
1639 the \c{QChar(char)} and \c{QString(const char (&ch)[N]} constructors,
1640 and the \c{QString::operator=(const char (&ch)[N])} assignment operator.
1641 This gives most of the type-safety benefits of \l QT_NO_CAST_FROM_ASCII
1642 but does not require user code to wrap character and string literals
1643 with QLatin1Char, QLatin1StringView or similar.
1644
1645 Using this macro together with source strings outside the 7-bit range,
1646 non-literals, or literals with embedded NUL characters is undefined.
1647
1648 \sa QT_NO_CAST_FROM_ASCII, QT_NO_CAST_TO_ASCII
1649*/
1650
1651/*!
1652 \macro QT_NO_CAST_FROM_ASCII
1653 \relates QString
1654 \relates QChar
1655
1656 Disables automatic conversions from 8-bit strings (\c{char *}) to Unicode
1657 QStrings, as well as from 8-bit \c{char} types (\c{char} and
1658 \c{unsigned char}) to QChar.
1659
1660 \sa QT_NO_CAST_TO_ASCII, QT_RESTRICTED_CAST_FROM_ASCII,
1661 QT_NO_CAST_FROM_BYTEARRAY
1662*/
1663
1664/*!
1665 \macro QT_NO_CAST_TO_ASCII
1666 \relates QString
1667
1668 Disables automatic conversion from QString to 8-bit strings (\c{char *}).
1669
1670 \sa QT_NO_CAST_FROM_ASCII, QT_RESTRICTED_CAST_FROM_ASCII,
1671 QT_NO_CAST_FROM_BYTEARRAY
1672*/
1673
1674/*!
1675 \macro QT_ASCII_CAST_WARNINGS
1676 \internal
1677 \relates QString
1678
1679 This macro can be defined to force a warning whenever a function is
1680 called that automatically converts between unicode and 8-bit encodings.
1681
1682 Note: This only works for compilers that support warnings for
1683 deprecated API.
1684
1685 \sa QT_NO_CAST_TO_ASCII, QT_NO_CAST_FROM_ASCII, QT_RESTRICTED_CAST_FROM_ASCII
1686*/
1687
1688/*!
1689 \class QString
1690 \inmodule QtCore
1691 \reentrant
1692
1693 \brief The QString class provides a Unicode character string.
1694
1695 \ingroup tools
1696 \ingroup shared
1697 \ingroup string-processing
1698
1699 \compares strong
1700 \compareswith strong QChar QLatin1StringView {const char16_t *} \
1701 QStringView QUtf8StringView
1702 \endcompareswith
1703 \compareswith strong QByteArray QByteArrayView {const char *}
1704 When comparing with byte arrays, their content is interpreted as UTF-8.
1705 \endcompareswith
1706
1707 QString stores a string of 16-bit \l{QChar}s, where each QChar
1708 corresponds to one UTF-16 code unit. (Unicode characters
1709 with code values above 65535 are stored using surrogate pairs,
1710 that is, two consecutive \l{QChar}s.)
1711
1712 \l{Unicode} is an international standard that supports most of the
1713 writing systems in use today. It is a superset of US-ASCII (ANSI
1714 X3.4-1986) and Latin-1 (ISO 8859-1), and all the US-ASCII/Latin-1
1715 characters are available at the same code positions.
1716
1717 Behind the scenes, QString uses \l{implicit sharing}
1718 (copy-on-write) to reduce memory usage and to avoid the needless
1719 copying of data. This also helps reduce the inherent overhead of
1720 storing 16-bit characters instead of 8-bit characters.
1721
1722 In addition to QString, Qt also provides the QByteArray class to
1723 store raw bytes and traditional 8-bit '\\0'-terminated strings.
1724 For most purposes, QString is the class you want to use. It is
1725 used throughout the Qt API, and the Unicode support ensures that
1726 your applications are easy to translate if you want to expand
1727 your application's market at some point. Two prominent cases
1728 where QByteArray is appropriate are when you need to store raw
1729 binary data, and when memory conservation is critical (like in
1730 embedded systems).
1731
1732 \section1 Initializing a string
1733
1734 One way to initialize a QString is to pass a \c{const char
1735 *} to its constructor. For example, the following code creates a
1736 QString of size 5 containing the data "Hello":
1737
1738 \snippet qstring/main.cpp 0
1739
1740 QString converts the \c{const char *} data into Unicode using the
1741 fromUtf8() function.
1742
1743 In all of the QString functions that take \c{const char *}
1744 parameters, the \c{const char *} is interpreted as a classic
1745 C-style \c{'\\0'}-terminated string. Except where the function's
1746 name overtly indicates some other encoding, such \c{const char *}
1747 parameters are assumed to be encoded in UTF-8.
1748
1749 Since Qt 6.4, it is also possible to initialize QStrings using
1750 the \l {Qt::Literals::StringLiterals::operator""_s()} and
1751 \l {Qt::Literals::StringLiterals::operator""_L1()} literal
1752 operators. In many cases, using the literals results in
1753 \l{More efficient string construction}{more efficient string construction}.
1754
1755
1756 You can also provide string data as an array of \l{QChar}s:
1757
1758 \snippet qstring/main.cpp 1
1759
1760 QString makes a deep copy of the QChar data, so you can modify it
1761 later without experiencing side effects. You can avoid taking a
1762 deep copy of the character data by using QStringView or
1763 QString::fromRawData() instead.
1764
1765 Another approach is to set the size of the string using resize()
1766 and to initialize the data character per character. QString uses
1767 0-based indexes, just like C++ arrays. To access the character at
1768 a particular index position, you can use \l operator[](). On
1769 non-\c{const} strings, \l operator[]() returns a reference to a
1770 character that can be used on the left side of an assignment. For
1771 example:
1772
1773 \snippet qstring/main.cpp 2
1774
1775 For read-only access, an alternative syntax is to use the at()
1776 function:
1777
1778 \snippet qstring/main.cpp 3
1779
1780 The at() function can be faster than \l operator[]() because it
1781 never causes a \l{deep copy} to occur. Alternatively, use the
1782 first(), last(), or sliced() functions to extract several characters
1783 at a time.
1784
1785 A QString can embed '\\0' characters (QChar::Null). The size()
1786 function always returns the size of the whole string, including
1787 embedded '\\0' characters.
1788
1789 After a call to the resize() function, newly allocated characters
1790 have undefined values. To set all the characters in the string to
1791 a particular value, use the fill() function.
1792
1793 QString provides dozens of overloads designed to simplify string
1794 usage. For example, if you want to compare a QString with a string
1795 literal, you can write code like this and it will work as expected:
1796
1797 \snippet qstring/main.cpp 4
1798
1799 You can also pass string literals to functions that take QStrings
1800 as arguments, invoking the QString(const char *)
1801 constructor. Similarly, you can pass a QString to a function that
1802 takes a \c{const char *} argument using the \l qPrintable() macro,
1803 which returns the given QString as a \c{const char *}. This is
1804 equivalent to calling toLocal8Bit().\l{QByteArray::}{constData()}
1805 on the QString.
1806
1807 \section1 Manipulating string data
1808
1809 QString provides the following basic functions for modifying the
1810 character data: append(), prepend(), insert(), replace(), and
1811 remove(). For example:
1812
1813 \snippet qstring/main.cpp 5
1814
1815 In the above example, the replace() function's first two arguments are the
1816 position from which to start replacing and the number of characters that
1817 should be replaced.
1818
1819 When data-modifying functions increase the size of the string,
1820 QString may reallocate the memory in which it holds its data. When
1821 this happens, QString expands by more than it immediately needs so as
1822 to have space for further expansion without reallocation until the size
1823 of the string has significantly increased.
1824
1825 The insert(), remove(), and, when replacing a sub-string with one of
1826 different size, replace() functions can be slow (\l{linear time}) for
1827 large strings because they require moving many characters in the string
1828 by at least one position in memory.
1829
1830 If you are building a QString gradually and know in advance
1831 approximately how many characters the QString will contain, you
1832 can call reserve(), asking QString to preallocate a certain amount
1833 of memory. You can also call capacity() to find out how much
1834 memory the QString actually has allocated.
1835
1836 QString provides \l{STL-style iterators} (QString::const_iterator and
1837 QString::iterator). In practice, iterators are handy when working with
1838 generic algorithms provided by the C++ standard library.
1839
1840 \note Iterators over a QString, and references to individual characters
1841 within one, cannot be relied on to remain valid when any non-\c{const}
1842 method of the QString is called. Accessing such an iterator or reference
1843 after the call to a non-\c{const} method leads to undefined behavior. When
1844 stability for iterator-like functionality is required, you should use
1845 indexes instead of iterators, as they are not tied to QString's internal
1846 state and thus do not get invalidated.
1847
1848 \note Due to \l{implicit sharing}, the first non-\c{const} operator or
1849 function used on a given QString may cause it to internally perform a deep
1850 copy of its data. This invalidates all iterators over the string and
1851 references to individual characters within it. Do not call non-const
1852 functions while keeping iterators. Accessing an iterator or reference
1853 after it has been invalidated leads to undefined behavior. See the
1854 \l{Implicit sharing iterator problem} section for more information.
1855
1856 A frequent requirement is to remove or simplify the spacing between
1857 visible characters in a string. The characters that make up that spacing
1858 are those for which \l {QChar::}{isSpace()} returns \c true, such as
1859 the simple space \c{' '}, the horizontal tab \c{'\\t'} and the newline \c{'\\n'}.
1860 To obtain a copy of a string leaving out any spacing from its start and end,
1861 use \l trimmed(). To also replace each sequence of spacing characters within
1862 the string with a simple space, \c{' '}, use \l simplified().
1863
1864 If you want to find all occurrences of a particular character or
1865 substring in a QString, use the indexOf() or lastIndexOf()
1866 functions.The former searches forward, the latter searches backward.
1867 Either can be told an index position from which to start their search.
1868 Each returns the index position of the character or substring if they
1869 find it; otherwise, they return -1. For example, here is a typical loop
1870 that finds all occurrences of a particular substring:
1871
1872 \snippet qstring/main.cpp 6
1873
1874 QString provides many functions for converting numbers into
1875 strings and strings into numbers. See the arg() functions, the
1876 setNum() functions, the number() static functions, and the
1877 toInt(), toDouble(), and similar functions.
1878
1879 To get an uppercase or lowercase version of a string, use toUpper() or
1880 toLower().
1881
1882 Lists of strings are handled by the QStringList class. You can
1883 split a string into a list of strings using the split() function,
1884 and join a list of strings into a single string with an optional
1885 separator using QStringList::join(). You can obtain a filtered list
1886 from a string list by selecting the entries in it that contain a
1887 particular substring or match a particular QRegularExpression.
1888 See QStringList::filter() for details.
1889
1890 \section1 Querying string data
1891
1892 To see if a QString starts or ends with a particular substring, use
1893 startsWith() or endsWith(). To check whether a QString contains a
1894 specific character or substring, use the contains() function. To
1895 find out how many times a particular character or substring occurs
1896 in a string, use count().
1897
1898 To obtain a pointer to the actual character data, call data() or
1899 constData(). These functions return a pointer to the beginning of
1900 the QChar data. The pointer is guaranteed to remain valid until a
1901 non-\c{const} function is called on the QString.
1902
1903 \section2 Comparing strings
1904
1905 QStrings can be compared using overloaded operators such as \l
1906 operator<(), \l operator<=(), \l operator==(), \l operator>=(),
1907 and so on. The comparison is based exclusively on the lexicographical
1908 order of the two strings, seen as sequences of UTF-16 code units.
1909 It is very fast but is not what a human would expect; the
1910 QString::localeAwareCompare() function is usually a better choice for
1911 sorting user-interface strings, when such a comparison is available.
1912
1913 When Qt is linked with the ICU library (which it usually is), its
1914 locale-aware sorting is used. Otherwise, platform-specific solutions
1915 are used:
1916 \list
1917 \li On Windows, localeAwareCompare() uses the current user locale,
1918 as set in the \uicontrol{regional} and \uicontrol{language}
1919 options portion of \uicontrol{Control Panel}.
1920 \li On \macos and iOS, \l localeAwareCompare() compares according
1921 to the \uicontrol{Order for sorted lists} setting in the
1922 \uicontrol{International preferences} panel.
1923 \li On other Unix-like systems, the comparison falls back to the
1924 system library's \c strcoll().
1925 \endlist
1926
1927 \section1 Converting between encoded string data and QString
1928
1929 QString provides the following functions that return a
1930 \c{const char *} version of the string as QByteArray: toUtf8(),
1931 toLatin1(), and toLocal8Bit().
1932
1933 \list
1934 \li toLatin1() returns a Latin-1 (ISO 8859-1) encoded 8-bit string.
1935 \li toUtf8() returns a UTF-8 encoded 8-bit string. UTF-8 is a
1936 superset of US-ASCII (ANSI X3.4-1986) that supports the entire
1937 Unicode character set through multibyte sequences.
1938 \li toLocal8Bit() returns an 8-bit string using the system's local
1939 encoding. This is the same as toUtf8() on Unix systems.
1940 \endlist
1941
1942 To convert from one of these encodings, QString provides
1943 fromLatin1(), fromUtf8(), and fromLocal8Bit(). Other
1944 encodings are supported through the QStringEncoder and QStringDecoder
1945 classes.
1946
1947 As mentioned above, QString provides a lot of functions and
1948 operators that make it easy to interoperate with \c{const char *}
1949 strings. But this functionality is a double-edged sword: It makes
1950 QString more convenient to use if all strings are US-ASCII or
1951 Latin-1, but there is always the risk that an implicit conversion
1952 from or to \c{const char *} is done using the wrong 8-bit
1953 encoding. To minimize these risks, you can turn off these implicit
1954 conversions by defining some of the following preprocessor symbols:
1955
1956 \list
1957 \li \l QT_NO_CAST_FROM_ASCII disables automatic conversions from
1958 C string literals and pointers to Unicode.
1959 \li \l QT_RESTRICTED_CAST_FROM_ASCII allows automatic conversions
1960 from C characters and character arrays but disables automatic
1961 conversions from character pointers to Unicode.
1962 \li \l QT_NO_CAST_TO_ASCII disables automatic conversion from QString
1963 to C strings.
1964 \endlist
1965
1966 You then need to explicitly call fromUtf8(), fromLatin1(),
1967 or fromLocal8Bit() to construct a QString from an
1968 8-bit string, or use the lightweight QLatin1StringView class. For
1969 example:
1970
1971 \snippet code/src_corelib_text_qstring.cpp 1
1972
1973 Similarly, you must call toLatin1(), toUtf8(), or
1974 toLocal8Bit() explicitly to convert the QString to an 8-bit
1975 string.
1976
1977 \table 100 %
1978 \header
1979 \li Note for C Programmers
1980
1981 \row
1982 \li
1983 Due to C++'s type system and the fact that QString is
1984 \l{implicitly shared}, QStrings may be treated like \c{int}s or
1985 other basic types. For example:
1986
1987 \snippet qstring/main.cpp 7
1988
1989 The \c result variable is a normal variable allocated on the
1990 stack. When \c return is called, and because we're returning by
1991 value, the copy constructor is called and a copy of the string is
1992 returned. No actual copying takes place thanks to the implicit
1993 sharing.
1994
1995 \endtable
1996
1997 \section1 Distinction between null and empty strings
1998
1999 For historical reasons, QString distinguishes between null
2000 and empty strings. A \e null string is a string that is
2001 initialized using QString's default constructor or by passing
2002 \nullptr to the constructor. An \e empty string is any
2003 string with size 0. A null string is always empty, but an empty
2004 string isn't necessarily null:
2005
2006 \snippet qstring/main.cpp 8
2007
2008 All functions except isNull() treat null strings the same as empty
2009 strings. For example, toUtf8().\l{QByteArray::}{constData()} returns a valid pointer
2010 (not \nullptr) to a '\\0' character for a null string. We
2011 recommend that you always use the isEmpty() function and avoid isNull().
2012
2013 \section1 Number formats
2014
2015 When a QString::arg() \c{'%'} format specifier includes the \c{'L'} locale
2016 qualifier, and the base is ten (its default), the default locale is
2017 used. This can be set using \l{QLocale::setDefault()}. For more refined
2018 control of localized string representations of numbers, see
2019 QLocale::toString(). All other number formatting done by QString follows the
2020 C locale's representation of numbers.
2021
2022 When QString::arg() applies left-padding to numbers, the fill character
2023 \c{'0'} is treated specially. If the number is negative, its minus sign
2024 appears before the zero-padding. If the field is localized, the
2025 locale-appropriate zero character is used in place of \c{'0'}. For
2026 floating-point numbers, this special treatment only applies if the number is
2027 finite.
2028
2029 \section2 Floating-point formats
2030
2031 In member functions (for example, arg() and number()) that format floating-point
2032 numbers (\c float or \c double) as strings, the representation used can be
2033 controlled by a choice of \e format and \e precision, whose meanings are as
2034 for \l {QLocale::toString(double, char, int)}.
2035
2036 If the selected \e format includes an exponent, localized forms follow the
2037 locale's convention on digits in the exponent. For non-localized formatting,
2038 the exponent shows its sign and includes at least two digits, left-padding
2039 with zero if needed.
2040
2041 \section1 More efficient string construction
2042
2043 Many strings are known at compile time. The QString constructor from
2044 C++ string literals will copy the contents of the string,
2045 treating the contents as UTF-8. This requires memory allocation and
2046 re-encoding string data, operations that will happen at runtime.
2047 If the string data is known at compile time, you can use the QStringLiteral
2048 macro or similarly \c{operator""_s} to create QString's payload at compile
2049 time instead.
2050
2051 Using the QString \c{'+'} operator, it is easy to construct a
2052 complex string from multiple substrings. You will often write code
2053 like this:
2054
2055 \snippet qstring/stringbuilder.cpp 0
2056
2057 There is nothing wrong with either of these string constructions,
2058 but there are a few hidden inefficiencies:
2059
2060 First, repeated use of the \c{'+'} operator may lead to
2061 multiple memory allocations. When concatenating \e{n} substrings,
2062 where \e{n > 2}, there can be as many as \e{n - 1} calls to the
2063 memory allocator.
2064
2065 These allocations can be optimized by an internal class
2066 \c{QStringBuilder}. This class is marked
2067 internal and does not appear in the documentation, because you
2068 aren't meant to instantiate it in your code. Its use will be
2069 automatic, as described below.
2070
2071 \c{QStringBuilder} uses expression templates and reimplements the
2072 \c{'%'} operator so that when you use \c{'%'} for string
2073 concatenation instead of \c{'+'}, multiple substring
2074 concatenations will be postponed until the final result is about
2075 to be assigned to a QString. At this point, the amount of memory
2076 required for the final result is known. The memory allocator is
2077 then called \e{once} to get the required space, and the substrings
2078 are copied into it one by one.
2079
2080 Additional efficiency is gained by inlining and reducing reference
2081 counting (the QString created from a \c{QStringBuilder}
2082 has a ref count of 1, whereas QString::append() needs an extra
2083 test).
2084
2085 There are two ways you can access this improved method of string
2086 construction. The straightforward way is to include
2087 \c{QStringBuilder} wherever you want to use it and use the
2088 \c{'%'} operator instead of \c{'+'} when concatenating strings:
2089
2090 \snippet qstring/stringbuilder.cpp 5
2091
2092 A more global approach, which is more convenient but not entirely
2093 source-compatible, is to define \c QT_USE_QSTRINGBUILDER (by adding
2094 it to the compiler flags) at build time. This will make concatenating
2095 strings with \c{'+'} work the same way as \c{QStringBuilder's} \c{'%'}.
2096
2097 \note Using automatic type deduction (for example, by using the \c
2098 auto keyword) with the result of string concatenation when QStringBuilder
2099 is enabled will show that the concatenation is indeed an object of a
2100 QStringBuilder specialization:
2101
2102 \snippet qstring/stringbuilder.cpp 6
2103
2104 This does not cause any harm, as QStringBuilder will implicitly convert to
2105 QString when required. If this is undesirable, then one should specify
2106 the necessary types instead of having the compiler deduce them:
2107
2108 \snippet qstring/stringbuilder.cpp 7
2109
2110 \section1 Maximum size and out-of-memory conditions
2111
2112 The maximum size of QString depends on the architecture. Most 64-bit
2113 systems can allocate more than 2 GB of memory, with a typical limit
2114 of 2^63 bytes. The actual value also depends on the overhead required for
2115 managing the data block. As a result, you can expect a maximum size
2116 of 2 GB minus overhead on 32-bit platforms and 2^63 bytes minus overhead
2117 on 64-bit platforms. The number of elements that can be stored in a
2118 QString is this maximum size divided by the size of QChar.
2119
2120 When memory allocation fails, QString throws a \c std::bad_alloc
2121 exception if the application was compiled with exception support.
2122 Out-of-memory conditions in Qt containers are the only cases where Qt
2123 will throw exceptions. If exceptions are disabled, then running out of
2124 memory is undefined behavior.
2125
2126 \note Target operating systems may impose limits on how much memory an
2127 application can allocate, in total, or on the size of individual allocations.
2128 This may further restrict the size of string a QString can hold.
2129 Mitigating or controlling the behavior these limits cause is beyond the
2130 scope of the Qt API.
2131
2132 \sa {Which string class to use?}, fromRawData(), QChar, QStringView,
2133 QLatin1StringView, QByteArray
2134*/
2135
2136/*! \typedef QString::ConstIterator
2137
2138 Qt-style synonym for QString::const_iterator.
2139*/
2140
2141/*! \typedef QString::Iterator
2142
2143 Qt-style synonym for QString::iterator.
2144*/
2145
2146/*! \typedef QString::const_iterator
2147
2148 \sa QString::iterator
2149*/
2150
2151/*! \typedef QString::iterator
2152
2153 \sa QString::const_iterator
2154*/
2155
2156/*! \typedef QString::const_reverse_iterator
2157 \since 5.6
2158
2159 \sa QString::reverse_iterator, QString::const_iterator
2160*/
2161
2162/*! \typedef QString::reverse_iterator
2163 \since 5.6
2164
2165 \sa QString::const_reverse_iterator, QString::iterator
2166*/
2167
2168/*!
2169 \typedef QString::size_type
2170*/
2171
2172/*!
2173 \typedef QString::difference_type
2174*/
2175
2176/*!
2177 \typedef QString::const_reference
2178*/
2179/*!
2180 \typedef QString::reference
2181*/
2182
2183/*!
2184 \typedef QString::const_pointer
2185
2186 The QString::const_pointer typedef provides an STL-style
2187 const pointer to a QString element (QChar).
2188*/
2189/*!
2190 \typedef QString::pointer
2191
2192 The QString::pointer typedef provides an STL-style
2193 pointer to a QString element (QChar).
2194*/
2195
2196/*!
2197 \typedef QString::value_type
2198*/
2199
2200/*! \fn QString::iterator QString::begin()
2201
2202 Returns an \l{STL-style iterators}{STL-style iterator} pointing to the
2203 first character in the string.
2204
2205//! [iterator-invalidation-func-desc]
2206 \warning The returned iterator is invalidated on detachment or when the
2207 QString is modified.
2208//! [iterator-invalidation-func-desc]
2209
2210 \sa constBegin(), end()
2211*/
2212
2213/*! \fn QString::const_iterator QString::begin() const
2214
2215 \overload begin()
2216*/
2217
2218/*! \fn QString::const_iterator QString::cbegin() const
2219 \since 5.0
2220
2221 Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the
2222 first character in the string.
2223
2224 \include qstring.cpp iterator-invalidation-func-desc
2225
2226 \sa begin(), cend()
2227*/
2228
2229/*! \fn QString::const_iterator QString::constBegin() const
2230
2231 Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the
2232 first character in the string.
2233
2234 \include qstring.cpp iterator-invalidation-func-desc
2235
2236 \sa begin(), constEnd()
2237*/
2238
2239/*! \fn QString::iterator QString::end()
2240
2241 Returns an \l{STL-style iterators}{STL-style iterator} pointing just after
2242 the last character in the string.
2243
2244 \include qstring.cpp iterator-invalidation-func-desc
2245
2246 \sa begin(), constEnd()
2247*/
2248
2249/*! \fn QString::const_iterator QString::end() const
2250
2251 \overload end()
2252*/
2253
2254/*! \fn QString::const_iterator QString::cend() const
2255 \since 5.0
2256
2257 Returns a const \l{STL-style iterators}{STL-style iterator} pointing just
2258 after the last character in the string.
2259
2260 \include qstring.cpp iterator-invalidation-func-desc
2261
2262 \sa cbegin(), end()
2263*/
2264
2265/*! \fn QString::const_iterator QString::constEnd() const
2266
2267 Returns a const \l{STL-style iterators}{STL-style iterator} pointing just
2268 after the last character in the string.
2269
2270 \include qstring.cpp iterator-invalidation-func-desc
2271
2272 \sa constBegin(), end()
2273*/
2274
2275/*! \fn QString::reverse_iterator QString::rbegin()
2276 \since 5.6
2277
2278 Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing to
2279 the first character in the string, in reverse order.
2280
2281 \include qstring.cpp iterator-invalidation-func-desc
2282
2283 \sa begin(), crbegin(), rend()
2284*/
2285
2286/*! \fn QString::const_reverse_iterator QString::rbegin() const
2287 \since 5.6
2288 \overload
2289*/
2290
2291/*! \fn QString::const_reverse_iterator QString::crbegin() const
2292 \since 5.6
2293
2294 Returns a const \l{STL-style iterators}{STL-style} reverse iterator
2295 pointing to the first character in the string, in reverse order.
2296
2297 \include qstring.cpp iterator-invalidation-func-desc
2298
2299 \sa begin(), rbegin(), rend()
2300*/
2301
2302/*! \fn QString::reverse_iterator QString::rend()
2303 \since 5.6
2304
2305 Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing just
2306 after the last character in the string, in reverse order.
2307
2308 \include qstring.cpp iterator-invalidation-func-desc
2309
2310 \sa end(), crend(), rbegin()
2311*/
2312
2313/*! \fn QString::const_reverse_iterator QString::rend() const
2314 \since 5.6
2315 \overload
2316*/
2317
2318/*! \fn QString::const_reverse_iterator QString::crend() const
2319 \since 5.6
2320
2321 Returns a const \l{STL-style iterators}{STL-style} reverse iterator
2322 pointing just after the last character in the string, in reverse order.
2323
2324 \include qstring.cpp iterator-invalidation-func-desc
2325
2326 \sa end(), rend(), rbegin()
2327*/
2328
2329/*!
2330 \fn QString::QString()
2331
2332 Constructs a null string. Null strings are also considered empty.
2333
2334 \sa isEmpty(), isNull(), {Distinction Between Null and Empty Strings}
2335*/
2336
2337/*!
2338 \fn QString::QString(QString &&other)
2339
2340 Move-constructs a QString instance, making it point at the same
2341 object that \a other was pointing to.
2342
2343 \since 5.2
2344*/
2345
2346/*! \fn QString::QString(const char *str)
2347
2348 Constructs a string initialized with the 8-bit string \a str. The
2349 given const char pointer is converted to Unicode using the
2350 fromUtf8() function.
2351
2352 You can disable this constructor by defining
2353 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
2354 can be useful if you want to ensure that all user-visible strings
2355 go through QObject::tr(), for example.
2356
2357 \note Defining \l QT_RESTRICTED_CAST_FROM_ASCII also disables
2358 this constructor, but enables a \c{QString(const char (&ch)[N])}
2359 constructor instead. Using non-literal input, or input with
2360 embedded NUL characters, or non-7-bit characters is undefined
2361 in this case.
2362
2363 \sa fromLatin1(), fromLocal8Bit(), fromUtf8()
2364*/
2365
2366/*! \fn QString::QString(const char8_t *str)
2367
2368 Constructs a string initialized with the UTF-8 string \a str. The
2369 given const char8_t pointer is converted to Unicode using the
2370 fromUtf8() function.
2371
2372 \since 6.1
2373 \sa fromLatin1(), fromLocal8Bit(), fromUtf8()
2374*/
2375
2376/*!
2377 \fn QString::QString(QStringView sv)
2378
2379 Constructs a string initialized with the string view's data.
2380
2381 The QString will be null if and only if \a sv is null.
2382
2383 \since 6.8
2384
2385 \sa fromUtf16()
2386*/
2387
2388/*
2389//! [from-std-string]
2390Returns a copy of the \a str string. The given string is assumed to be
2391encoded in \1, and is converted to QString using the \2 function.
2392//! [from-std-string]
2393*/
2394
2395/*! \fn QString QString::fromStdString(const std::string &str)
2396
2397 \include qstring.cpp {from-std-string} {UTF-8} {fromUtf8()}
2398
2399 \sa fromLatin1(), fromLocal8Bit(), fromUtf8(), QByteArray::fromStdString()
2400*/
2401
2402/*! \fn QString QString::fromStdWString(const std::wstring &str)
2403
2404 Returns a copy of the \a str string. The given string is assumed
2405 to be encoded in utf16 if the size of wchar_t is 2 bytes (e.g. on
2406 windows) and ucs4 if the size of wchar_t is 4 bytes (most Unix
2407 systems).
2408
2409 \sa fromUtf16(), fromLatin1(), fromLocal8Bit(), fromUtf8(), fromUcs4(),
2410 fromStdU16String(), fromStdU32String()
2411*/
2412
2413/*! \fn QString QString::fromWCharArray(const wchar_t *string, qsizetype size)
2414 \since 4.2
2415
2416 Reads the first \a size code units of the \c wchar_t array to whose start
2417 \a string points, converting them to Unicode and returning the result as
2418 a QString. The encoding used by \c wchar_t is assumed to be UTF-32 if the
2419 type's size is four bytes or UTF-16 if its size is two bytes.
2420
2421 If \a size is -1 (default), the \a string must be '\\0'-terminated.
2422
2423 \sa fromUtf16(), fromLatin1(), fromLocal8Bit(), fromUtf8(), fromUcs4(),
2424 fromStdWString()
2425*/
2426
2427/*! \fn std::wstring QString::toStdWString() const
2428
2429 Returns a std::wstring object with the data contained in this
2430 QString. The std::wstring is encoded in UTF-16 on platforms where
2431 wchar_t is 2 bytes wide (for example, Windows) and in UTF-32 on platforms
2432 where wchar_t is 4 bytes wide (most Unix systems).
2433
2434 This method is mostly useful to pass a QString to a function
2435 that accepts a std::wstring object.
2436
2437 \sa utf16(), toLatin1(), toUtf8(), toLocal8Bit(), toStdU16String(),
2438 toStdU32String()
2439*/
2440
2441qsizetype QString::toUcs4_helper(const char16_t *uc, qsizetype length, char32_t *out)
2442{
2443 qsizetype count = 0;
2444
2445 QStringIterator i(QStringView(uc, length));
2446 while (i.hasNext())
2447 out[count++] = i.next();
2448
2449 return count;
2450}
2451
2452/*! \fn qsizetype QString::toWCharArray(wchar_t *array) const
2453 \since 4.2
2454
2455 Fills the \a array with the data contained in this QString object.
2456 The array is encoded in UTF-16 on platforms where
2457 wchar_t is 2 bytes wide (e.g. windows) and in UTF-32 on platforms
2458 where wchar_t is 4 bytes wide (most Unix systems).
2459
2460 \a array has to be allocated by the caller and contain enough space to
2461 hold the complete string (allocating the array with the same length as the
2462 string is always sufficient).
2463
2464 This function returns the actual length of the string in \a array.
2465
2466 \note This function does not append a null character to the array.
2467
2468 \sa utf16(), toUcs4(), toLatin1(), toUtf8(), toLocal8Bit(), toStdWString(),
2469 QStringView::toWCharArray()
2470*/
2471
2472/*! \fn QString::QString(const QString &other)
2473
2474 Constructs a copy of \a other.
2475
2476 This operation takes \l{constant time}, because QString is
2477 \l{implicitly shared}. This makes returning a QString from a
2478 function very fast. If a shared instance is modified, it will be
2479 copied (copy-on-write), and that takes \l{linear time}.
2480
2481 \sa operator=()
2482*/
2483
2484/*!
2485 Constructs a string initialized with the first \a size characters
2486 of the QChar array \a unicode.
2487
2488 If \a unicode is 0, a null string is constructed.
2489
2490 If \a size is negative, \a unicode is assumed to point to a '\\0'-terminated
2491 array and its length is determined dynamically. The terminating
2492 null character is not considered part of the string.
2493
2494 QString makes a deep copy of the string data. The unicode data is copied as
2495 is and the Byte Order Mark is preserved if present.
2496
2497 \sa fromRawData()
2498*/
2499QString::QString(const QChar *unicode, qsizetype size)
2500{
2501 if (!unicode) {
2502 d.clear();
2503 } else {
2504 if (size < 0)
2505 size = QtPrivate::qustrlen(reinterpret_cast<const char16_t *>(unicode));
2506 if (!size) {
2507 d = DataPointer::fromRawData(&_empty, 0);
2508 } else {
2509 d = DataPointer(size, size);
2510 Q_CHECK_PTR(d.data());
2511 memcpy(d.data(), unicode, size * sizeof(QChar));
2512 d.data()[size] = '\0';
2513 }
2514 }
2515}
2516
2517/*!
2518 Constructs a string of the given \a size with every character set
2519 to \a ch.
2520
2521 \sa fill()
2522*/
2523QString::QString(qsizetype size, QChar ch)
2524{
2525 if (size <= 0) {
2526 d = DataPointer::fromRawData(&_empty, 0);
2527 } else {
2528 d = DataPointer(size, size);
2529 Q_CHECK_PTR(d.data());
2530 d.data()[size] = '\0';
2531 char16_t *b = d.data();
2532 char16_t *e = d.data() + size;
2533 const char16_t value = ch.unicode();
2534 std::fill(b, e, value);
2535 }
2536}
2537
2538/*! \fn QString::QString(qsizetype size, Qt::Initialization)
2539 \internal
2540
2541 Constructs a string of the given \a size without initializing the
2542 characters. This is only used in \c QStringBuilder::toString().
2543*/
2544QString::QString(qsizetype size, Qt::Initialization)
2545{
2546 if (size <= 0) {
2547 d = DataPointer::fromRawData(&_empty, 0);
2548 } else {
2549 d = DataPointer(size, size);
2550 Q_CHECK_PTR(d.data());
2551 d.data()[size] = '\0';
2552 }
2553}
2554
2555/*! \fn QString::QString(QLatin1StringView str)
2556
2557 Constructs a copy of the Latin-1 string viewed by \a str.
2558
2559 \sa fromLatin1()
2560*/
2561
2562/*!
2563 Constructs a string of size 1 containing the character \a ch.
2564*/
2565QString::QString(QChar ch)
2566{
2567 d = DataPointer(1, 1);
2568 Q_CHECK_PTR(d.data());
2569 d.data()[0] = ch.unicode();
2570 d.data()[1] = '\0';
2571}
2572
2573/*! \fn QString::QString(const QByteArray &ba)
2574
2575 Constructs a string initialized with the byte array \a ba. The
2576 given byte array is converted to Unicode using fromUtf8().
2577
2578 You can disable this constructor by defining
2579 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
2580 can be useful if you want to ensure that all user-visible strings
2581 go through QObject::tr(), for example.
2582
2583 \note Any null ('\\0') bytes in the byte array will be included in this
2584 string, converted to Unicode null characters (U+0000). This behavior is
2585 different from Qt 5.x.
2586
2587 \sa fromLatin1(), fromLocal8Bit(), fromUtf8()
2588*/
2589
2590/*! \fn QString::QString(const Null &)
2591 \internal
2592*/
2593
2594/*! \fn QString::QString(QStringPrivate)
2595 \internal
2596*/
2597
2598/*! \fn QString &QString::operator=(const QString::Null &)
2599 \internal
2600*/
2601
2602/*!
2603 \fn QString::~QString()
2604
2605 Destroys the string.
2606*/
2607
2608
2609/*! \fn void QString::swap(QString &other)
2610 \since 4.8
2611 \memberswap{string}
2612*/
2613
2614/*! \fn void QString::detach()
2615
2616 Ensures that this string's data is no longer
2617 \l{Implicit Sharing}{shared} with other instances.
2618*/
2619
2620/*! \fn bool QString::isDetached() const
2621
2622 \internal
2623*/
2624
2625/*! \fn bool QString::isSharedWith(const QString &other) const
2626
2627 \internal
2628*/
2629
2630/*! \fn QString::operator std::u16string_view() const
2631 \target qstring-operator-std-u16string_view
2632 \since 6.7
2633
2634 Converts this QString object to a \c{std::u16string_view} object.
2635*/
2636
2637static bool needsReallocate(const QString &str, qsizetype newSize)
2638{
2639 const auto capacityAtEnd = str.capacity() - str.data_ptr().freeSpaceAtBegin();
2640 return newSize > capacityAtEnd;
2641}
2642
2643/*!
2644 Sets the size of the string to \a size characters.
2645
2646 If \a size is greater than the current size, the string is
2647 extended to make it \a size characters long with the extra
2648 characters added to the end. The new characters are uninitialized.
2649
2650 If \a size is less than the current size, characters beyond position
2651 \a size are excluded from the string.
2652
2653 \note While resize() will grow the capacity if needed, it never shrinks
2654 capacity. To shed excess capacity, use squeeze().
2655
2656 Example:
2657
2658 \snippet qstring/main.cpp 45
2659
2660 If you want to append a certain number of identical characters to
2661 the string, use the \l {QString::}{resize(qsizetype, QChar)} overload.
2662
2663 If you want to expand the string so that it reaches a certain
2664 width and fill the new positions with a particular character, use
2665 the leftJustified() function:
2666
2667 If \a size is negative, it is equivalent to passing zero.
2668
2669 \snippet qstring/main.cpp 47
2670
2671 \sa truncate(), reserve(), squeeze()
2672*/
2673
2674void QString::resize(qsizetype size)
2675{
2676 if (size < 0)
2677 size = 0;
2678
2679 if (d.needsDetach() || needsReallocate(*this, size))
2680 reallocData(size, QArrayData::Grow);
2681 d.size = size;
2682 if (d.allocatedCapacity())
2683 d.data()[size] = u'\0';
2684}
2685
2686/*!
2687 \overload
2688 \since 5.7
2689
2690 Unlike \l {QString::}{resize(qsizetype)}, this overload
2691 initializes the new characters to \a fillChar:
2692
2693 \snippet qstring/main.cpp 46
2694*/
2695
2696void QString::resize(qsizetype newSize, QChar fillChar)
2697{
2698 const qsizetype oldSize = size();
2699 resize(newSize);
2700 const qsizetype difference = size() - oldSize;
2701 if (difference > 0)
2702 std::fill_n(d.data() + oldSize, difference, fillChar.unicode());
2703}
2704
2705
2706/*!
2707 \since 6.8
2708
2709 Sets the size of the string to \a size characters. If the size of
2710 the string grows, the new characters are uninitialized.
2711
2712 The behavior is identical to \c{resize(size)}.
2713
2714 \sa resize()
2715*/
2716
2717void QString::resizeForOverwrite(qsizetype size)
2718{
2719 resize(size);
2720}
2721
2722
2723/*! \fn qsizetype QString::capacity() const
2724
2725 Returns the maximum number of characters that can be stored in
2726 the string without forcing a reallocation.
2727
2728 The sole purpose of this function is to provide a means of fine
2729 tuning QString's memory usage. In general, you will rarely ever
2730 need to call this function. If you want to know how many
2731 characters are in the string, call size().
2732
2733 \note a statically allocated string will report a capacity of 0,
2734 even if it's not empty.
2735
2736 \note The free space position in the allocated memory block is undefined. In
2737 other words, one should not assume that the free memory is always located
2738 after the initialized elements.
2739
2740 \sa reserve(), squeeze()
2741*/
2742
2743/*!
2744 \fn void QString::reserve(qsizetype size)
2745
2746 Ensures the string has space for at least \a size characters.
2747
2748 If you know in advance how large a string will be, you can call this
2749 function to save repeated reallocation while building it.
2750 This can improve performance when building a string incrementally.
2751 A long sequence of operations that add to a string may trigger several
2752 reallocations, the last of which may leave you with significantly more
2753 space than you need. This is less efficient than doing a single
2754 allocation of the right size at the start.
2755
2756 If in doubt about how much space shall be needed, it is usually better to
2757 use an upper bound as \a size, or a high estimate of the most likely size,
2758 if a strict upper bound would be much bigger than this. If \a size is an
2759 underestimate, the string will grow as needed once the reserved size is
2760 exceeded, which may lead to a larger allocation than your best
2761 overestimate would have and will slow the operation that triggers it.
2762
2763 \warning reserve() reserves memory but does not change the size of the
2764 string. Accessing data beyond the end of the string is undefined behavior.
2765 If you need to access memory beyond the current end of the string,
2766 use resize().
2767
2768 This function is useful for code that needs to build up a long
2769 string and wants to avoid repeated reallocation. In this example,
2770 we want to add to the string until some condition is \c true, and
2771 we're fairly sure that size is large enough to make a call to
2772 reserve() worthwhile:
2773
2774 \snippet qstring/main.cpp 44
2775
2776 \sa squeeze(), capacity(), resize()
2777*/
2778
2779/*!
2780 \fn void QString::squeeze()
2781
2782 Releases any memory not required to store the character data.
2783
2784 The sole purpose of this function is to provide a means of fine
2785 tuning QString's memory usage. In general, you will rarely ever
2786 need to call this function.
2787
2788 \sa reserve(), capacity()
2789*/
2790
2791void QString::reallocData(qsizetype alloc, QArrayData::AllocationOption option)
2792{
2793 if (!alloc) {
2794 d = DataPointer::fromRawData(&_empty, 0);
2795 return;
2796 }
2797
2798 // don't use reallocate path when reducing capacity and there's free space
2799 // at the beginning: might shift data pointer outside of allocated space
2800 const bool cannotUseReallocate = d.freeSpaceAtBegin() > 0;
2801
2802 if (d.needsDetach() || cannotUseReallocate) {
2803 DataPointer dd(alloc, qMin(alloc, d.size), option);
2804 Q_CHECK_PTR(dd.data());
2805 if (dd.size > 0)
2806 ::memcpy(dd.data(), d.data(), dd.size * sizeof(QChar));
2807 dd.data()[dd.size] = 0;
2808 d.swap(dd);
2809 } else {
2810 d->reallocate(alloc, option);
2811 }
2812}
2813
2814void QString::reallocGrowData(qsizetype n)
2815{
2816 if (!n) // expected to always allocate
2817 n = 1;
2818
2819 if (d.needsDetach()) {
2820 DataPointer dd(DataPointer::allocateGrow(d, n, QArrayData::GrowsAtEnd));
2821 Q_CHECK_PTR(dd.data());
2822 dd->copyAppend(d.data(), d.data() + d.size);
2823 dd.data()[dd.size] = 0;
2824 d.swap(dd);
2825 } else {
2826 d->reallocate(d.constAllocatedCapacity() + n, QArrayData::Grow);
2827 }
2828}
2829
2830/*! \fn void QString::clear()
2831
2832 Clears the contents of the string and makes it null.
2833
2834 \sa resize(), isNull()
2835*/
2836
2837/*! \fn QString &QString::operator=(const QString &other)
2838
2839 Assigns \a other to this string and returns a reference to this
2840 string.
2841*/
2842
2843/*!
2844 \fn QString &QString::operator=(QString &&other)
2845
2846 Move-assigns \a other to this QString instance.
2847
2848 \since 5.2
2849*/
2850
2851/*! \fn QString &QString::operator=(QLatin1StringView str)
2852
2853 \overload operator=()
2854
2855 Assigns the Latin-1 string viewed by \a str to this string.
2856*/
2857QString &QString::operator=(QLatin1StringView other)
2858{
2859 const qsizetype capacityAtEnd = capacity() - d.freeSpaceAtBegin();
2860 if (isDetached() && other.size() <= capacityAtEnd) { // assumes d.alloc == 0 -> !isDetached() (sharedNull)
2861 d.size = other.size();
2862 d.data()[other.size()] = 0;
2863 qt_from_latin1(d.data(), other.latin1(), other.size());
2864 } else {
2865 *this = fromLatin1(other.latin1(), other.size());
2866 }
2867 return *this;
2868}
2869
2870/*! \fn QString &QString::operator=(const QByteArray &ba)
2871
2872 \overload operator=()
2873
2874 Assigns \a ba to this string. The byte array is converted to Unicode
2875 using the fromUtf8() function.
2876
2877 You can disable this operator by defining
2878 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
2879 can be useful if you want to ensure that all user-visible strings
2880 go through QObject::tr(), for example.
2881*/
2882
2883/*! \fn QString &QString::operator=(const char *str)
2884
2885 \overload operator=()
2886
2887 Assigns \a str to this string. The const char pointer is converted
2888 to Unicode using the fromUtf8() function.
2889
2890 You can disable this operator by defining \l QT_NO_CAST_FROM_ASCII
2891 or \l QT_RESTRICTED_CAST_FROM_ASCII when you compile your applications.
2892 This can be useful if you want to ensure that all user-visible strings
2893 go through QObject::tr(), for example.
2894*/
2895
2896/*!
2897 \overload operator=()
2898
2899 Sets the string to contain the single character \a ch.
2900*/
2901QString &QString::operator=(QChar ch)
2902{
2903 return assign(1, ch);
2904}
2905
2906/*!
2907 \fn QString& QString::insert(qsizetype position, const QString &str)
2908
2909 Inserts the string \a str at the given index \a position and
2910 returns a reference to this string.
2911
2912 Example:
2913
2914 \snippet qstring/main.cpp 26
2915
2916//! [string-grow-at-insertion]
2917 This string grows to accommodate the insertion. If \a position is beyond
2918 the end of the string, space characters are appended to the string to reach
2919 this \a position, followed by \a str.
2920//! [string-grow-at-insertion]
2921
2922 \sa append(), prepend(), replace(), remove()
2923*/
2924
2925/*!
2926 \fn QString& QString::insert(qsizetype position, QStringView str)
2927 \since 6.0
2928 \overload insert()
2929
2930 Inserts the string view \a str at the given index \a position and
2931 returns a reference to this string.
2932
2933 \include qstring.cpp string-grow-at-insertion
2934*/
2935
2936
2937/*!
2938 \fn QString& QString::insert(qsizetype position, const char *str)
2939 \since 5.5
2940 \overload insert()
2941
2942 Inserts the C string \a str at the given index \a position and
2943 returns a reference to this string.
2944
2945 \include qstring.cpp string-grow-at-insertion
2946
2947 This function is not available when \l QT_NO_CAST_FROM_ASCII is
2948 defined.
2949*/
2950
2951/*!
2952 \fn QString& QString::insert(qsizetype position, const QByteArray &str)
2953 \since 5.5
2954 \overload insert()
2955
2956 Interprets the contents of \a str as UTF-8, inserts the Unicode string
2957 it encodes at the given index \a position and returns a reference to
2958 this string.
2959
2960 \include qstring.cpp string-grow-at-insertion
2961
2962 This function is not available when \l QT_NO_CAST_FROM_ASCII is
2963 defined.
2964*/
2965
2966/*! \internal
2967 T is a view or a container on/of QChar, char16_t, or char
2968*/
2969template <typename T>
2970static void insert_helper(QString &str, qsizetype i, const T &toInsert)
2971{
2972 auto &str_d = str.data_ptr();
2973 qsizetype difference = 0;
2974 if (Q_UNLIKELY(i > str_d.size))
2975 difference = i - str_d.size;
2976 const qsizetype oldSize = str_d.size;
2977 const qsizetype insert_size = toInsert.size();
2978 const qsizetype newSize = str_d.size + difference + insert_size;
2979 const auto side = i == 0 ? QArrayData::GrowsAtBeginning : QArrayData::GrowsAtEnd;
2980
2981 if (str_d.needsDetach() || needsReallocate(str, newSize)) {
2982 const auto cbegin = str.cbegin();
2983 const auto cend = str.cend();
2984 const auto insert_start = difference == 0 ? std::next(cbegin, i) : cend;
2985 QString other;
2986 // Using detachAndGrow() so that prepend optimization works and QStringBuilder
2987 // unittests pass
2988 other.data_ptr().detachAndGrow(side, newSize, nullptr, nullptr);
2989 other.append(QStringView(cbegin, insert_start));
2990 other.resize(i, u' ');
2991 other.append(toInsert);
2992 other.append(QStringView(insert_start, cend));
2993 str.swap(other);
2994 return;
2995 }
2996
2997 str_d.detachAndGrow(side, difference + insert_size, nullptr, nullptr);
2998 Q_CHECK_PTR(str_d.data());
2999 str.resize(newSize);
3000
3001 auto begin = str_d.begin();
3002 auto old_end = std::next(begin, oldSize);
3003 std::fill_n(old_end, difference, u' ');
3004 auto insert_start = std::next(begin, i);
3005 if (difference == 0)
3006 std::move_backward(insert_start, old_end, str_d.end());
3007
3008 using Char = std::remove_cv_t<typename T::value_type>;
3009 if constexpr(std::is_same_v<Char, QChar>)
3010 std::copy_n(reinterpret_cast<const char16_t *>(toInsert.data()), insert_size, insert_start);
3011 else if constexpr (std::is_same_v<Char, char16_t>)
3012 std::copy_n(toInsert.data(), insert_size, insert_start);
3013 else if constexpr (std::is_same_v<Char, char>)
3014 qt_from_latin1(insert_start, toInsert.data(), insert_size);
3015}
3016
3017/*!
3018 \fn QString &QString::insert(qsizetype position, QLatin1StringView str)
3019 \overload insert()
3020
3021 Inserts the Latin-1 string viewed by \a str at the given index \a position.
3022
3023 \include qstring.cpp string-grow-at-insertion
3024*/
3025QString &QString::insert(qsizetype i, QLatin1StringView str)
3026{
3027 const char *s = str.latin1();
3028 if (i < 0 || !s || !(*s))
3029 return *this;
3030
3031 insert_helper(*this, i, str);
3032 return *this;
3033}
3034
3035/*!
3036 \fn QString &QString::insert(qsizetype position, QUtf8StringView str)
3037 \overload insert()
3038 \since 6.5
3039
3040 Inserts the UTF-8 string view \a str at the given index \a position.
3041
3042 \note Inserting variable-width UTF-8-encoded string data is conceptually slower
3043 than inserting fixed-width string data such as UTF-16 (QStringView) or Latin-1
3044 (QLatin1StringView) and should thus be used sparingly.
3045
3046 \include qstring.cpp string-grow-at-insertion
3047*/
3048QString &QString::insert(qsizetype i, QUtf8StringView s)
3049{
3050 auto insert_size = s.size();
3051 if (i < 0 || insert_size <= 0)
3052 return *this;
3053
3054 qsizetype difference = 0;
3055 if (Q_UNLIKELY(i > d.size))
3056 difference = i - d.size;
3057
3058 const qsizetype newSize = d.size + difference + insert_size;
3059
3060 if (d.needsDetach() || needsReallocate(*this, newSize)) {
3061 const auto cbegin = this->cbegin();
3062 const auto insert_start = difference == 0 ? std::next(cbegin, i) : cend();
3063 QString other;
3064 other.reserve(newSize);
3065 other.append(QStringView(cbegin, insert_start));
3066 if (difference > 0)
3067 other.resize(i, u' ');
3068 other.append(s);
3069 other.append(QStringView(insert_start, cend()));
3070 swap(other);
3071 return *this;
3072 }
3073
3074 if (i >= d.size) {
3075 d.detachAndGrow(QArrayData::GrowsAtEnd, difference + insert_size, nullptr, nullptr);
3076 Q_CHECK_PTR(d.data());
3077
3078 if (difference > 0)
3079 resize(i, u' ');
3080 append(s);
3081 } else {
3082 // Optimal insertion of Utf8 data is at the end, anywhere else could
3083 // potentially lead to moving characters twice if Utf8 data size
3084 // (variable-width) is less than the equivalent Utf16 data size
3085 QVarLengthArray<char16_t> buffer(insert_size); // ### optimize (QTBUG-108546)
3086 char16_t *b = QUtf8::convertToUnicode(buffer.data(), s);
3087 insert_helper(*this, i, QStringView(buffer.data(), b));
3088 }
3089
3090 return *this;
3091}
3092
3093/*!
3094 \fn QString& QString::insert(qsizetype position, const QChar *unicode, qsizetype size)
3095 \overload insert()
3096
3097 Inserts the first \a size characters of the QChar array \a unicode
3098 at the given index \a position in the string.
3099
3100 This string grows to accommodate the insertion. If \a position is beyond
3101 the end of the string, space characters are appended to the string to reach
3102 this \a position, followed by \a size characters of the QChar array
3103 \a unicode.
3104*/
3105QString& QString::insert(qsizetype i, const QChar *unicode, qsizetype size)
3106{
3107 if (i < 0 || size <= 0)
3108 return *this;
3109
3110 // In case when data points into "this"
3111 if (!d.needsDetach() && QtPrivate::q_points_into_range(unicode, *this)) {
3112 QVarLengthArray copy(unicode, unicode + size);
3113 insert(i, copy.data(), size);
3114 } else {
3115 insert_helper(*this, i, QStringView(unicode, size));
3116 }
3117
3118 return *this;
3119}
3120
3121/*!
3122 \fn QString& QString::insert(qsizetype position, QChar ch)
3123 \overload insert()
3124
3125 Inserts \a ch at the given index \a position in the string.
3126
3127 This string grows to accommodate the insertion. If \a position is beyond
3128 the end of the string, space characters are appended to the string to reach
3129 this \a position, followed by \a ch.
3130*/
3131
3132QString& QString::insert(qsizetype i, QChar ch)
3133{
3134 if (i < 0)
3135 i += d.size;
3136 return insert(i, &ch, 1);
3137}
3138
3139/*!
3140 Appends the string \a str onto the end of this string.
3141
3142 Example:
3143
3144 \snippet qstring/main.cpp 9
3145
3146 This is the same as using the insert() function:
3147
3148 \snippet qstring/main.cpp 10
3149
3150 The append() function is typically very fast (\l{constant time}),
3151 because QString preallocates extra space at the end of the string
3152 data so it can grow without reallocating the entire string each
3153 time.
3154
3155 \sa operator+=(), prepend(), insert()
3156*/
3157QString &QString::append(const QString &str)
3158{
3159 if (!str.isNull()) {
3160 if (isNull()) {
3161 if (Q_UNLIKELY(!str.d.isMutable()))
3162 assign(str); // fromRawData, so we do a deep copy
3163 else
3164 operator=(str);
3165 } else if (str.size()) {
3166 append(str.constData(), str.size());
3167 }
3168 }
3169 return *this;
3170}
3171
3172/*!
3173 \fn QString &QString::append(QStringView v)
3174 \overload append()
3175 \since 6.0
3176
3177 Appends the given string view \a v to this string and returns the result.
3178*/
3179
3180/*!
3181 \overload append()
3182 \since 5.0
3183
3184 Appends \a len characters from the QChar array \a str to this string.
3185*/
3186QString &QString::append(const QChar *str, qsizetype len)
3187{
3188 if (str && len > 0) {
3189 static_assert(sizeof(QChar) == sizeof(char16_t), "Unexpected difference in sizes");
3190 // the following should be safe as QChar uses char16_t as underlying data
3191 const char16_t *char16String = reinterpret_cast<const char16_t *>(str);
3192 d->growAppend(char16String, char16String + len);
3193 d.data()[d.size] = u'\0';
3194 }
3195 return *this;
3196}
3197
3198/*!
3199 \overload append()
3200
3201 Appends the Latin-1 string viewed by \a str to this string.
3202*/
3203QString &QString::append(QLatin1StringView str)
3204{
3205 append_helper(*this, str);
3206 return *this;
3207}
3208
3209/*!
3210 \overload append()
3211 \since 6.5
3212
3213 Appends the UTF-8 string view \a str to this string.
3214*/
3215QString &QString::append(QUtf8StringView str)
3216{
3217 append_helper(*this, str);
3218 return *this;
3219}
3220
3221/*! \fn QString &QString::append(const QByteArray &ba)
3222
3223 \overload append()
3224
3225 Appends the byte array \a ba to this string. The given byte array
3226 is converted to Unicode using the fromUtf8() function.
3227
3228 You can disable this function by defining \l QT_NO_CAST_FROM_ASCII
3229 when you compile your applications. This can be useful if you want
3230 to ensure that all user-visible strings go through QObject::tr(),
3231 for example.
3232*/
3233
3234/*! \fn QString &QString::append(const char *str)
3235
3236 \overload append()
3237
3238 Appends the string \a str to this string. The given const char
3239 pointer is converted to Unicode using the fromUtf8() function.
3240
3241 You can disable this function by defining \l QT_NO_CAST_FROM_ASCII
3242 when you compile your applications. This can be useful if you want
3243 to ensure that all user-visible strings go through QObject::tr(),
3244 for example.
3245*/
3246
3247/*!
3248 \overload append()
3249
3250 Appends the character \a ch to this string.
3251*/
3252QString &QString::append(QChar ch)
3253{
3254 d.detachAndGrow(QArrayData::GrowsAtEnd, 1, nullptr, nullptr);
3255 d->copyAppend(1, ch.unicode());
3256 d.data()[d.size] = '\0';
3257 return *this;
3258}
3259
3260/*! \fn QString &QString::prepend(const QString &str)
3261
3262 Prepends the string \a str to the beginning of this string and
3263 returns a reference to this string.
3264
3265 This operation is typically very fast (\l{constant time}), because
3266 QString preallocates extra space at the beginning of the string data,
3267 so it can grow without reallocating the entire string each time.
3268
3269 Example:
3270
3271 \snippet qstring/main.cpp 36
3272
3273 \sa append(), insert()
3274*/
3275
3276/*! \fn QString &QString::prepend(QLatin1StringView str)
3277
3278 \overload prepend()
3279
3280 Prepends the Latin-1 string viewed by \a str to this string.
3281*/
3282
3283/*! \fn QString &QString::prepend(QUtf8StringView str)
3284 \since 6.5
3285 \overload prepend()
3286
3287 Prepends the UTF-8 string view \a str to this string.
3288*/
3289
3290/*! \fn QString &QString::prepend(const QChar *str, qsizetype len)
3291 \since 5.5
3292 \overload prepend()
3293
3294 Prepends \a len characters from the QChar array \a str to this string and
3295 returns a reference to this string.
3296*/
3297
3298/*! \fn QString &QString::prepend(QStringView str)
3299 \since 6.0
3300 \overload prepend()
3301
3302 Prepends the string view \a str to the beginning of this string and
3303 returns a reference to this string.
3304*/
3305
3306/*! \fn QString &QString::prepend(const QByteArray &ba)
3307
3308 \overload prepend()
3309
3310 Prepends the byte array \a ba to this string. The byte array is
3311 converted to Unicode using the fromUtf8() function.
3312
3313 You can disable this function by defining
3314 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
3315 can be useful if you want to ensure that all user-visible strings
3316 go through QObject::tr(), for example.
3317*/
3318
3319/*! \fn QString &QString::prepend(const char *str)
3320
3321 \overload prepend()
3322
3323 Prepends the string \a str to this string. The const char pointer
3324 is converted to Unicode using the fromUtf8() function.
3325
3326 You can disable this function by defining
3327 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
3328 can be useful if you want to ensure that all user-visible strings
3329 go through QObject::tr(), for example.
3330*/
3331
3332/*! \fn QString &QString::prepend(QChar ch)
3333
3334 \overload prepend()
3335
3336 Prepends the character \a ch to this string.
3337*/
3338
3339/*!
3340 \fn QString &QString::assign(QAnyStringView v)
3341 \since 6.6
3342
3343 Replaces the contents of this string with a copy of \a v and returns a
3344 reference to this string.
3345
3346 The size of this string will be equal to the size of \a v, converted to
3347 UTF-16 as if by \c{v.toString()}. Unlike QAnyStringView::toString(), however,
3348 this function only allocates memory if the estimated size exceeds the capacity
3349 of this string or this string is shared.
3350
3351 \sa QAnyStringView::toString()
3352*/
3353
3354/*!
3355 \fn QString &QString::assign(qsizetype n, QChar c)
3356 \since 6.6
3357
3358 Replaces the contents of this string with \a n copies of \a c and
3359 returns a reference to this string.
3360
3361 The size of this string will be equal to \a n, which has to be non-negative.
3362
3363 This function will only allocate memory if \a n exceeds the capacity of this
3364 string or this string is shared.
3365
3366 \sa fill()
3367*/
3368
3369/*!
3370 \fn template <typename InputIterator, QString::if_compatible_iterator<InputIterator>> QString &QString::assign(InputIterator first, InputIterator last)
3371 \since 6.6
3372
3373 Replaces the contents of this string with a copy of the elements in the
3374 iterator range [\a first, \a last) and returns a reference to this string.
3375
3376 The size of this string will be equal to the decoded length of the elements
3377 in the range [\a first, \a last), which need not be the same as the length of
3378 the range itself, because this function transparently recodes the input
3379 character set to UTF-16.
3380
3381 This function will only allocate memory if the number of elements in the
3382 range, or, for non-UTF-16-encoded input, the maximum possible size of the
3383 resulting string, exceeds the capacity of this string, or if this string is
3384 shared.
3385
3386 \note The behavior is undefined if either argument is an iterator into *this or
3387 [\a first, \a last) is not a valid range.
3388
3389 \constraints
3390 \c InputIterator meets the requirements of a
3391 \l {https://en.cppreference.com/w/cpp/named_req/InputIterator} {LegacyInputIterator}
3392 and the \c{value_type} of \c InputIterator is one of the following character types:
3393 \list
3394 \li QChar
3395 \li QLatin1Char
3396 \li \c {char}
3397 \li \c {unsigned char}
3398 \li \c {signed char}
3399 \li \c {char8_t}
3400 \li \c char16_t
3401 \li (on platforms, such as Windows, where it is a 16-bit type) \c wchar_t
3402 \li \c char32_t
3403 \endlist
3404*/
3405
3406QString &QString::assign(QAnyStringView s)
3407{
3408 if (s.size() <= capacity() && isDetached()) {
3409 const auto offset = d.freeSpaceAtBegin();
3410 if (offset)
3411 d.setBegin(d.begin() - offset);
3412 resize(0);
3413 s.visit([this](auto input) {
3414 this->append(input);
3415 });
3416 } else {
3417 *this = s.toString();
3418 }
3419 return *this;
3420}
3421
3422#ifndef QT_BOOTSTRAPPED
3423QString &QString::assign_helper(const char32_t *data, qsizetype len)
3424{
3425 // worst case: each char32_t requires a surrogate pair, so
3426 const auto requiredCapacity = len * 2;
3427 if (requiredCapacity <= capacity() && isDetached()) {
3428 const auto offset = d.freeSpaceAtBegin();
3429 if (offset)
3430 d.setBegin(d.begin() - offset);
3431 auto begin = reinterpret_cast<QChar *>(d.begin());
3432 auto ba = QByteArrayView(reinterpret_cast<const std::byte*>(data), len * sizeof(char32_t));
3433 QStringConverter::State state;
3434 const auto end = QUtf32::convertToUnicode(begin, ba, &state, DetectEndianness);
3435 d.size = end - begin;
3436 d.data()[d.size] = u'\0';
3437 } else {
3438 *this = QString::fromUcs4(data, len);
3439 }
3440 return *this;
3441}
3442#endif
3443
3444/*!
3445 \fn QString &QString::remove(qsizetype position, qsizetype n)
3446
3447 Removes \a n characters from the string, starting at the given \a
3448 position index, and returns a reference to the string.
3449
3450 If the specified \a position index is within the string, but \a
3451 position + \a n is beyond the end of the string, the string is
3452 truncated at the specified \a position.
3453
3454 If \a n is <= 0 nothing is changed.
3455
3456 \snippet qstring/main.cpp 37
3457
3458//! [shrinking-erase]
3459 Element removal will preserve the string's capacity and not reduce the
3460 amount of allocated memory. To shed extra capacity and free as much memory
3461 as possible, call squeeze() after the last change to the string's size.
3462//! [shrinking-erase]
3463
3464 \sa insert(), replace()
3465*/
3466QString &QString::remove(qsizetype pos, qsizetype len)
3467{
3468 if (pos < 0) // count from end of string
3469 pos += size();
3470
3471 if (size_t(pos) >= size_t(size()) || len <= 0)
3472 return *this;
3473
3474 len = std::min(len, size() - pos);
3475
3476 if (!d.isShared()) {
3477 d->erase(d.begin() + pos, len);
3478 d.data()[d.size] = u'\0';
3479 } else {
3480 // TODO: either reserve "size()", which is bigger than needed, or
3481 // modify the shrinking-erase docs of this method (since the size
3482 // of "copy" won't have any extra capacity any more)
3483 const qsizetype sz = size() - len;
3484 QString copy{sz, Qt::Uninitialized};
3485 auto begin = d.begin();
3486 auto toRemove_start = d.begin() + pos;
3487 copy.d->copyRanges({{begin, toRemove_start},
3488 {toRemove_start + len, d.end()}});
3489 swap(copy);
3490 }
3491 return *this;
3492}
3493
3494template<typename T>
3495static void removeStringImpl(QString &s, const T &needle, Qt::CaseSensitivity cs)
3496{
3497 const auto needleSize = needle.size();
3498 if (!needleSize)
3499 return;
3500
3501 // avoid detach if nothing to do:
3502 qsizetype i = s.indexOf(needle, 0, cs);
3503 if (i < 0)
3504 return;
3505
3506 QString::DataPointer &dptr = s.data_ptr();
3507 auto begin = dptr.begin();
3508 auto end = dptr.end();
3509
3510 auto copyFunc = [&](auto &dst) {
3511 auto src = begin + i + needleSize;
3512 while (src < end) {
3513 i = s.indexOf(needle, std::distance(begin, src), cs);
3514 auto hit = i == -1 ? end : begin + i;
3515 dst = std::copy(src, hit, dst);
3516 src = hit + needleSize;
3517 }
3518 return dst;
3519 };
3520
3521 if (!dptr.needsDetach()) {
3522 auto dst = begin + i;
3523 dst = copyFunc(dst);
3524 s.truncate(std::distance(begin, dst));
3525 } else {
3526 QString copy{s.size(), Qt::Uninitialized};
3527 auto copy_begin = copy.begin();
3528 auto dst = std::copy(begin, begin + i, copy_begin); // Chunk before the first hit
3529 dst = copyFunc(dst);
3530 copy.resize(std::distance(copy_begin, dst));
3531 s.swap(copy);
3532 }
3533}
3534
3535/*!
3536 Removes every occurrence of the given \a str string in this
3537 string, and returns a reference to this string.
3538
3539 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3540
3541 This is the same as \c replace(str, "", cs).
3542
3543 \include qstring.cpp shrinking-erase
3544
3545 \sa replace()
3546*/
3547QString &QString::remove(const QString &str, Qt::CaseSensitivity cs)
3548{
3549 const auto s = str.d.data();
3550 if (QtPrivate::q_points_into_range(s, d))
3551 removeStringImpl(*this, QStringView{QVarLengthArray(s, s + str.size())}, cs);
3552 else
3553 removeStringImpl(*this, qToStringViewIgnoringNull(str), cs);
3554 return *this;
3555}
3556
3557/*!
3558 \since 5.11
3559 \overload
3560
3561 Removes every occurrence of the given Latin-1 string viewed by \a str
3562 from this string, and returns a reference to this string.
3563
3564 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3565
3566 This is the same as \c replace(str, "", cs).
3567
3568 \include qstring.cpp shrinking-erase
3569
3570 \sa replace()
3571*/
3572QString &QString::remove(QLatin1StringView str, Qt::CaseSensitivity cs)
3573{
3574 removeStringImpl(*this, str, cs);
3575 return *this;
3576}
3577
3578/*!
3579 \fn QString &QString::removeAt(qsizetype pos)
3580
3581 \since 6.5
3582
3583 Removes the character at index \a pos. If \a pos is out of bounds
3584 (i.e. \a pos >= size()), this function does nothing.
3585
3586 \sa remove()
3587*/
3588
3589/*!
3590 \fn QString &QString::removeFirst()
3591
3592 \since 6.5
3593
3594 Removes the first character in this string. If the string is empty,
3595 this function does nothing.
3596
3597 \sa remove()
3598*/
3599
3600/*!
3601 \fn QString &QString::removeLast()
3602
3603 \since 6.5
3604
3605 Removes the last character in this string. If the string is empty,
3606 this function does nothing.
3607
3608 \sa remove()
3609*/
3610
3611/*!
3612 Removes every occurrence of the character \a ch in this string, and
3613 returns a reference to this string.
3614
3615 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3616
3617 Example:
3618
3619 \snippet qstring/main.cpp 38
3620
3621 This is the same as \c replace(ch, "", cs).
3622
3623 \include qstring.cpp shrinking-erase
3624
3625 \sa replace()
3626*/
3627QString &QString::remove(QChar ch, Qt::CaseSensitivity cs)
3628{
3629 const qsizetype idx = indexOf(ch, 0, cs);
3630 if (idx == -1)
3631 return *this;
3632
3633 const bool isCase = cs == Qt::CaseSensitive;
3634 ch = isCase ? ch : ch.toCaseFolded();
3635 auto match = [ch, isCase](QChar x) {
3636 return ch == (isCase ? x : x.toCaseFolded());
3637 };
3638
3639
3640 auto begin = d.begin();
3641 auto first_match = begin + idx;
3642 auto end = d.end();
3643 if (!d.isShared()) {
3644 auto it = std::remove_if(first_match, end, match);
3645 d->erase(it, std::distance(it, end));
3646 d.data()[d.size] = u'\0';
3647 } else {
3648 // Instead of detaching, create a new string and copy all characters except for
3649 // the ones we're removing
3650 // TODO: size() is more than the needed since "copy" would be shorter
3651 QString copy{size(), Qt::Uninitialized};
3652 auto dst = copy.d.begin();
3653 auto it = std::copy(begin, first_match, dst); // Chunk before idx
3654 it = std::remove_copy_if(first_match + 1, end, it, match);
3655 copy.d.size = std::distance(dst, it);
3656 copy.d.data()[copy.d.size] = u'\0';
3657 *this = std::move(copy);
3658 }
3659 return *this;
3660}
3661
3662/*!
3663 \fn QString &QString::remove(const QRegularExpression &re)
3664 \since 5.0
3665
3666 Removes every occurrence of the regular expression \a re in the
3667 string, and returns a reference to the string. For example:
3668
3669 \snippet qstring/main.cpp 96
3670
3671 \include qstring.cpp shrinking-erase
3672
3673 \sa indexOf(), lastIndexOf(), replace()
3674*/
3675
3676/*!
3677 \fn template <typename Predicate> QString &QString::removeIf(Predicate pred)
3678 \since 6.1
3679
3680 Removes all elements for which the predicate \a pred returns true
3681 from the string. Returns a reference to the string.
3682
3683 \sa remove()
3684*/
3685
3686static void replace_helper(QString &str, QSpan<qsizetype> indices, qsizetype blen, QStringView after)
3687{
3688 const qsizetype oldSize = str.data_ptr().size;
3689 const qsizetype adjust = indices.size() * (after.size() - blen);
3690 const qsizetype newSize = oldSize + adjust;
3691 using A = QStringAlgorithms<QString>;
3692 if (str.data_ptr().needsDetach() || needsReallocate(str, newSize)) {
3693 A::replace_helper(str, blen, after, indices);
3694 return;
3695 }
3696
3697 if (QtPrivate::q_points_into_range(after.begin(), str)) {
3698 // Copy after if it lies inside our own d.b area (which we could
3699 // possibly invalidate via a realloc or modify by replacement)
3700 A::replace_helper(str, blen, QVarLengthArray(after.begin(), after.end()), indices);
3701 } else {
3702 A::replace_helper(str, blen, after, indices);
3703 }
3704}
3705
3706/*!
3707 \fn QString &QString::replace(qsizetype position, qsizetype n, const QString &after)
3708
3709 Replaces \a n characters beginning at index \a position with
3710 the string \a after and returns a reference to this string.
3711
3712 \note If the specified \a position index is within the string,
3713 but \a position + \a n goes outside the strings range,
3714 then \a n will be adjusted to stop at the end of the string.
3715
3716 Example:
3717
3718 \snippet qstring/main.cpp 40
3719
3720 \sa insert(), remove()
3721*/
3722QString &QString::replace(qsizetype pos, qsizetype len, const QString &after)
3723{
3724 return replace(pos, len, after.constData(), after.size());
3725}
3726
3727/*!
3728 \fn QString &QString::replace(qsizetype position, qsizetype n, const QChar *after, qsizetype alen)
3729 \overload replace()
3730 Replaces \a n characters beginning at index \a position with the
3731 first \a alen characters of the QChar array \a after and returns a
3732 reference to this string.
3733
3734 \a n must not be negative.
3735*/
3736QString &QString::replace(qsizetype pos, qsizetype len, const QChar *after, qsizetype alen)
3737{
3738 Q_PRE(len >= 0);
3739
3740 if (size_t(pos) > size_t(this->size()))
3741 return *this;
3742 if (len > this->size() - pos)
3743 len = this->size() - pos;
3744
3745 qsizetype indices[] = {pos};
3746 replace_helper(*this, indices, len, QStringView{after, alen});
3747 return *this;
3748}
3749
3750/*!
3751 \fn QString &QString::replace(qsizetype position, qsizetype n, QChar after)
3752 \overload replace()
3753
3754 Replaces \a n characters beginning at index \a position with the
3755 character \a after and returns a reference to this string.
3756*/
3757QString &QString::replace(qsizetype pos, qsizetype len, QChar after)
3758{
3759 return replace(pos, len, &after, 1);
3760}
3761
3762/*!
3763 \overload replace()
3764 Replaces every occurrence of the string \a before with the string \a
3765 after and returns a reference to this string.
3766
3767 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3768
3769 Example:
3770
3771 \snippet qstring/main.cpp 41
3772
3773 \note The replacement text is not rescanned after it is inserted.
3774
3775 Example:
3776
3777 \snippet qstring/main.cpp 86
3778
3779//! [empty-before-arg-in-replace]
3780 \note If you use an empty \a before argument, the \a after argument will be
3781 inserted \e {before and after} each character of the string.
3782//! [empty-before-arg-in-replace]
3783
3784*/
3785QString &QString::replace(const QString &before, const QString &after, Qt::CaseSensitivity cs)
3786{
3787 return replace(before.constData(), before.size(), after.constData(), after.size(), cs);
3788}
3789
3790/*!
3791 \since 4.5
3792 \overload replace()
3793
3794 Replaces each occurrence in this string of the first \a blen
3795 characters of \a before with the first \a alen characters of \a
3796 after and returns a reference to this string.
3797
3798 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3799
3800 \note If \a before points to an \e empty string (that is, \a blen == 0),
3801 the string pointed to by \a after will be inserted \e {before and after}
3802 each character in this string.
3803*/
3804QString &QString::replace(const QChar *before, qsizetype blen,
3805 const QChar *after, qsizetype alen,
3806 Qt::CaseSensitivity cs)
3807{
3808 if (isEmpty()) {
3809 if (blen)
3810 return *this;
3811 } else {
3812 if (cs == Qt::CaseSensitive && before == after && blen == alen)
3813 return *this;
3814 }
3815 if (alen == 0 && blen == 0)
3816 return *this;
3817 if (alen == 1 && blen == 1)
3818 return replace(*before, *after, cs);
3819
3820 QStringMatcher matcher(before, blen, cs);
3821
3822 qsizetype index = 0;
3823
3824 QVarLengthArray<qsizetype> indices;
3825 while ((index = matcher.indexIn(*this, index)) != -1) {
3826 indices.push_back(index);
3827 if (blen) // Step over before:
3828 index += blen;
3829 else // Only count one instance of empty between any two characters:
3830 index++;
3831 }
3832 if (indices.isEmpty())
3833 return *this;
3834
3835 replace_helper(*this, indices, blen, QStringView{after, alen});
3836 return *this;
3837}
3838
3839/*!
3840 \overload replace()
3841 Replaces every occurrence of the character \a ch in the string with
3842 \a after and returns a reference to this string.
3843
3844 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3845*/
3846QString& QString::replace(QChar ch, const QString &after, Qt::CaseSensitivity cs)
3847{
3848 if (after.size() == 0)
3849 return remove(ch, cs);
3850
3851 if (after.size() == 1)
3852 return replace(ch, after.front(), cs);
3853
3854 if (size() == 0)
3855 return *this;
3856
3857 const char16_t cc = (cs == Qt::CaseSensitive ? ch.unicode() : ch.toCaseFolded().unicode());
3858
3859 QVarLengthArray<qsizetype> indices;
3860 if (cs == Qt::CaseSensitive) {
3861 const char16_t *begin = d.begin();
3862 const char16_t *end = d.end();
3863 QStringView view(begin, end);
3864 const char16_t *hit = nullptr;
3865 while ((hit = QtPrivate::qustrchr(view, cc)) != end) {
3866 indices.push_back(std::distance(begin, hit));
3867 view = QStringView(std::next(hit), end);
3868 }
3869 } else {
3870 for (qsizetype i = 0; i < d.size; ++i)
3871 if (QChar::toCaseFolded(d.data()[i]) == cc)
3872 indices.push_back(i);
3873 }
3874 if (indices.isEmpty())
3875 return *this;
3876
3877 replace_helper(*this, indices, 1, after);
3878 return *this;
3879}
3880
3881/*!
3882 \overload replace()
3883 Replaces every occurrence of the character \a before with the
3884 character \a after and returns a reference to this string.
3885
3886 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3887*/
3888QString& QString::replace(QChar before, QChar after, Qt::CaseSensitivity cs)
3889{
3890 const qsizetype idx = indexOf(before, 0, cs);
3891 if (idx == -1)
3892 return *this;
3893
3894 const char16_t achar = after.unicode();
3895 char16_t bchar = before.unicode();
3896
3897 auto matchesCIS = [](char16_t beforeChar) {
3898 return [beforeChar](char16_t ch) { return foldAndCompare(ch, beforeChar); };
3899 };
3900
3901 auto hit = d.begin() + idx;
3902 if (!d.needsDetach()) {
3903 *hit++ = achar;
3904 if (cs == Qt::CaseSensitive) {
3905 std::replace(hit, d.end(), bchar, achar);
3906 } else {
3907 bchar = foldCase(bchar);
3908 std::replace_if(hit, d.end(), matchesCIS(bchar), achar);
3909 }
3910 } else {
3911 QString other{ d.size, Qt::Uninitialized };
3912 auto dest = std::copy(d.begin(), hit, other.d.begin());
3913 *dest++ = achar;
3914 ++hit;
3915 if (cs == Qt::CaseSensitive) {
3916 std::replace_copy(hit, d.end(), dest, bchar, achar);
3917 } else {
3918 bchar = foldCase(bchar);
3919 std::replace_copy_if(hit, d.end(), dest, matchesCIS(bchar), achar);
3920 }
3921
3922 swap(other);
3923 }
3924 return *this;
3925}
3926
3927/*!
3928 \since 4.5
3929 \overload replace()
3930
3931 Replaces every occurrence in this string of the Latin-1 string viewed
3932 by \a before with the Latin-1 string viewed by \a after, and returns a
3933 reference to this string.
3934
3935 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3936
3937 \note The text is not rescanned after a replacement.
3938
3939 \include qstring.cpp empty-before-arg-in-replace
3940*/
3941QString &QString::replace(QLatin1StringView before, QLatin1StringView after, Qt::CaseSensitivity cs)
3942{
3943 const qsizetype alen = after.size();
3944 const qsizetype blen = before.size();
3945 if (blen == 1 && alen == 1)
3946 return replace(before.front(), after.front(), cs);
3947
3948 QVarLengthArray<char16_t> a = qt_from_latin1_to_qvla(after);
3949 QVarLengthArray<char16_t> b = qt_from_latin1_to_qvla(before);
3950 return replace((const QChar *)b.data(), blen, (const QChar *)a.data(), alen, cs);
3951}
3952
3953/*!
3954 \since 4.5
3955 \overload replace()
3956
3957 Replaces every occurrence in this string of the Latin-1 string viewed
3958 by \a before with the string \a after, and returns a reference to this
3959 string.
3960
3961 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3962
3963 \note The text is not rescanned after a replacement.
3964
3965 \include qstring.cpp empty-before-arg-in-replace
3966*/
3967QString &QString::replace(QLatin1StringView before, const QString &after, Qt::CaseSensitivity cs)
3968{
3969 const qsizetype blen = before.size();
3970 if (blen == 1 && after.size() == 1)
3971 return replace(before.front(), after.front(), cs);
3972
3973 QVarLengthArray<char16_t> b = qt_from_latin1_to_qvla(before);
3974 return replace((const QChar *)b.data(), blen, after.constData(), after.d.size, cs);
3975}
3976
3977/*!
3978 \since 4.5
3979 \overload replace()
3980
3981 Replaces every occurrence of the string \a before with the string \a
3982 after and returns a reference to this string.
3983
3984 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
3985
3986 \note The text is not rescanned after a replacement.
3987
3988 \include qstring.cpp empty-before-arg-in-replace
3989*/
3990QString &QString::replace(const QString &before, QLatin1StringView after, Qt::CaseSensitivity cs)
3991{
3992 const qsizetype alen = after.size();
3993 if (before.size() == 1 && alen == 1)
3994 return replace(before.front(), after.front(), cs);
3995
3996 QVarLengthArray<char16_t> a = qt_from_latin1_to_qvla(after);
3997 return replace(before.constData(), before.d.size, (const QChar *)a.data(), alen, cs);
3998}
3999
4000/*!
4001 \since 4.5
4002 \overload replace()
4003
4004 Replaces every occurrence of the character \a c with the string \a
4005 after and returns a reference to this string.
4006
4007 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4008
4009 \note The text is not rescanned after a replacement.
4010*/
4011QString &QString::replace(QChar c, QLatin1StringView after, Qt::CaseSensitivity cs)
4012{
4013 const qsizetype alen = after.size();
4014 if (alen == 1)
4015 return replace(c, after.front(), cs);
4016
4017 QVarLengthArray<char16_t> a = qt_from_latin1_to_qvla(after);
4018 return replace(&c, 1, (const QChar *)a.data(), alen, cs);
4019}
4020
4021/*!
4022 \fn bool QString::operator==(const QString &lhs, const QString &rhs)
4023 \overload operator==()
4024
4025 Returns \c true if string \a lhs is equal to string \a rhs; otherwise
4026 returns \c false.
4027
4028 \include qstring.cpp compare-isNull-vs-isEmpty
4029
4030 \sa {Comparing Strings}
4031*/
4032
4033/*!
4034 \fn bool QString::operator==(const QString &lhs, const QLatin1StringView &rhs)
4035
4036 \overload operator==()
4037
4038 Returns \c true if \a lhs is equal to \a rhs; otherwise
4039 returns \c false.
4040*/
4041
4042/*!
4043 \fn bool QString::operator==(const QLatin1StringView &lhs, const QString &rhs)
4044
4045 \overload operator==()
4046
4047 Returns \c true if \a lhs is equal to \a rhs; otherwise
4048 returns \c false.
4049*/
4050
4051/*! \fn bool QString::operator==(const QString &lhs, const QByteArray &rhs)
4052
4053 \overload operator==()
4054
4055 The \a rhs byte array is converted to a QUtf8StringView.
4056
4057 You can disable this operator by defining
4058 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
4059 can be useful if you want to ensure that all user-visible strings
4060 go through QObject::tr(), for example.
4061
4062 Returns \c true if string \a lhs is lexically equal to \a rhs.
4063 Otherwise returns \c false.
4064*/
4065
4066/*! \fn bool QString::operator==(const QString &lhs, const char * const &rhs)
4067
4068 \overload operator==()
4069
4070 The \a rhs const char pointer is converted to a QUtf8StringView.
4071
4072 You can disable this operator by defining
4073 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
4074 can be useful if you want to ensure that all user-visible strings
4075 go through QObject::tr(), for example.
4076*/
4077
4078/*!
4079 \fn bool QString::operator<(const QString &lhs, const QString &rhs)
4080
4081 \overload operator<()
4082
4083 Returns \c true if string \a lhs is lexically less than string
4084 \a rhs; otherwise returns \c false.
4085
4086 \sa {Comparing Strings}
4087*/
4088
4089/*!
4090 \fn bool QString::operator<(const QString &lhs, const QLatin1StringView &rhs)
4091
4092 \overload operator<()
4093
4094 Returns \c true if \a lhs is lexically less than \a rhs;
4095 otherwise returns \c false.
4096*/
4097
4098/*!
4099 \fn bool QString::operator<(const QLatin1StringView &lhs, const QString &rhs)
4100
4101 \overload operator<()
4102
4103 Returns \c true if \a lhs is lexically less than \a rhs;
4104 otherwise returns \c false.
4105*/
4106
4107/*! \fn bool QString::operator<(const QString &lhs, const QByteArray &rhs)
4108
4109 \overload operator<()
4110
4111 The \a rhs byte array is converted to a QUtf8StringView.
4112 If any NUL characters ('\\0') are embedded in the byte array, they will be
4113 included in the transformation.
4114
4115 You can disable this operator
4116 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
4117 can be useful if you want to ensure that all user-visible strings
4118 go through QObject::tr(), for example.
4119*/
4120
4121/*! \fn bool QString::operator<(const QString &lhs, const char * const &rhs)
4122
4123 Returns \c true if string \a lhs is lexically less than string \a rhs.
4124 Otherwise returns \c false.
4125
4126 \overload operator<()
4127
4128 The \a rhs const char pointer is converted to a QUtf8StringView.
4129
4130 You can disable this operator by defining
4131 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
4132 can be useful if you want to ensure that all user-visible strings
4133 go through QObject::tr(), for example.
4134*/
4135
4136/*! \fn bool QString::operator<=(const QString &lhs, const QString &rhs)
4137
4138 Returns \c true if string \a lhs is lexically less than or equal to
4139 string \a rhs; otherwise returns \c false.
4140
4141 \sa {Comparing Strings}
4142*/
4143
4144/*!
4145 \fn bool QString::operator<=(const QString &lhs, const QLatin1StringView &rhs)
4146
4147 \overload operator<=()
4148
4149 Returns \c true if \a lhs is lexically less than or equal to \a rhs;
4150 otherwise returns \c false.
4151*/
4152
4153/*!
4154 \fn bool QString::operator<=(const QLatin1StringView &lhs, const QString &rhs)
4155
4156 \overload operator<=()
4157
4158 Returns \c true if \a lhs is lexically less than or equal to \a rhs;
4159 otherwise returns \c false.
4160*/
4161
4162/*! \fn bool QString::operator<=(const QString &lhs, const QByteArray &rhs)
4163
4164 \overload operator<=()
4165
4166 The \a rhs byte array is converted to a QUtf8StringView.
4167 If any NUL characters ('\\0') are embedded in the byte array, they will be
4168 included in the transformation.
4169
4170 You can disable this operator by defining
4171 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
4172 can be useful if you want to ensure that all user-visible strings
4173 go through QObject::tr(), for example.
4174*/
4175
4176/*! \fn bool QString::operator<=(const QString &lhs, const char * const &rhs)
4177
4178 \overload operator<=()
4179
4180 The \a rhs const char pointer is converted to a QUtf8StringView.
4181
4182 You can disable this operator by defining
4183 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
4184 can be useful if you want to ensure that all user-visible strings
4185 go through QObject::tr(), for example.
4186*/
4187
4188/*! \fn bool QString::operator>(const QString &lhs, const QString &rhs)
4189
4190 Returns \c true if string \a lhs is lexically greater than string \a rhs;
4191 otherwise returns \c false.
4192
4193 \sa {Comparing Strings}
4194*/
4195
4196/*!
4197 \fn bool QString::operator>(const QString &lhs, const QLatin1StringView &rhs)
4198
4199 \overload operator>()
4200
4201 Returns \c true if \a lhs is lexically greater than \a rhs;
4202 otherwise returns \c false.
4203*/
4204
4205/*!
4206 \fn bool QString::operator>(const QLatin1StringView &lhs, const QString &rhs)
4207
4208 \overload operator>()
4209
4210 Returns \c true if \a lhs is lexically greater than \a rhs;
4211 otherwise returns \c false.
4212*/
4213
4214/*! \fn bool QString::operator>(const QString &lhs, const QByteArray &rhs)
4215
4216 \overload operator>()
4217
4218 The \a rhs byte array is converted to a QUtf8StringView.
4219 If any NUL characters ('\\0') are embedded in the byte array, they will be
4220 included in the transformation.
4221
4222 You can disable this operator by defining
4223 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
4224 can be useful if you want to ensure that all user-visible strings
4225 go through QObject::tr(), for example.
4226*/
4227
4228/*! \fn bool QString::operator>(const QString &lhs, const char * const &rhs)
4229
4230 \overload operator>()
4231
4232 The \a rhs const char pointer is converted to a QUtf8StringView.
4233
4234 You can disable this operator by defining \l QT_NO_CAST_FROM_ASCII
4235 when you compile your applications. This can be useful if you want
4236 to ensure that all user-visible strings go through QObject::tr(),
4237 for example.
4238*/
4239
4240/*! \fn bool QString::operator>=(const QString &lhs, const QString &rhs)
4241
4242 Returns \c true if string \a lhs is lexically greater than or equal to
4243 string \a rhs; otherwise returns \c false.
4244
4245 \sa {Comparing Strings}
4246*/
4247
4248/*!
4249 \fn bool QString::operator>=(const QString &lhs, const QLatin1StringView &rhs)
4250
4251 \overload operator>=()
4252
4253 Returns \c true if \a lhs is lexically greater than or equal to \a rhs;
4254 otherwise returns \c false.
4255*/
4256
4257/*!
4258 \fn bool QString::operator>=(const QLatin1StringView &lhs, const QString &rhs)
4259
4260 \overload operator>=()
4261
4262 Returns \c true if \a lhs is lexically greater than or equal to \a rhs;
4263 otherwise returns \c false.
4264*/
4265
4266/*! \fn bool QString::operator>=(const QString &lhs, const QByteArray &rhs)
4267
4268 \overload operator>=()
4269
4270 The \a rhs byte array is converted to a QUtf8StringView.
4271 If any NUL characters ('\\0') are embedded in the byte array, they will be
4272 included in the transformation.
4273
4274 You can disable this operator by defining \l QT_NO_CAST_FROM_ASCII
4275 when you compile your applications. This can be useful if you want
4276 to ensure that all user-visible strings go through QObject::tr(),
4277 for example.
4278*/
4279
4280/*! \fn bool QString::operator>=(const QString &lhs, const char * const &rhs)
4281
4282 \overload operator>=()
4283
4284 The \a rhs const char pointer is converted to a QUtf8StringView.
4285
4286 You can disable this operator by defining \l QT_NO_CAST_FROM_ASCII
4287 when you compile your applications. This can be useful if you want
4288 to ensure that all user-visible strings go through QObject::tr(),
4289 for example.
4290*/
4291
4292/*! \fn bool QString::operator!=(const QString &lhs, const QString &rhs)
4293
4294 Returns \c true if string \a lhs is not equal to string \a rhs;
4295 otherwise returns \c false.
4296
4297 \sa {Comparing Strings}
4298*/
4299
4300/*! \fn bool QString::operator!=(const QString &lhs, const QLatin1StringView &rhs)
4301
4302 Returns \c true if string \a lhs is not equal to string \a rhs.
4303 Otherwise returns \c false.
4304
4305 \overload operator!=()
4306*/
4307
4308/*! \fn bool QString::operator!=(const QString &lhs, const QByteArray &rhs)
4309
4310 \overload operator!=()
4311
4312 The \a rhs byte array is converted to a QUtf8StringView.
4313 If any NUL characters ('\\0') are embedded in the byte array, they will be
4314 included in the transformation.
4315
4316 You can disable this operator by defining \l QT_NO_CAST_FROM_ASCII
4317 when you compile your applications. This can be useful if you want
4318 to ensure that all user-visible strings go through QObject::tr(),
4319 for example.
4320*/
4321
4322/*! \fn bool QString::operator!=(const QString &lhs, const char * const &rhs)
4323
4324 \overload operator!=()
4325
4326 The \a rhs const char pointer is converted to a QUtf8StringView.
4327
4328 You can disable this operator by defining
4329 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
4330 can be useful if you want to ensure that all user-visible strings
4331 go through QObject::tr(), for example.
4332*/
4333
4334/*! \fn bool QString::operator==(const QByteArray &lhs, const QString &rhs)
4335
4336 Returns \c true if byte array \a lhs is equal to the UTF-8 encoding of
4337 \a rhs; otherwise returns \c false.
4338
4339 The comparison is case sensitive.
4340
4341 You can disable this operator by defining \c
4342 QT_NO_CAST_FROM_ASCII when you compile your applications. You
4343 then need to call QString::fromUtf8(), QString::fromLatin1(),
4344 or QString::fromLocal8Bit() explicitly if you want to convert the byte
4345 array to a QString before doing the comparison.
4346*/
4347
4348/*! \fn bool QString::operator!=(const QByteArray &lhs, const QString &rhs)
4349
4350 Returns \c true if byte array \a lhs is not equal to the UTF-8 encoding of
4351 \a rhs; otherwise returns \c false.
4352
4353 The comparison is case sensitive.
4354
4355 You can disable this operator by defining \c
4356 QT_NO_CAST_FROM_ASCII when you compile your applications. You
4357 then need to call QString::fromUtf8(), QString::fromLatin1(),
4358 or QString::fromLocal8Bit() explicitly if you want to convert the byte
4359 array to a QString before doing the comparison.
4360*/
4361
4362/*! \fn bool QString::operator<(const QByteArray &lhs, const QString &rhs)
4363
4364 Returns \c true if byte array \a lhs is lexically less than the UTF-8 encoding
4365 of \a rhs; otherwise returns \c false.
4366
4367 The comparison is case sensitive.
4368
4369 You can disable this operator by defining \c
4370 QT_NO_CAST_FROM_ASCII when you compile your applications. You
4371 then need to call QString::fromUtf8(), QString::fromLatin1(),
4372 or QString::fromLocal8Bit() explicitly if you want to convert the byte
4373 array to a QString before doing the comparison.
4374*/
4375
4376/*! \fn bool QString::operator>(const QByteArray &lhs, const QString &rhs)
4377
4378 Returns \c true if byte array \a lhs is lexically greater than the UTF-8
4379 encoding of \a rhs; otherwise returns \c false.
4380
4381 The comparison is case sensitive.
4382
4383 You can disable this operator by defining \c
4384 QT_NO_CAST_FROM_ASCII when you compile your applications. You
4385 then need to call QString::fromUtf8(), QString::fromLatin1(),
4386 or QString::fromLocal8Bit() explicitly if you want to convert the byte
4387 array to a QString before doing the comparison.
4388*/
4389
4390/*! \fn bool QString::operator<=(const QByteArray &lhs, const QString &rhs)
4391
4392 Returns \c true if byte array \a lhs is lexically less than or equal to the
4393 UTF-8 encoding of \a rhs; otherwise returns \c false.
4394
4395 The comparison is case sensitive.
4396
4397 You can disable this operator by defining \c
4398 QT_NO_CAST_FROM_ASCII when you compile your applications. You
4399 then need to call QString::fromUtf8(), QString::fromLatin1(),
4400 or QString::fromLocal8Bit() explicitly if you want to convert the byte
4401 array to a QString before doing the comparison.
4402*/
4403
4404/*! \fn bool QString::operator>=(const QByteArray &lhs, const QString &rhs)
4405
4406 Returns \c true if byte array \a lhs is greater than or equal to the UTF-8
4407 encoding of \a rhs; otherwise returns \c false.
4408
4409 The comparison is case sensitive.
4410
4411 You can disable this operator by defining \c
4412 QT_NO_CAST_FROM_ASCII when you compile your applications. You
4413 then need to call QString::fromUtf8(), QString::fromLatin1(),
4414 or QString::fromLocal8Bit() explicitly if you want to convert the byte
4415 array to a QString before doing the comparison.
4416*/
4417
4418/*!
4419 \fn qsizetype QString::indexOf(const QString &str, qsizetype from, Qt::CaseSensitivity cs) const
4420 \include qstring.qdocinc {qstring-first-index-of} {string} {str}
4421
4422 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4423
4424 Example:
4425
4426 \snippet qstring/main.cpp 24
4427
4428 \include qstring.qdocinc negative-index-start-search-from-end
4429
4430 \sa lastIndexOf(), contains(), count()
4431*/
4432
4433/*!
4434 \fn qsizetype QString::indexOf(QStringView str, qsizetype from, Qt::CaseSensitivity cs) const
4435 \since 5.14
4436 \overload indexOf()
4437
4438 \include qstring.qdocinc {qstring-first-index-of} {string view} {str}
4439
4440 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4441
4442 \include qstring.qdocinc negative-index-start-search-from-end
4443
4444 \sa QStringView::indexOf(), lastIndexOf(), contains(), count()
4445*/
4446
4447/*!
4448 \fn qsizetype QString::indexOf(QLatin1StringView str, qsizetype from, Qt::CaseSensitivity cs) const
4449 \since 4.5
4450
4451 \include {qstring.qdocinc} {qstring-first-index-of} {Latin-1 string viewed by} {str}
4452
4453 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4454
4455 Example:
4456
4457 \snippet qstring/main.cpp 24
4458
4459 \include qstring.qdocinc negative-index-start-search-from-end
4460
4461 \sa lastIndexOf(), contains(), count()
4462*/
4463
4464/*!
4465 \fn qsizetype QString::indexOf(QChar ch, qsizetype from, Qt::CaseSensitivity cs) const
4466 \overload indexOf()
4467
4468 \include qstring.qdocinc {qstring-first-index-of} {character} {ch}
4469*/
4470
4471/*!
4472 \fn qsizetype QString::lastIndexOf(const QString &str, qsizetype from, Qt::CaseSensitivity cs) const
4473 \include qstring.qdocinc {qstring-last-index-of} {string} {str}
4474
4475 \include qstring.qdocinc negative-index-start-search-from-end
4476
4477 Returns -1 if \a str is not found.
4478
4479 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4480
4481 Example:
4482
4483 \snippet qstring/main.cpp 29
4484
4485 \note When searching for a 0-length \a str, the match at the end of
4486 the data is excluded from the search by a negative \a from, even
4487 though \c{-1} is normally thought of as searching from the end of the
4488 string: the match at the end is \e after the last character, so it is
4489 excluded. To include such a final empty match, either give a positive
4490 value for \a from or omit the \a from parameter entirely.
4491
4492 \sa indexOf(), contains(), count()
4493*/
4494
4495/*!
4496 \fn qsizetype QString::lastIndexOf(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
4497 \since 6.2
4498 \overload lastIndexOf()
4499
4500 Returns the index position of the last occurrence of the string \a
4501 str in this string. Returns -1 if \a str is not found.
4502
4503 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4504
4505 Example:
4506
4507 \snippet qstring/main.cpp 29
4508
4509 \sa indexOf(), contains(), count()
4510*/
4511
4512
4513/*!
4514 \fn qsizetype QString::lastIndexOf(QLatin1StringView str, qsizetype from, Qt::CaseSensitivity cs) const
4515 \since 4.5
4516 \overload lastIndexOf()
4517
4518 \include qstring.qdocinc {qstring-last-index-of} {Latin-1 string viewed by} {str}
4519
4520 \include qstring.qdocinc negative-index-start-search-from-end
4521
4522 Returns -1 if \a str is not found.
4523
4524 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4525
4526 Example:
4527
4528 \snippet qstring/main.cpp 29
4529
4530 \note When searching for a 0-length \a str, the match at the end of
4531 the data is excluded from the search by a negative \a from, even
4532 though \c{-1} is normally thought of as searching from the end of the
4533 string: the match at the end is \e after the last character, so it is
4534 excluded. To include such a final empty match, either give a positive
4535 value for \a from or omit the \a from parameter entirely.
4536
4537 \sa indexOf(), contains(), count()
4538*/
4539
4540/*!
4541 \fn qsizetype QString::lastIndexOf(QLatin1StringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
4542 \since 6.2
4543 \overload lastIndexOf()
4544
4545 Returns the index position of the last occurrence of the string \a
4546 str in this string. Returns -1 if \a str is not found.
4547
4548 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4549
4550 Example:
4551
4552 \snippet qstring/main.cpp 29
4553
4554 \sa indexOf(), contains(), count()
4555*/
4556
4557/*!
4558 \fn qsizetype QString::lastIndexOf(QChar ch, qsizetype from, Qt::CaseSensitivity cs) const
4559 \overload lastIndexOf()
4560
4561 \include qstring.qdocinc {qstring-last-index-of} {character} {ch}
4562*/
4563
4564/*!
4565 \fn QString::lastIndexOf(QChar ch, Qt::CaseSensitivity) const
4566 \since 6.3
4567 \overload lastIndexOf()
4568*/
4569
4570/*!
4571 \fn qsizetype QString::lastIndexOf(QStringView str, qsizetype from, Qt::CaseSensitivity cs) const
4572 \since 5.14
4573 \overload lastIndexOf()
4574
4575 \include qstring.qdocinc {qstring-last-index-of} {string view} {str}
4576
4577 \include qstring.qdocinc negative-index-start-search-from-end
4578
4579 Returns -1 if \a str is not found.
4580
4581 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4582
4583 \note When searching for a 0-length \a str, the match at the end of
4584 the data is excluded from the search by a negative \a from, even
4585 though \c{-1} is normally thought of as searching from the end of the
4586 string: the match at the end is \e after the last character, so it is
4587 excluded. To include such a final empty match, either give a positive
4588 value for \a from or omit the \a from parameter entirely.
4589
4590 \sa indexOf(), contains(), count()
4591*/
4592
4593/*!
4594 \fn qsizetype QString::lastIndexOf(QStringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
4595 \since 6.2
4596 \overload lastIndexOf()
4597
4598 Returns the index position of the last occurrence of the string view \a
4599 str in this string. Returns -1 if \a str is not found.
4600
4601 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4602
4603 \sa indexOf(), contains(), count()
4604*/
4605
4606#if QT_CONFIG(regularexpression)
4607struct QStringCapture
4608{
4609 qsizetype pos;
4610 qsizetype len;
4611 int no;
4612};
4613Q_DECLARE_TYPEINFO(QStringCapture, Q_PRIMITIVE_TYPE);
4614
4615/*!
4616 \overload replace()
4617 \since 5.0
4618
4619 Replaces every occurrence of the regular expression \a re in the
4620 string with \a after. Returns a reference to the string. For
4621 example:
4622
4623 \snippet qstring/main.cpp 87
4624
4625 For regular expressions containing capturing groups,
4626 occurrences of \b{\\1}, \b{\\2}, ..., in \a after are replaced
4627 with the string captured by the corresponding capturing group.
4628
4629 \snippet qstring/main.cpp 88
4630
4631 \sa indexOf(), lastIndexOf(), remove(), QRegularExpression, QRegularExpressionMatch
4632*/
4633QString &QString::replace(const QRegularExpression &re, const QString &after)
4634{
4635 if (!re.isValid()) {
4636 qtWarnAboutInvalidRegularExpression(re, "QString", "replace");
4637 return *this;
4638 }
4639
4640 const QString copy(*this);
4641 QRegularExpressionMatchIterator iterator = re.globalMatch(copy);
4642 if (!iterator.hasNext()) // no matches at all
4643 return *this;
4644
4645 reallocData(d.size, QArrayData::KeepSize);
4646
4647 qsizetype numCaptures = re.captureCount();
4648
4649 // 1. build the backreferences list, holding where the backreferences
4650 // are in the replacement string
4651 QVarLengthArray<QStringCapture> backReferences;
4652 const qsizetype al = after.size();
4653 const QChar *ac = after.unicode();
4654
4655 for (qsizetype i = 0; i < al - 1; i++) {
4656 if (ac[i] == u'\\') {
4657 int no = ac[i + 1].digitValue();
4658 if (no > 0 && no <= numCaptures) {
4659 QStringCapture backReference;
4660 backReference.pos = i;
4661 backReference.len = 2;
4662
4663 if (i < al - 2) {
4664 int secondDigit = ac[i + 2].digitValue();
4665 if (secondDigit != -1 && ((no * 10) + secondDigit) <= numCaptures) {
4666 no = (no * 10) + secondDigit;
4667 ++backReference.len;
4668 }
4669 }
4670
4671 backReference.no = no;
4672 backReferences.append(backReference);
4673 }
4674 }
4675 }
4676
4677 // 2. iterate on the matches. For every match, copy in chunks
4678 // - the part before the match
4679 // - the after string, with the proper replacements for the backreferences
4680
4681 qsizetype newLength = 0; // length of the new string, with all the replacements
4682 qsizetype lastEnd = 0;
4683 QVarLengthArray<QStringView> chunks;
4684 const QStringView copyView{ copy }, afterView{ after };
4685 while (iterator.hasNext()) {
4686 QRegularExpressionMatch match = iterator.next();
4687 qsizetype len;
4688 // add the part before the match
4689 len = match.capturedStart() - lastEnd;
4690 if (len > 0) {
4691 chunks << copyView.mid(lastEnd, len);
4692 newLength += len;
4693 }
4694
4695 lastEnd = 0;
4696 // add the after string, with replacements for the backreferences
4697 for (const QStringCapture &backReference : std::as_const(backReferences)) {
4698 // part of "after" before the backreference
4699 len = backReference.pos - lastEnd;
4700 if (len > 0) {
4701 chunks << afterView.mid(lastEnd, len);
4702 newLength += len;
4703 }
4704
4705 // backreference itself
4706 len = match.capturedLength(backReference.no);
4707 if (len > 0) {
4708 chunks << copyView.mid(match.capturedStart(backReference.no), len);
4709 newLength += len;
4710 }
4711
4712 lastEnd = backReference.pos + backReference.len;
4713 }
4714
4715 // add the last part of the after string
4716 len = afterView.size() - lastEnd;
4717 if (len > 0) {
4718 chunks << afterView.mid(lastEnd, len);
4719 newLength += len;
4720 }
4721
4722 lastEnd = match.capturedEnd();
4723 }
4724
4725 // 3. trailing string after the last match
4726 if (copyView.size() > lastEnd) {
4727 chunks << copyView.mid(lastEnd);
4728 newLength += copyView.size() - lastEnd;
4729 }
4730
4731 // 4. assemble the chunks together
4732 resize(newLength);
4733 qsizetype i = 0;
4734 QChar *uc = data();
4735 for (const QStringView &chunk : std::as_const(chunks)) {
4736 qsizetype len = chunk.size();
4737 memcpy(uc + i, chunk.constData(), len * sizeof(QChar));
4738 i += len;
4739 }
4740
4741 return *this;
4742}
4743#endif // QT_CONFIG(regularexpression)
4744
4745/*!
4746 Returns the number of (potentially overlapping) occurrences of
4747 the string \a str in this string.
4748
4749 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4750
4751 \sa contains(), indexOf()
4752*/
4753
4754qsizetype QString::count(const QString &str, Qt::CaseSensitivity cs) const
4755{
4756 return QtPrivate::count(QStringView(unicode(), size()), QStringView(str.unicode(), str.size()), cs);
4757}
4758
4759/*!
4760 \overload count()
4761
4762 Returns the number of occurrences of character \a ch in the string.
4763
4764 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4765
4766 \sa contains(), indexOf()
4767*/
4768
4769qsizetype QString::count(QChar ch, Qt::CaseSensitivity cs) const
4770{
4771 return QtPrivate::count(QStringView(unicode(), size()), ch, cs);
4772}
4773
4774/*!
4775 \since 6.0
4776 \overload count()
4777 Returns the number of (potentially overlapping) occurrences of the
4778 string view \a str in this string.
4779
4780 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4781
4782 \sa contains(), indexOf()
4783*/
4784qsizetype QString::count(QStringView str, Qt::CaseSensitivity cs) const
4785{
4786 return QtPrivate::count(*this, str, cs);
4787}
4788
4789/*! \fn bool QString::contains(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
4790
4791 Returns \c true if this string contains an occurrence of the string
4792 \a str; otherwise returns \c false.
4793
4794 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4795
4796 Example:
4797 \snippet qstring/main.cpp 17
4798
4799 \sa indexOf(), count()
4800*/
4801
4802/*! \fn bool QString::contains(QLatin1StringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
4803 \since 5.3
4804
4805 \overload contains()
4806
4807 Returns \c true if this string contains an occurrence of the latin-1 string
4808 \a str; otherwise returns \c false.
4809*/
4810
4811/*! \fn bool QString::contains(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
4812
4813 \overload contains()
4814
4815 Returns \c true if this string contains an occurrence of the
4816 character \a ch; otherwise returns \c false.
4817*/
4818
4819/*! \fn bool QString::contains(QStringView str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
4820 \since 5.14
4821 \overload contains()
4822
4823 Returns \c true if this string contains an occurrence of the string view
4824 \a str; otherwise returns \c false.
4825
4826 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
4827
4828 \sa indexOf(), count()
4829*/
4830
4831#if QT_CONFIG(regularexpression)
4832/*!
4833 \since 5.5
4834
4835 Returns the index position of the first match of the regular
4836 expression \a re in the string, searching forward from index
4837 position \a from. Returns -1 if \a re didn't match anywhere.
4838
4839 If the match is successful and \a rmatch is not \nullptr, it also
4840 writes the results of the match into the QRegularExpressionMatch object
4841 pointed to by \a rmatch.
4842
4843 Example:
4844
4845 \snippet qstring/main.cpp 93
4846*/
4847qsizetype QString::indexOf(const QRegularExpression &re, qsizetype from, QRegularExpressionMatch *rmatch) const
4848{
4849 return QtPrivate::indexOf(QStringView(*this), this, re, from, rmatch);
4850}
4851
4852/*!
4853 \since 5.5
4854
4855 Returns the index position of the last match of the regular
4856 expression \a re in the string, which starts before the index
4857 position \a from.
4858
4859 \include qstring.qdocinc negative-index-start-search-from-end
4860
4861 Returns -1 if \a re didn't match anywhere.
4862
4863 If the match is successful and \a rmatch is not \nullptr, it also
4864 writes the results of the match into the QRegularExpressionMatch object
4865 pointed to by \a rmatch.
4866
4867 Example:
4868
4869 \snippet qstring/main.cpp 94
4870
4871 \note Due to how the regular expression matching algorithm works,
4872 this function will actually match repeatedly from the beginning of
4873 the string until the position \a from is reached.
4874
4875 \note When searching for a regular expression \a re that may match
4876 0 characters, the match at the end of the data is excluded from the
4877 search by a negative \a from, even though \c{-1} is normally
4878 thought of as searching from the end of the string: the match at
4879 the end is \e after the last character, so it is excluded. To
4880 include such a final empty match, either give a positive value for
4881 \a from or omit the \a from parameter entirely.
4882*/
4883qsizetype QString::lastIndexOf(const QRegularExpression &re, qsizetype from, QRegularExpressionMatch *rmatch) const
4884{
4885 return QtPrivate::lastIndexOf(QStringView(*this), this, re, from, rmatch);
4886}
4887
4888/*!
4889 \fn qsizetype QString::lastIndexOf(const QRegularExpression &re, QRegularExpressionMatch *rmatch = nullptr) const
4890 \since 6.2
4891 \overload lastIndexOf()
4892
4893 Returns the index position of the last match of the regular
4894 expression \a re in the string. Returns -1 if \a re didn't match anywhere.
4895
4896 If the match is successful and \a rmatch is not \nullptr, it also
4897 writes the results of the match into the QRegularExpressionMatch object
4898 pointed to by \a rmatch.
4899
4900 Example:
4901
4902 \snippet qstring/main.cpp 94
4903
4904 \note Due to how the regular expression matching algorithm works,
4905 this function will actually match repeatedly from the beginning of
4906 the string until the end of the string is reached.
4907*/
4908
4909/*!
4910 \since 5.1
4911
4912 Returns \c true if the regular expression \a re matches somewhere in this
4913 string; otherwise returns \c false.
4914
4915 If the match is successful and \a rmatch is not \nullptr, it also
4916 writes the results of the match into the QRegularExpressionMatch object
4917 pointed to by \a rmatch.
4918
4919 \sa QRegularExpression::match()
4920*/
4921
4922bool QString::contains(const QRegularExpression &re, QRegularExpressionMatch *rmatch) const
4923{
4924 return QtPrivate::contains(QStringView(*this), this, re, rmatch);
4925}
4926
4927/*!
4928 \overload count()
4929 \since 5.0
4930
4931 Returns the number of times the regular expression \a re matches
4932 in the string.
4933
4934 For historical reasons, this function counts overlapping matches,
4935 so in the example below, there are four instances of "ana" or
4936 "ama":
4937
4938 \snippet qstring/main.cpp 95
4939
4940 This behavior is different from simply iterating over the matches
4941 in the string using QRegularExpressionMatchIterator.
4942
4943 \sa QRegularExpression::globalMatch()
4944*/
4945qsizetype QString::count(const QRegularExpression &re) const
4946{
4947 return QtPrivate::count(QStringView(*this), re);
4948}
4949#endif // QT_CONFIG(regularexpression)
4950
4951#if QT_DEPRECATED_SINCE(6, 4)
4952/*! \fn qsizetype QString::count() const
4953 \deprecated [6.4] Use size() or length() instead.
4954 \overload count()
4955
4956 Same as size().
4957*/
4958#endif
4959
4960/*!
4961 \enum QString::SectionFlag
4962
4963 This enum specifies flags that can be used to affect various
4964 aspects of the section() function's behavior with respect to
4965 separators and empty fields.
4966
4967 \value SectionDefault Empty fields are counted, leading and
4968 trailing separators are not included, and the separator is
4969 compared case sensitively.
4970
4971 \value SectionSkipEmpty Treat empty fields as if they don't exist,
4972 i.e. they are not considered as far as \e start and \e end are
4973 concerned.
4974
4975 \value SectionIncludeLeadingSep Include the leading separator (if
4976 any) in the result string.
4977
4978 \value SectionIncludeTrailingSep Include the trailing separator
4979 (if any) in the result string.
4980
4981 \value SectionCaseInsensitiveSeps Compare the separator
4982 case-insensitively.
4983
4984 \sa section()
4985*/
4986
4987/*!
4988 \fn QString QString::section(QChar sep, qsizetype start, qsizetype end = -1, SectionFlags flags) const
4989
4990 This function returns a section of the string.
4991
4992 This string is treated as a sequence of fields separated by the
4993 character, \a sep. The returned string consists of the fields from
4994 position \a start to position \a end inclusive. If \a end is not
4995 specified, all fields from position \a start to the end of the
4996 string are included. Fields are numbered 0, 1, 2, etc., counting
4997 from the left, and -1, -2, etc., counting from right to left.
4998
4999 The \a flags argument can be used to affect some aspects of the
5000 function's behavior, e.g. whether to be case sensitive, whether
5001 to skip empty fields and how to deal with leading and trailing
5002 separators; see \l{SectionFlags}.
5003
5004 \snippet qstring/main.cpp 52
5005
5006 If \a start or \a end is negative, we count fields from the right
5007 of the string, the right-most field being -1, the one from
5008 right-most field being -2, and so on.
5009
5010 \snippet qstring/main.cpp 53
5011
5012 \sa split()
5013*/
5014
5015/*!
5016 \overload section()
5017
5018 \snippet qstring/main.cpp 51
5019 \snippet qstring/main.cpp 54
5020
5021 \sa split()
5022*/
5023
5024QString QString::section(const QString &sep, qsizetype start, qsizetype end, SectionFlags flags) const
5025{
5026 const QList<QStringView> sections = QStringView{ *this }.split(
5027 sep, Qt::KeepEmptyParts, (flags & SectionCaseInsensitiveSeps) ? Qt::CaseInsensitive : Qt::CaseSensitive);
5028 const qsizetype sectionsSize = sections.size();
5029 if (!(flags & SectionSkipEmpty)) {
5030 if (start < 0)
5031 start += sectionsSize;
5032 if (end < 0)
5033 end += sectionsSize;
5034 } else {
5035 qsizetype skip = 0;
5036 for (qsizetype k = 0; k < sectionsSize; ++k) {
5037 if (sections.at(k).isEmpty())
5038 skip++;
5039 }
5040 if (start < 0)
5041 start += sectionsSize - skip;
5042 if (end < 0)
5043 end += sectionsSize - skip;
5044 }
5045 if (start >= sectionsSize || end < 0 || start > end)
5046 return QString();
5047
5048 QString ret;
5049 qsizetype first_i = start, last_i = end;
5050 for (qsizetype x = 0, i = 0; x <= end && i < sectionsSize; ++i) {
5051 const QStringView &section = sections.at(i);
5052 const bool empty = section.isEmpty();
5053 if (x >= start) {
5054 if (x == start)
5055 first_i = i;
5056 if (x == end)
5057 last_i = i;
5058 if (x > start && i > 0)
5059 ret += sep;
5060 ret += section;
5061 }
5062 if (!empty || !(flags & SectionSkipEmpty))
5063 x++;
5064 }
5065 if ((flags & SectionIncludeLeadingSep) && first_i > 0)
5066 ret.prepend(sep);
5067 if ((flags & SectionIncludeTrailingSep) && last_i < sectionsSize - 1)
5068 ret += sep;
5069 return ret;
5070}
5071
5072#if QT_CONFIG(regularexpression)
5073struct qt_section_chunk
5074{
5075 qsizetype length;
5076 QStringView string;
5077};
5078Q_DECLARE_TYPEINFO(qt_section_chunk, Q_RELOCATABLE_TYPE);
5079
5080static QString extractSections(QSpan<qt_section_chunk> sections, qsizetype start, qsizetype end,
5081 QString::SectionFlags flags)
5082{
5083 const qsizetype sectionsSize = sections.size();
5084
5085 if (!(flags & QString::SectionSkipEmpty)) {
5086 if (start < 0)
5087 start += sectionsSize;
5088 if (end < 0)
5089 end += sectionsSize;
5090 } else {
5091 qsizetype skip = 0;
5092 for (qsizetype k = 0; k < sectionsSize; ++k) {
5093 const qt_section_chunk &section = sections[k];
5094 if (section.length == section.string.size())
5095 skip++;
5096 }
5097 if (start < 0)
5098 start += sectionsSize - skip;
5099 if (end < 0)
5100 end += sectionsSize - skip;
5101 }
5102 if (start >= sectionsSize || end < 0 || start > end)
5103 return QString();
5104
5105 QString ret;
5106 qsizetype x = 0;
5107 qsizetype first_i = start, last_i = end;
5108 for (qsizetype i = 0; x <= end && i < sectionsSize; ++i) {
5109 const qt_section_chunk &section = sections[i];
5110 const bool empty = (section.length == section.string.size());
5111 if (x >= start) {
5112 if (x == start)
5113 first_i = i;
5114 if (x == end)
5115 last_i = i;
5116 if (x != start)
5117 ret += section.string;
5118 else
5119 ret += section.string.mid(section.length);
5120 }
5121 if (!empty || !(flags & QString::SectionSkipEmpty))
5122 x++;
5123 }
5124
5125 if ((flags & QString::SectionIncludeLeadingSep) && first_i >= 0) {
5126 const qt_section_chunk &section = sections[first_i];
5127 ret.prepend(section.string.left(section.length));
5128 }
5129
5130 if ((flags & QString::SectionIncludeTrailingSep)
5131 && last_i < sectionsSize - 1) {
5132 const qt_section_chunk &section = sections[last_i + 1];
5133 ret += section.string.left(section.length);
5134 }
5135
5136 return ret;
5137}
5138
5139/*!
5140 \overload section()
5141 \since 5.0
5142
5143 This string is treated as a sequence of fields separated by the
5144 regular expression, \a re.
5145
5146 \snippet qstring/main.cpp 89
5147
5148 \warning Using this QRegularExpression version is much more expensive than
5149 the overloaded string and character versions.
5150
5151 \sa split(), simplified()
5152*/
5153QString QString::section(const QRegularExpression &re, qsizetype start, qsizetype end, SectionFlags flags) const
5154{
5155 if (!re.isValid()) {
5156 qtWarnAboutInvalidRegularExpression(re, "QString", "section");
5157 return QString();
5158 }
5159
5160 const QChar *uc = unicode();
5161 if (!uc)
5162 return QString();
5163
5164 QRegularExpression sep(re);
5165 if (flags & SectionCaseInsensitiveSeps)
5166 sep.setPatternOptions(sep.patternOptions() | QRegularExpression::CaseInsensitiveOption);
5167
5168 QVarLengthArray<qt_section_chunk> sections;
5169 qsizetype n = size(), m = 0, last_m = 0, last_len = 0;
5170 QRegularExpressionMatchIterator iterator = sep.globalMatch(*this);
5171 while (iterator.hasNext()) {
5172 QRegularExpressionMatch match = iterator.next();
5173 m = match.capturedStart();
5174 sections.append(qt_section_chunk{last_len, QStringView{*this}.sliced(last_m, m - last_m)});
5175 last_m = m;
5176 last_len = match.capturedLength();
5177 }
5178 sections.append(qt_section_chunk{last_len, QStringView{*this}.sliced(last_m, n - last_m)});
5179
5180 return extractSections(sections, start, end, flags);
5181}
5182#endif // QT_CONFIG(regularexpression)
5183
5184/*!
5185 \fn QString QString::left(qsizetype n) const &
5186 \fn QString QString::left(qsizetype n) &&
5187
5188 Returns a substring that contains the \a n leftmost characters of
5189 this string (that is, from the beginning of this string up to, but not
5190 including, the element at index position \a n).
5191
5192 If you know that \a n cannot be out of bounds, use first() instead in new
5193 code, because it is faster.
5194
5195 The entire string is returned if \a n is greater than or equal
5196 to size(), or less than zero.
5197
5198 \sa first(), last(), startsWith(), chopped(), chop(), truncate()
5199*/
5200
5201/*!
5202 \fn QString QString::right(qsizetype n) const &
5203 \fn QString QString::right(qsizetype n) &&
5204
5205 Returns a substring that contains the \a n rightmost characters
5206 of the string.
5207
5208 If you know that \a n cannot be out of bounds, use last() instead in new
5209 code, because it is faster.
5210
5211 The entire string is returned if \a n is greater than or equal
5212 to size(), or less than zero.
5213
5214 \sa endsWith(), last(), first(), sliced(), chopped(), chop(), truncate(), slice()
5215*/
5216
5217/*!
5218 \fn QString QString::mid(qsizetype position, qsizetype n) const &
5219 \fn QString QString::mid(qsizetype position, qsizetype n) &&
5220
5221 Returns a string that contains \a n characters of this string, starting
5222 at the specified \a position index up to, but not including, the element
5223 at index position \tt {\a position + \a n}.
5224
5225 If you know that \a position and \a n cannot be out of bounds, use sliced()
5226 instead in new code, because it is faster.
5227
5228 Returns a null string if the \a position index exceeds the
5229 length of the string. If there are less than \a n characters
5230 available in the string starting at the given \a position, or if
5231 \a n is -1 (default), the function returns all characters that
5232 are available from the specified \a position.
5233
5234 \sa first(), last(), sliced(), chopped(), chop(), truncate(), slice()
5235*/
5236QString QString::mid(qsizetype position, qsizetype n) const &
5237{
5238 qsizetype p = position;
5239 qsizetype l = n;
5240 using namespace QtPrivate;
5241 switch (QContainerImplHelper::mid(size(), &p, &l)) {
5242 case QContainerImplHelper::Null:
5243 return QString();
5244 case QContainerImplHelper::Empty:
5245 return QString(DataPointer::fromRawData(&_empty, 0));
5246 case QContainerImplHelper::Full:
5247 return *this;
5248 case QContainerImplHelper::Subset:
5249 return sliced(p, l);
5250 }
5251 Q_UNREACHABLE_RETURN(QString());
5252}
5253
5254QString QString::mid(qsizetype position, qsizetype n) &&
5255{
5256 qsizetype p = position;
5257 qsizetype l = n;
5258 using namespace QtPrivate;
5259 switch (QContainerImplHelper::mid(size(), &p, &l)) {
5260 case QContainerImplHelper::Null:
5261 return QString();
5262 case QContainerImplHelper::Empty:
5263 resize(0); // keep capacity if we've reserve()d
5264 [[fallthrough]];
5265 case QContainerImplHelper::Full:
5266 return std::move(*this);
5267 case QContainerImplHelper::Subset:
5268 return std::move(*this).sliced(p, l);
5269 }
5270 Q_UNREACHABLE_RETURN(QString());
5271}
5272
5273/*!
5274 \fn QString QString::first(qsizetype n) const &
5275 \fn QString QString::first(qsizetype n) &&
5276 \since 6.0
5277
5278 Returns a string that contains the first \a n characters of this string,
5279 (that is, from the beginning of this string up to, but not including,
5280 the element at index position \a n).
5281
5282 \note The behavior is undefined when \a n < 0 or \a n > size().
5283
5284 \snippet qstring/main.cpp 31
5285
5286 \sa last(), sliced(), startsWith(), chopped(), chop(), truncate(), slice()
5287*/
5288
5289/*!
5290 \fn QString QString::last(qsizetype n) const &
5291 \fn QString QString::last(qsizetype n) &&
5292 \since 6.0
5293
5294 Returns the string that contains the last \a n characters of this string.
5295
5296 \note The behavior is undefined when \a n < 0 or \a n > size().
5297
5298 \snippet qstring/main.cpp 48
5299
5300 \sa first(), sliced(), endsWith(), chopped(), chop(), truncate(), slice()
5301*/
5302
5303/*!
5304 \fn QString QString::sliced(qsizetype pos, qsizetype n) const &
5305 \fn QString QString::sliced(qsizetype pos, qsizetype n) &&
5306 \since 6.0
5307
5308 Returns a string that contains \a n characters of this string, starting
5309 at position \a pos up to, but not including, the element at index position
5310 \tt {\a pos + \a n}.
5311
5312 \note The behavior is undefined when \a pos < 0, \a n < 0,
5313 or \a pos + \a n > size().
5314
5315 \snippet qstring/main.cpp 34
5316
5317 \sa first(), last(), chopped(), chop(), truncate(), slice()
5318*/
5319QString QString::sliced_helper(QString &str, qsizetype pos, qsizetype n)
5320{
5321 if (n == 0)
5322 return QString(DataPointer::fromRawData(&_empty, 0));
5323 DataPointer d = std::move(str.d).sliced(pos, n);
5324 d.data()[n] = 0;
5325 return QString(std::move(d));
5326}
5327
5328/*!
5329 \fn QString QString::sliced(qsizetype pos) const &
5330 \fn QString QString::sliced(qsizetype pos) &&
5331 \since 6.0
5332 \overload
5333
5334 Returns a string that contains the portion of this string starting at
5335 position \a pos and extending to its end.
5336
5337 \note The behavior is undefined when \a pos < 0 or \a pos > size().
5338
5339 \sa first(), last(), chopped(), chop(), truncate(), slice()
5340*/
5341
5342/*!
5343 \fn QString &QString::slice(qsizetype pos, qsizetype n)
5344 \since 6.8
5345
5346 Modifies this string to start at position \a pos, up to, but not including,
5347 the character (code point) at index position \tt {\a pos + \a n}; and
5348 returns a reference to this string.
5349
5350 \note The behavior is undefined if \a pos < 0, \a n < 0,
5351 or \a pos + \a n > size().
5352
5353 \snippet qstring/main.cpp slice97
5354
5355 \sa sliced(), first(), last(), chopped(), chop(), truncate()
5356*/
5357
5358/*!
5359 \fn QString &QString::slice(qsizetype pos)
5360 \since 6.8
5361 \overload
5362
5363 Modifies this string to start at position \a pos and extending to its end,
5364 and returns a reference to this string.
5365
5366 \note The behavior is undefined if \a pos < 0 or \a pos > size().
5367
5368 \sa sliced(), first(), last(), chopped(), chop(), truncate()
5369*/
5370
5371/*!
5372 \fn QString QString::chopped(qsizetype len) const &
5373 \fn QString QString::chopped(qsizetype len) &&
5374 \since 5.10
5375
5376 Returns a string that contains the size() - \a len leftmost characters
5377 of this string.
5378
5379 \note The behavior is undefined if \a len is negative or greater than size().
5380
5381 \sa endsWith(), first(), last(), sliced(), chop(), truncate(), slice()
5382*/
5383
5384/*!
5385 Returns \c true if the string starts with \a s; otherwise returns
5386 \c false.
5387
5388 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
5389
5390 \snippet qstring/main.cpp 65
5391
5392 \sa endsWith()
5393*/
5394bool QString::startsWith(const QString& s, Qt::CaseSensitivity cs) const
5395{
5396 return qt_starts_with_impl(QStringView(*this), QStringView(s), cs);
5397}
5398
5399/*!
5400 \overload startsWith()
5401 */
5402bool QString::startsWith(QLatin1StringView s, Qt::CaseSensitivity cs) const
5403{
5404 return qt_starts_with_impl(QStringView(*this), s, cs);
5405}
5406
5407/*!
5408 \overload startsWith()
5409
5410 Returns \c true if the string starts with \a c; otherwise returns
5411 \c false.
5412*/
5413bool QString::startsWith(QChar c, Qt::CaseSensitivity cs) const
5414{
5415 if (!size())
5416 return false;
5417 if (cs == Qt::CaseSensitive)
5418 return at(0) == c;
5419 return foldCase(at(0)) == foldCase(c);
5420}
5421
5422/*!
5423 \fn bool QString::startsWith(QStringView str, Qt::CaseSensitivity cs) const
5424 \since 5.10
5425 \overload
5426
5427 Returns \c true if the string starts with the string view \a str;
5428 otherwise returns \c false.
5429
5430 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
5431
5432 \sa endsWith()
5433*/
5434
5435/*!
5436 Returns \c true if the string ends with \a s; otherwise returns
5437 \c false.
5438
5439 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
5440
5441 \snippet qstring/main.cpp 20
5442
5443 \sa startsWith()
5444*/
5445bool QString::endsWith(const QString &s, Qt::CaseSensitivity cs) const
5446{
5447 return qt_ends_with_impl(QStringView(*this), QStringView(s), cs);
5448}
5449
5450/*!
5451 \fn bool QString::endsWith(QStringView str, Qt::CaseSensitivity cs) const
5452 \since 5.10
5453 \overload endsWith()
5454 Returns \c true if the string ends with the string view \a str;
5455 otherwise returns \c false.
5456
5457 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
5458
5459 \sa startsWith()
5460*/
5461
5462/*!
5463 \overload endsWith()
5464*/
5465bool QString::endsWith(QLatin1StringView s, Qt::CaseSensitivity cs) const
5466{
5467 return qt_ends_with_impl(QStringView(*this), s, cs);
5468}
5469
5470/*!
5471 Returns \c true if the string ends with \a c; otherwise returns
5472 \c false.
5473
5474 \overload endsWith()
5475 */
5476bool QString::endsWith(QChar c, Qt::CaseSensitivity cs) const
5477{
5478 if (!size())
5479 return false;
5480 if (cs == Qt::CaseSensitive)
5481 return at(size() - 1) == c;
5482 return foldCase(at(size() - 1)) == foldCase(c);
5483}
5484
5485static bool checkCase(QStringView s, QUnicodeTables::Case c) noexcept
5486{
5487 QStringIterator it(s);
5488 while (it.hasNext()) {
5489 const char32_t uc = it.next();
5490 if (caseConversion(uc)[c].diff)
5491 return false;
5492 }
5493 return true;
5494}
5495
5496bool QtPrivate::isLower(QStringView s) noexcept
5497{
5498 return checkCase(s, QUnicodeTables::LowerCase);
5499}
5500
5501bool QtPrivate::isUpper(QStringView s) noexcept
5502{
5503 return checkCase(s, QUnicodeTables::UpperCase);
5504}
5505
5506/*!
5507 Returns \c true if the string is uppercase, that is, it's identical
5508 to its toUpper() folding.
5509
5510 Note that this does \e not mean that the string does not contain
5511 lowercase letters (some lowercase letters do not have a uppercase
5512 folding; they are left unchanged by toUpper()).
5513 For more information, refer to the Unicode standard, section 3.13.
5514
5515 \since 5.12
5516
5517 \sa QChar::toUpper(), isLower()
5518*/
5519bool QString::isUpper() const
5520{
5521 return QtPrivate::isUpper(qToStringViewIgnoringNull(*this));
5522}
5523
5524/*!
5525 Returns \c true if the string is lowercase, that is, it's identical
5526 to its toLower() folding.
5527
5528 Note that this does \e not mean that the string does not contain
5529 uppercase letters (some uppercase letters do not have a lowercase
5530 folding; they are left unchanged by toLower()).
5531 For more information, refer to the Unicode standard, section 3.13.
5532
5533 \since 5.12
5534
5535 \sa QChar::toLower(), isUpper()
5536 */
5537bool QString::isLower() const
5538{
5539 return QtPrivate::isLower(qToStringViewIgnoringNull(*this));
5540}
5541
5542static QByteArray qt_convert_to_latin1(QStringView string);
5543
5544QByteArray QString::toLatin1_helper(const QString &string)
5545{
5546 return qt_convert_to_latin1(string);
5547}
5548
5549/*!
5550 \since 6.0
5551 \internal
5552 \relates QAnyStringView
5553
5554 Returns a UTF-16 representation of \a string as a QString.
5555
5556 \sa QString::toLatin1(), QStringView::toLatin1(), QtPrivate::convertToUtf8(),
5557 QtPrivate::convertToLocal8Bit(), QtPrivate::convertToUcs4()
5558*/
5559QString QtPrivate::convertToQString(QAnyStringView string)
5560{
5561 return string.visit([] (auto string) { return string.toString(); });
5562}
5563
5564/*!
5565 \since 5.10
5566 \internal
5567 \relates QStringView
5568
5569 Returns a Latin-1 representation of \a string as a QByteArray.
5570
5571 The behavior is undefined if \a string contains non-Latin1 characters.
5572
5573 \sa QString::toLatin1(), QStringView::toLatin1(), QtPrivate::convertToUtf8(),
5574 QtPrivate::convertToLocal8Bit(), QtPrivate::convertToUcs4()
5575*/
5577{
5578 return qt_convert_to_latin1(string);
5579}
5580
5581Q_NEVER_INLINE
5582static QByteArray qt_convert_to_latin1(QStringView string)
5583{
5584 if (Q_UNLIKELY(string.isNull()))
5585 return QByteArray();
5586
5587 QByteArray ba(string.size(), Qt::Uninitialized);
5588
5589 // since we own the only copy, we're going to const_cast the constData;
5590 // that avoids an unnecessary call to detach() and expansion code that will never get used
5591 qt_to_latin1(reinterpret_cast<uchar *>(const_cast<char *>(ba.constData())),
5592 string.utf16(), string.size());
5593 return ba;
5594}
5595
5596QByteArray QString::toLatin1_helper_inplace(QString &s)
5597{
5598 if (!s.isDetached())
5599 return qt_convert_to_latin1(s);
5600
5601 // We can return our own buffer to the caller.
5602 // Conversion to Latin-1 always shrinks the buffer by half.
5603 // This relies on the fact that we use QArrayData for everything behind the scenes
5604
5605 // First, do the in-place conversion. Since isDetached() == true, the data
5606 // was allocated by QArrayData, so the null terminator must be there.
5607 qsizetype length = s.size();
5608 char16_t *sdata = s.d.data();
5609 Q_ASSERT(sdata[length] == u'\0');
5610 qt_to_latin1(reinterpret_cast<uchar *>(sdata), sdata, length + 1);
5611
5612 // Move the internals over to the byte array.
5613 // Kids, avert your eyes. Don't try this at home.
5614 auto ba_d = std::move(s.d).reinterpreted<char>();
5615
5616 // Some sanity checks
5617 Q_ASSERT(ba_d.d->allocatedCapacity() >= ba_d.size);
5618 Q_ASSERT(s.isNull());
5619 Q_ASSERT(s.isEmpty());
5620 Q_ASSERT(s.constData() == QString().constData());
5621
5622 return QByteArray(std::move(ba_d));
5623}
5624
5625/*!
5626 \since 6.9
5627 \internal
5628 \relates QLatin1StringView
5629
5630 Returns a UTF-8 representation of \a string as a QByteArray.
5631*/
5632QByteArray QtPrivate::convertToUtf8(QLatin1StringView string)
5633{
5634 if (Q_UNLIKELY(string.isNull()))
5635 return QByteArray();
5636
5637 // create a QByteArray with the worst case scenario size
5638 QByteArray ba(string.size() * 2, Qt::Uninitialized);
5639 const qsizetype sz = QUtf8::convertFromLatin1(ba.data(), string) - ba.data();
5640 ba.truncate(sz);
5641
5642 return ba;
5643}
5644
5645// QLatin1 methods that use helpers from qstring.cpp
5646char16_t *QLatin1::convertToUnicode(char16_t *out, QLatin1StringView in) noexcept
5647{
5648 const qsizetype len = in.size();
5649 qt_from_latin1(out, in.data(), len);
5650 return std::next(out, len);
5651}
5652
5653char *QLatin1::convertFromUnicode(char *out, QStringView in) noexcept
5654{
5655 const qsizetype len = in.size();
5656 qt_to_latin1(reinterpret_cast<uchar *>(out), in.utf16(), len);
5657 return out + len;
5658}
5659
5660/*!
5661 \fn QByteArray QString::toLatin1() const
5662
5663 Returns a Latin-1 representation of the string as a QByteArray.
5664
5665 The returned byte array is undefined if the string contains non-Latin1
5666 characters. Those characters may be suppressed or replaced with a
5667 question mark.
5668
5669 \sa fromLatin1(), toUtf8(), toLocal8Bit(), QStringEncoder
5670*/
5671
5672static QByteArray qt_convert_to_local_8bit(QStringView string);
5673
5674/*!
5675 \fn QByteArray QString::toLocal8Bit() const
5676
5677 Returns the local 8-bit representation of the string as a
5678 QByteArray.
5679
5680 \include qstring.qdocinc {qstring-local-8-bit-equivalent} {toUtf8}
5681
5682 If this string contains any characters that cannot be encoded in the
5683 local 8-bit encoding, the returned byte array is undefined. Those
5684 characters may be suppressed or replaced by another.
5685
5686 \sa fromLocal8Bit(), toLatin1(), toUtf8(), QStringEncoder
5687*/
5688
5689QByteArray QString::toLocal8Bit_helper(const QChar *data, qsizetype size)
5690{
5691 return qt_convert_to_local_8bit(QStringView(data, size));
5692}
5693
5694static QByteArray qt_convert_to_local_8bit(QStringView string)
5695{
5696 if (string.isNull())
5697 return QByteArray();
5698 QStringEncoder fromUtf16(QStringEncoder::System, QStringEncoder::Flag::Stateless);
5699 return fromUtf16(string);
5700}
5701
5702/*!
5703 \since 5.10
5704 \internal
5705 \relates QStringView
5706
5707 Returns a local 8-bit representation of \a string as a QByteArray.
5708
5709 On Unix systems this is equivalent to toUtf8(), on Windows the systems
5710 current code page is being used.
5711
5712 The behavior is undefined if \a string contains characters not
5713 supported by the locale's 8-bit encoding.
5714
5715 \sa QString::toLocal8Bit(), QStringView::toLocal8Bit()
5716*/
5718{
5719 return qt_convert_to_local_8bit(string);
5720}
5721
5722static QByteArray qt_convert_to_utf8(QStringView str);
5723
5724/*!
5725 \fn QByteArray QString::toUtf8() const
5726
5727 Returns a UTF-8 representation of the string as a QByteArray.
5728
5729 UTF-8 is a Unicode codec and can represent all characters in a Unicode
5730 string like QString.
5731
5732 \sa fromUtf8(), toLatin1(), toLocal8Bit(), QStringEncoder
5733*/
5734
5735QByteArray QString::toUtf8_helper(const QString &str)
5736{
5737 return qt_convert_to_utf8(str);
5738}
5739
5740static QByteArray qt_convert_to_utf8(QStringView str)
5741{
5742 if (str.isNull())
5743 return QByteArray();
5744
5745 return QUtf8::convertFromUnicode(str);
5746}
5747
5748/*!
5749 \since 5.10
5750 \internal
5751 \relates QStringView
5752
5753 Returns a UTF-8 representation of \a string as a QByteArray.
5754
5755 UTF-8 is a Unicode codec and can represent all characters in a Unicode
5756 string like QStringView.
5757
5758 \sa QString::toUtf8(), QStringView::toUtf8()
5759*/
5761{
5762 return qt_convert_to_utf8(string);
5763}
5764
5765static QList<uint> qt_convert_to_ucs4(QStringView string);
5766
5767/*!
5768 \since 4.2
5769
5770 Returns a UCS-4/UTF-32 representation of the string as a QList<uint>.
5771
5772 UTF-32 is a Unicode codec and therefore it is lossless. All characters from
5773 this string will be encoded in UTF-32. Any invalid sequence of code units in
5774 this string is replaced by the Unicode replacement character
5775 (QChar::ReplacementCharacter, which corresponds to \c{U+FFFD}).
5776
5777 The returned list is not 0-terminated.
5778
5779 \sa fromUtf8(), toUtf8(), toLatin1(), toLocal8Bit(), QStringEncoder,
5780 fromUcs4(), toWCharArray()
5781*/
5782QList<uint> QString::toUcs4() const
5783{
5784 return qt_convert_to_ucs4(*this);
5785}
5786
5787static QList<uint> qt_convert_to_ucs4(QStringView string)
5788{
5789 QList<uint> v(string.size());
5790 uint *a = const_cast<uint*>(v.constData());
5791 QStringIterator it(string);
5792 while (it.hasNext())
5793 *a++ = it.next();
5794 v.resize(a - v.constData());
5795 return v;
5796}
5797
5798/*!
5799 \since 5.10
5800 \internal
5801 \relates QStringView
5802
5803 Returns a UCS-4/UTF-32 representation of \a string as a QList<uint>.
5804
5805 UTF-32 is a Unicode codec and therefore it is lossless. All characters from
5806 this string will be encoded in UTF-32. Any invalid sequence of code units in
5807 this string is replaced by the Unicode replacement character
5808 (QChar::ReplacementCharacter, which corresponds to \c{U+FFFD}).
5809
5810 The returned list is not 0-terminated.
5811
5812 \sa QString::toUcs4(), QStringView::toUcs4(), QtPrivate::convertToLatin1(),
5813 QtPrivate::convertToLocal8Bit(), QtPrivate::convertToUtf8()
5814*/
5815QList<uint> QtPrivate::convertToUcs4(QStringView string)
5816{
5817 return qt_convert_to_ucs4(string);
5818}
5819
5820/*!
5821 \fn QString QString::fromLatin1(QByteArrayView str)
5822 \overload
5823 \since 6.0
5824
5825 Returns a QString initialized with the Latin-1 string \a str.
5826
5827 \note: any null ('\\0') bytes in the byte array will be included in this
5828 string, converted to Unicode null characters (U+0000).
5829*/
5830QString QString::fromLatin1(QByteArrayView ba)
5831{
5832 DataPointer d;
5833 if (!ba.data()) {
5834 // nothing to do
5835 } else if (ba.size() == 0) {
5836 d = DataPointer::fromRawData(&_empty, 0);
5837 } else {
5838 d = DataPointer(ba.size(), ba.size());
5839 Q_CHECK_PTR(d.data());
5840 d.data()[ba.size()] = '\0';
5841 char16_t *dst = d.data();
5842
5843 qt_from_latin1(dst, ba.data(), size_t(ba.size()));
5844 }
5845 return QString(std::move(d));
5846}
5847
5848/*!
5849 \fn QString QString::fromLatin1(const char *str, qsizetype size)
5850 Returns a QString initialized with the first \a size characters
5851 of the Latin-1 string \a str.
5852
5853 If \a size is \c{-1}, \c{strlen(str)} is used instead.
5854
5855 \sa toLatin1(), fromUtf8(), fromLocal8Bit()
5856*/
5857
5858/*!
5859 \fn QString QString::fromLatin1(const QByteArray &str)
5860 \overload
5861 \since 5.0
5862
5863 Returns a QString initialized with the Latin-1 string \a str.
5864
5865 \note: any null ('\\0') bytes in the byte array will be included in this
5866 string, converted to Unicode null characters (U+0000). This behavior is
5867 different from Qt 5.x.
5868*/
5869
5870/*!
5871 \fn QString QString::fromLocal8Bit(const char *str, qsizetype size)
5872 Returns a QString initialized with the first \a size characters
5873 of the 8-bit string \a str.
5874
5875 If \a size is \c{-1}, \c{strlen(str)} is used instead.
5876
5877 \include qstring.qdocinc {qstring-local-8-bit-equivalent} {fromUtf8}
5878
5879 \sa toLocal8Bit(), fromLatin1(), fromUtf8()
5880*/
5881
5882/*!
5883 \fn QString QString::fromLocal8Bit(const QByteArray &str)
5884 \overload
5885 \since 5.0
5886
5887 Returns a QString initialized with the 8-bit string \a str.
5888
5889 \include qstring.qdocinc {qstring-local-8-bit-equivalent} {fromUtf8}
5890
5891 \note: any null ('\\0') bytes in the byte array will be included in this
5892 string, converted to Unicode null characters (U+0000). This behavior is
5893 different from Qt 5.x.
5894*/
5895
5896/*!
5897 \fn QString QString::fromLocal8Bit(QByteArrayView str)
5898 \overload
5899 \since 6.0
5900
5901 Returns a QString initialized with the 8-bit string \a str.
5902
5903 \include qstring.qdocinc {qstring-local-8-bit-equivalent} {fromUtf8}
5904
5905 \note: any null ('\\0') bytes in the byte array will be included in this
5906 string, converted to Unicode null characters (U+0000).
5907*/
5908QString QString::fromLocal8Bit(QByteArrayView ba)
5909{
5910 if (ba.isNull())
5911 return QString();
5912 if (ba.isEmpty())
5913 return QString(DataPointer::fromRawData(&_empty, 0));
5914 QStringDecoder toUtf16(QStringDecoder::System, QStringDecoder::Flag::Stateless);
5915 return toUtf16(ba);
5916}
5917
5918/*! \fn QString QString::fromUtf8(const char *str, qsizetype size)
5919 Returns a QString initialized with the first \a size bytes
5920 of the UTF-8 string \a str.
5921
5922 If \a size is \c{-1}, \c{strlen(str)} is used instead.
5923
5924 UTF-8 is a Unicode codec and can represent all characters in a Unicode
5925 string like QString. However, invalid sequences are possible with UTF-8
5926 and, if any such are found, they will be replaced with one or more
5927 "replacement characters", or suppressed. These include non-Unicode
5928 sequences, non-characters, overlong sequences or surrogate codepoints
5929 encoded into UTF-8.
5930
5931 This function can be used to process incoming data incrementally as long as
5932 all UTF-8 characters are terminated within the incoming data. Any
5933 unterminated characters at the end of the string will be replaced or
5934 suppressed. In order to do stateful decoding, please use \l QStringDecoder.
5935
5936 \sa toUtf8(), fromLatin1(), fromLocal8Bit()
5937*/
5938
5939/*!
5940 \fn QString QString::fromUtf8(const char8_t *str)
5941 \overload
5942 \since 6.1
5943
5944 This overload is only available when compiling in C++20 mode.
5945*/
5946
5947/*!
5948 \fn QString QString::fromUtf8(const char8_t *str, qsizetype size)
5949 \overload
5950 \since 6.0
5951
5952 This overload is only available when compiling in C++20 mode.
5953*/
5954
5955/*!
5956 \fn QString QString::fromUtf8(const QByteArray &str)
5957 \overload
5958 \since 5.0
5959
5960 Returns a QString initialized with the UTF-8 string \a str.
5961
5962 \note: any null ('\\0') bytes in the byte array will be included in this
5963 string, converted to Unicode null characters (U+0000). This behavior is
5964 different from Qt 5.x.
5965*/
5966
5967/*!
5968 \fn QString QString::fromUtf8(QByteArrayView str)
5969 \overload
5970 \since 6.0
5971
5972 Returns a QString initialized with the UTF-8 string \a str.
5973
5974 \note: any null ('\\0') bytes in the byte array will be included in this
5975 string, converted to Unicode null characters (U+0000).
5976*/
5977QString QString::fromUtf8(QByteArrayView ba)
5978{
5979 if (ba.isNull())
5980 return QString();
5981 if (ba.isEmpty())
5982 return QString(DataPointer::fromRawData(&_empty, 0));
5983 return QUtf8::convertToUnicode(ba);
5984}
5985
5986#ifndef QT_BOOTSTRAPPED
5987/*!
5988 \since 5.3
5989 Returns a QString initialized with the first \a size characters
5990 of the Unicode string \a unicode (ISO-10646-UTF-16 encoded).
5991
5992 If \a size is -1 (default), \a unicode must be '\\0'-terminated.
5993
5994 This function checks for a Byte Order Mark (BOM). If it is missing,
5995 host byte order is assumed.
5996
5997 This function is slow compared to the other Unicode conversions.
5998 Use QString(const QChar *, qsizetype) or QString(const QChar *) if possible.
5999
6000 QString makes a deep copy of the Unicode data.
6001
6002 \sa utf16(), setUtf16(), fromStdU16String()
6003*/
6004QString QString::fromUtf16(const char16_t *unicode, qsizetype size)
6005{
6006 if (!unicode)
6007 return QString();
6008 if (size < 0)
6009 size = QtPrivate::qustrlen(unicode);
6010 QStringDecoder toUtf16(QStringDecoder::Utf16, QStringDecoder::Flag::Stateless);
6011 return toUtf16(QByteArrayView(reinterpret_cast<const char *>(unicode), size * 2));
6012}
6013
6014/*!
6015 \fn QString QString::fromUtf16(const ushort *str, qsizetype size)
6016 \deprecated [6.0] Use the \c char16_t overload instead.
6017*/
6018
6019/*!
6020 \fn QString QString::fromUcs4(const uint *str, qsizetype size)
6021 \since 4.2
6022 \deprecated [6.0] Use the \c char32_t overload instead.
6023*/
6024
6025/*!
6026 \since 5.3
6027
6028 Returns a QString initialized with the first \a size characters
6029 of the Unicode string \a unicode (encoded as UTF-32).
6030
6031 If \a size is -1 (default), \a unicode must be '\\0'-terminated.
6032
6033 \sa toUcs4(), fromUtf16(), utf16(), setUtf16(), fromWCharArray(),
6034 fromStdU32String()
6035*/
6036QString QString::fromUcs4(const char32_t *unicode, qsizetype size)
6037{
6038 if (!unicode)
6039 return QString();
6040 if (size < 0) {
6041 if constexpr (sizeof(char32_t) == sizeof(wchar_t))
6042 size = wcslen(reinterpret_cast<const wchar_t *>(unicode));
6043 else
6044 size = std::char_traits<char32_t>::length(unicode);
6045 }
6046 QStringDecoder toUtf16(QStringDecoder::Utf32, QStringDecoder::Flag::Stateless);
6047 return toUtf16(QByteArrayView(reinterpret_cast<const char *>(unicode), size * 4));
6048}
6049#endif // !QT_BOOTSTRAPPED
6050
6051/*!
6052 Resizes the string to \a size characters and copies \a unicode
6053 into the string.
6054
6055 If \a unicode is \nullptr, nothing is copied, but the string is still
6056 resized to \a size.
6057
6058 \sa unicode(), setUtf16()
6059*/
6060QString& QString::setUnicode(const QChar *unicode, qsizetype size)
6061{
6062 resize(size);
6063 if (unicode && size)
6064 memcpy(d.data(), unicode, size * sizeof(QChar));
6065 return *this;
6066}
6067
6068/*!
6069 \fn QString::setUnicode(const char16_t *unicode, qsizetype size)
6070 \overload
6071 \since 6.9
6072
6073 \sa unicode(), setUtf16()
6074*/
6075
6076/*!
6077 \fn QString::setUtf16(const char16_t *unicode, qsizetype size)
6078 \since 6.9
6079
6080 Resizes the string to \a size characters and copies \a unicode
6081 into the string.
6082
6083 If \a unicode is \nullptr, nothing is copied, but the string is still
6084 resized to \a size.
6085
6086 Note that unlike fromUtf16(), this function does not consider BOMs and
6087 possibly differing byte ordering.
6088
6089 \sa utf16(), setUnicode()
6090*/
6091
6092/*!
6093 \fn QString &QString::setUtf16(const ushort *unicode, qsizetype size)
6094 \obsolete [6.10] Use the \c char16_t overload instead.
6095*/
6096
6097/*!
6098 \fn QString QString::simplified() const
6099
6100 Returns a string that has whitespace removed from the start
6101 and the end, and that has each sequence of internal whitespace
6102 replaced with a single space.
6103
6104 Whitespace means any character for which QChar::isSpace() returns
6105 \c true. This includes the ASCII characters '\\t', '\\n', '\\v',
6106 '\\f', '\\r', and ' '.
6107
6108 Example:
6109
6110 \snippet qstring/main.cpp 57
6111
6112 \sa trimmed()
6113*/
6114QString QString::simplified_helper(const QString &str)
6115{
6116 return QStringAlgorithms<const QString>::simplified_helper(str);
6117}
6118
6119QString QString::simplified_helper(QString &str)
6120{
6121 return QStringAlgorithms<QString>::simplified_helper(str);
6122}
6123
6124namespace {
6125 template <typename StringView>
6126 StringView qt_trimmed(StringView s) noexcept
6127 {
6128 const auto [begin, end] = QStringAlgorithms<const StringView>::trimmed_helper_positions(s);
6129 return StringView{begin, end};
6130 }
6131}
6132
6133/*!
6134 \fn QStringView QtPrivate::trimmed(QStringView s)
6135 \fn QLatin1StringView QtPrivate::trimmed(QLatin1StringView s)
6136 \internal
6137 \relates QStringView
6138 \since 5.10
6139
6140 Returns \a s with whitespace removed from the start and the end.
6141
6142 Whitespace means any character for which QChar::isSpace() returns
6143 \c true. This includes the ASCII characters '\\t', '\\n', '\\v',
6144 '\\f', '\\r', and ' '.
6145
6146 \sa QString::trimmed(), QStringView::trimmed(), QLatin1StringView::trimmed()
6147*/
6148QStringView QtPrivate::trimmed(QStringView s) noexcept
6149{
6150 return qt_trimmed(s);
6151}
6152
6153QLatin1StringView QtPrivate::trimmed(QLatin1StringView s) noexcept
6154{
6155 return qt_trimmed(s);
6156}
6157
6158/*!
6159 \fn QString QString::trimmed() const
6160
6161 Returns a string that has whitespace removed from the start and
6162 the end.
6163
6164 Whitespace means any character for which QChar::isSpace() returns
6165 \c true. This includes the ASCII characters '\\t', '\\n', '\\v',
6166 '\\f', '\\r', and ' '.
6167
6168 Example:
6169
6170 \snippet qstring/main.cpp 82
6171
6172 Unlike simplified(), trimmed() leaves internal whitespace alone.
6173
6174 \sa simplified()
6175*/
6176QString QString::trimmed_helper(const QString &str)
6177{
6178 return QStringAlgorithms<const QString>::trimmed_helper(str);
6179}
6180
6181QString QString::trimmed_helper(QString &str)
6182{
6183 return QStringAlgorithms<QString>::trimmed_helper(str);
6184}
6185
6186/*! \fn const QChar QString::at(qsizetype position) const
6187
6188 Returns the character at the given index \a position in the
6189 string.
6190
6191 The \a position must be a valid index position in the string
6192 (i.e., 0 <= \a position < size()).
6193
6194 \sa operator[]()
6195*/
6196
6197/*!
6198 \fn QChar &QString::operator[](qsizetype position)
6199
6200 Returns the character at the specified \a position in the string as a
6201 modifiable reference.
6202
6203 Example:
6204
6205 \snippet qstring/main.cpp 85
6206
6207 \sa at()
6208*/
6209
6210/*!
6211 \fn const QChar QString::operator[](qsizetype position) const
6212
6213 \overload operator[]()
6214*/
6215
6216/*!
6217 \fn QChar QString::front() const
6218 \since 5.10
6219
6220 Returns the first character in the string.
6221 Same as \c{at(0)}.
6222
6223 This function is provided for STL compatibility.
6224
6225 \warning Calling this function on an empty string constitutes
6226 undefined behavior.
6227
6228 \sa back(), at(), operator[]()
6229*/
6230
6231/*!
6232 \fn QChar QString::back() const
6233 \since 5.10
6234
6235 Returns the last character in the string.
6236 Same as \c{at(size() - 1)}.
6237
6238 This function is provided for STL compatibility.
6239
6240 \warning Calling this function on an empty string constitutes
6241 undefined behavior.
6242
6243 \sa front(), at(), operator[]()
6244*/
6245
6246/*!
6247 \fn QChar &QString::front()
6248 \since 5.10
6249
6250 Returns a reference to the first character in the string.
6251 Same as \c{operator[](0)}.
6252
6253 This function is provided for STL compatibility.
6254
6255 \warning Calling this function on an empty string constitutes
6256 undefined behavior.
6257
6258 \sa back(), at(), operator[]()
6259*/
6260
6261/*!
6262 \fn QChar &QString::back()
6263 \since 5.10
6264
6265 Returns a reference to the last character in the string.
6266 Same as \c{operator[](size() - 1)}.
6267
6268 This function is provided for STL compatibility.
6269
6270 \warning Calling this function on an empty string constitutes
6271 undefined behavior.
6272
6273 \sa front(), at(), operator[]()
6274*/
6275
6276/*!
6277 \fn void QString::truncate(qsizetype position)
6278
6279 Truncates the string starting from, and including, the element at index
6280 \a position.
6281
6282 If the specified \a position index is beyond the end of the
6283 string, nothing happens.
6284
6285 Example:
6286
6287 \snippet qstring/main.cpp 83
6288
6289 If \a position is negative, it is equivalent to passing zero.
6290
6291 \sa chop(), resize(), first(), QStringView::truncate()
6292*/
6293
6294void QString::truncate(qsizetype pos)
6295{
6296 if (pos < size())
6297 resize(pos);
6298}
6299
6300
6301/*!
6302 Removes \a n characters from the end of the string.
6303
6304 If \a n is greater than or equal to size(), the result is an
6305 empty string; if \a n is negative, it is equivalent to passing zero.
6306
6307 Example:
6308 \snippet qstring/main.cpp 15
6309
6310 If you want to remove characters from the \e beginning of the
6311 string, use remove() instead.
6312
6313 \sa truncate(), resize(), remove(), QStringView::chop()
6314*/
6315void QString::chop(qsizetype n)
6316{
6317 if (n > 0)
6318 resize(d.size - n);
6319}
6320
6321/*!
6322 Sets every character in the string to character \a ch. If \a size
6323 is different from -1 (default), the string is resized to \a
6324 size beforehand.
6325
6326 Example:
6327
6328 \snippet qstring/main.cpp 21
6329
6330 \sa resize()
6331*/
6332
6333QString& QString::fill(QChar ch, qsizetype size)
6334{
6335 resize(size < 0 ? d.size : size);
6336 if (d.size)
6337 std::fill(d.data(), d.data() + d.size, ch.unicode());
6338 return *this;
6339}
6340
6341/*!
6342 \fn qsizetype QString::length() const
6343
6344 Returns the number of characters in this string. Equivalent to
6345 size().
6346
6347 \sa resize()
6348*/
6349
6350/*!
6351 \fn qsizetype QString::size() const
6352
6353 Returns the number of characters in this string.
6354
6355 The last character in the string is at position size() - 1.
6356
6357 Example:
6358 \snippet qstring/main.cpp 58
6359
6360 \sa isEmpty(), resize()
6361*/
6362
6363/*!
6364 \fn qsizetype QString::max_size() const
6365 \fn qsizetype QString::maxSize()
6366 \since 6.8
6367
6368 It returns the maximum number of elements that the string can
6369 theoretically hold. In practice, the number can be much smaller,
6370 limited by the amount of memory available to the system.
6371*/
6372
6373/*! \fn bool QString::isNull() const
6374
6375 Returns \c true if this string is null; otherwise returns \c false.
6376
6377 Example:
6378
6379 \snippet qstring/main.cpp 28
6380
6381 Qt makes a distinction between null strings and empty strings for
6382 historical reasons. For most applications, what matters is
6383 whether or not a string contains any data, and this can be
6384 determined using the isEmpty() function.
6385
6386 \sa isEmpty()
6387*/
6388
6389/*! \fn bool QString::isEmpty() const
6390
6391 Returns \c true if the string has no characters; otherwise returns
6392 \c false.
6393
6394 Example:
6395
6396 \snippet qstring/main.cpp 27
6397
6398 \sa size()
6399*/
6400
6401/*! \fn QString &QString::operator+=(const QString &other)
6402
6403 Appends the string \a other onto the end of this string and
6404 returns a reference to this string.
6405
6406 Example:
6407
6408 \snippet qstring/main.cpp 84
6409
6410 This operation is typically very fast (\l{constant time}),
6411 because QString preallocates extra space at the end of the string
6412 data so it can grow without reallocating the entire string each
6413 time.
6414
6415 \sa append(), prepend()
6416*/
6417
6418/*! \fn QString &QString::operator+=(QLatin1StringView str)
6419
6420 \overload operator+=()
6421
6422 Appends the Latin-1 string viewed by \a str to this string.
6423*/
6424
6425/*! \fn QString &QString::operator+=(QUtf8StringView str)
6426 \since 6.5
6427 \overload operator+=()
6428
6429 Appends the UTF-8 string view \a str to this string.
6430*/
6431
6432/*! \fn QString &QString::operator+=(const QByteArray &ba)
6433
6434 \overload operator+=()
6435
6436 Appends the byte array \a ba to this string. The byte array is converted
6437 to Unicode using the fromUtf8() function. If any NUL characters ('\\0')
6438 are embedded in the \a ba byte array, they will be included in the
6439 transformation.
6440
6441 You can disable this function by defining
6442 \l QT_NO_CAST_FROM_ASCII when you compile your applications. This
6443 can be useful if you want to ensure that all user-visible strings
6444 go through QObject::tr(), for example.
6445*/
6446
6447/*! \fn QString &QString::operator+=(const char *str)
6448
6449 \overload operator+=()
6450
6451 Appends the string \a str to this string. The const char pointer
6452 is converted to Unicode using the fromUtf8() function.
6453
6454 You can disable this function by defining \l QT_NO_CAST_FROM_ASCII
6455 when you compile your applications. This can be useful if you want
6456 to ensure that all user-visible strings go through QObject::tr(),
6457 for example.
6458*/
6459
6460/*! \fn QString &QString::operator+=(QStringView str)
6461 \since 6.0
6462 \overload operator+=()
6463
6464 Appends the string view \a str to this string.
6465*/
6466
6467/*! \fn QString &QString::operator+=(QChar ch)
6468
6469 \overload operator+=()
6470
6471 Appends the character \a ch to the string.
6472*/
6473
6474/*!
6475 \fn bool QString::operator==(const char * const &lhs, const QString &rhs)
6476
6477 \overload operator==()
6478
6479 Returns \c true if \a lhs is equal to \a rhs; otherwise returns \c false.
6480 Note that no string is equal to \a lhs being 0.
6481
6482 Equivalent to \c {lhs != 0 && compare(lhs, rhs) == 0}.
6483*/
6484
6485/*!
6486 \fn bool QString::operator!=(const char * const &lhs, const QString &rhs)
6487
6488 Returns \c true if \a lhs is not equal to \a rhs; otherwise returns
6489 \c false.
6490
6491 For \a lhs != 0, this is equivalent to \c {compare(} \a lhs, \a rhs
6492 \c {) != 0}. Note that no string is equal to \a lhs being 0.
6493*/
6494
6495/*!
6496 \fn bool QString::operator<(const char * const &lhs, const QString &rhs)
6497
6498 Returns \c true if \a lhs is lexically less than \a rhs; otherwise
6499 returns \c false. For \a lhs != 0, this is equivalent to \c
6500 {compare(lhs, rhs) < 0}.
6501
6502 \sa {Comparing Strings}
6503*/
6504
6505/*!
6506 \fn bool QString::operator<=(const char * const &lhs, const QString &rhs)
6507
6508 Returns \c true if \a lhs is lexically less than or equal to \a rhs;
6509 otherwise returns \c false. For \a lhs != 0, this is equivalent to \c
6510 {compare(lhs, rhs) <= 0}.
6511
6512 \sa {Comparing Strings}
6513*/
6514
6515/*!
6516 \fn bool QString::operator>(const char * const &lhs, const QString &rhs)
6517
6518 Returns \c true if \a lhs is lexically greater than \a rhs; otherwise
6519 returns \c false. Equivalent to \c {compare(lhs, rhs) > 0}.
6520
6521 \sa {Comparing Strings}
6522*/
6523
6524/*!
6525 \fn bool QString::operator>=(const char * const &lhs, const QString &rhs)
6526
6527 Returns \c true if \a lhs is lexically greater than or equal to \a rhs;
6528 otherwise returns \c false. For \a lhs != 0, this is equivalent to \c
6529 {compare(lhs, rhs) >= 0}.
6530
6531 \sa {Comparing Strings}
6532*/
6533
6534/*!
6535 \fn QString operator+(const QString &s1, const QString &s2)
6536 \fn QString operator+(QString &&s1, const QString &s2)
6537 \relates QString
6538
6539 Returns a string which is the result of concatenating \a s1 and \a
6540 s2.
6541*/
6542
6543/*!
6544 \fn QString operator+(const QString &s1, const char *s2)
6545 \relates QString
6546
6547 Returns a string which is the result of concatenating \a s1 and \a
6548 s2 (\a s2 is converted to Unicode using the QString::fromUtf8()
6549 function).
6550
6551 \sa QString::fromUtf8()
6552*/
6553
6554/*!
6555 \fn QString operator+(const char *s1, const QString &s2)
6556 \relates QString
6557
6558 Returns a string which is the result of concatenating \a s1 and \a
6559 s2 (\a s1 is converted to Unicode using the QString::fromUtf8()
6560 function).
6561
6562 \sa QString::fromUtf8()
6563*/
6564
6565/*!
6566 \fn QString operator+(QStringView lhs, const QString &rhs)
6567 \fn QString operator+(const QString &lhs, QStringView rhs)
6568
6569 \relates QString
6570 \since 6.9
6571
6572 Returns a string that is the result of concatenating \a lhs and \a rhs.
6573*/
6574
6575/*!
6576 \fn int QString::compare(const QString &s1, const QString &s2, Qt::CaseSensitivity cs)
6577 \since 4.2
6578
6579 Compares the string \a s1 with the string \a s2 and returns a negative integer
6580 if \a s1 is less than \a s2, a positive integer if it is greater than \a s2,
6581 and zero if they are equal.
6582
6583 \include qstring.qdocinc {search-comparison-case-sensitivity} {comparison}
6584
6585 Case sensitive comparison is based exclusively on the numeric
6586 Unicode values of the characters and is very fast, but is not what
6587 a human would expect. Consider sorting user-visible strings with
6588 localeAwareCompare().
6589
6590 \snippet qstring/main.cpp 16
6591
6592//! [compare-isNull-vs-isEmpty]
6593 \note This function treats null strings the same as empty strings,
6594 for more details see \l {Distinction Between Null and Empty Strings}.
6595//! [compare-isNull-vs-isEmpty]
6596
6597 \sa operator==(), operator<(), operator>(), {Comparing Strings}
6598*/
6599
6600/*!
6601 \fn int QString::compare(const QString &s1, QLatin1StringView s2, Qt::CaseSensitivity cs)
6602 \since 4.2
6603 \overload compare()
6604
6605 Performs a comparison of \a s1 and \a s2, using the case
6606 sensitivity setting \a cs.
6607*/
6608
6609/*!
6610 \fn int QString::compare(QLatin1StringView s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
6611
6612 \since 4.2
6613 \overload compare()
6614
6615 Performs a comparison of \a s1 and \a s2, using the case
6616 sensitivity setting \a cs.
6617*/
6618
6619/*!
6620 \fn int QString::compare(QStringView s, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
6621
6622 \since 5.12
6623 \overload compare()
6624
6625 Performs a comparison of this with \a s, using the case
6626 sensitivity setting \a cs.
6627*/
6628
6629/*!
6630 \fn int QString::compare(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
6631
6632 \since 5.14
6633 \overload compare()
6634
6635 Performs a comparison of this with \a ch, using the case
6636 sensitivity setting \a cs.
6637*/
6638
6639/*!
6640 \overload compare()
6641 \since 4.2
6642
6643 Lexically compares this string with the string \a other and returns
6644 a negative integer if this string is less than \a other, a positive
6645 integer if it is greater than \a other, and zero if they are equal.
6646
6647 Same as compare(*this, \a other, \a cs).
6648*/
6649int QString::compare(const QString &other, Qt::CaseSensitivity cs) const noexcept
6650{
6651 return QtPrivate::compareStrings(*this, other, cs);
6652}
6653
6654/*!
6655 \internal
6656 \since 4.5
6657*/
6658int QString::compare_helper(const QChar *data1, qsizetype length1, const QChar *data2, qsizetype length2,
6659 Qt::CaseSensitivity cs) noexcept
6660{
6661 Q_ASSERT(length1 >= 0);
6662 Q_ASSERT(length2 >= 0);
6663 Q_ASSERT(data1 || length1 == 0);
6664 Q_ASSERT(data2 || length2 == 0);
6665 return QtPrivate::compareStrings(QStringView(data1, length1), QStringView(data2, length2), cs);
6666}
6667
6668/*!
6669 \overload compare()
6670 \since 4.2
6671
6672 Same as compare(*this, \a other, \a cs).
6673*/
6674int QString::compare(QLatin1StringView other, Qt::CaseSensitivity cs) const noexcept
6675{
6676 return QtPrivate::compareStrings(*this, other, cs);
6677}
6678
6679/*!
6680 \internal
6681 \since 5.0
6682*/
6683int QString::compare_helper(const QChar *data1, qsizetype length1, const char *data2, qsizetype length2,
6684 Qt::CaseSensitivity cs) noexcept
6685{
6686 Q_ASSERT(length1 >= 0);
6687 Q_ASSERT(data1 || length1 == 0);
6688 if (!data2)
6689 return qt_lencmp(length1, 0);
6690 if (Q_UNLIKELY(length2 < 0))
6691 length2 = qsizetype(strlen(data2));
6692 return QtPrivate::compareStrings(QStringView(data1, length1),
6693 QUtf8StringView(data2, length2), cs);
6694}
6695
6696/*!
6697 \fn int QString::compare(const QString &s1, QStringView s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
6698 \overload compare()
6699*/
6700
6701/*!
6702 \fn int QString::compare(QStringView s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
6703 \overload compare()
6704*/
6705
6706bool comparesEqual(const QByteArrayView &lhs, const QChar &rhs) noexcept
6707{
6708 return QtPrivate::equalStrings(QUtf8StringView(lhs), QStringView(&rhs, 1));
6709}
6710
6711Qt::strong_ordering compareThreeWay(const QByteArrayView &lhs, const QChar &rhs) noexcept
6712{
6713 const int res = QtPrivate::compareStrings(QUtf8StringView(lhs), QStringView(&rhs, 1));
6714 return Qt::compareThreeWay(res, 0);
6715}
6716
6717bool comparesEqual(const QByteArrayView &lhs, char16_t rhs) noexcept
6718{
6719 return QtPrivate::equalStrings(QUtf8StringView(lhs), QStringView(&rhs, 1));
6720}
6721
6722Qt::strong_ordering compareThreeWay(const QByteArrayView &lhs, char16_t rhs) noexcept
6723{
6724 const int res = QtPrivate::compareStrings(QUtf8StringView(lhs), QStringView(&rhs, 1));
6725 return Qt::compareThreeWay(res, 0);
6726}
6727
6728bool comparesEqual(const QByteArray &lhs, const QChar &rhs) noexcept
6729{
6730 return QtPrivate::equalStrings(QUtf8StringView(lhs), QStringView(&rhs, 1));
6731}
6732
6733Qt::strong_ordering compareThreeWay(const QByteArray &lhs, const QChar &rhs) noexcept
6734{
6735 const int res = QtPrivate::compareStrings(QUtf8StringView(lhs), QStringView(&rhs, 1));
6736 return Qt::compareThreeWay(res, 0);
6737}
6738
6739bool comparesEqual(const QByteArray &lhs, char16_t rhs) noexcept
6740{
6741 return QtPrivate::equalStrings(QUtf8StringView(lhs), QStringView(&rhs, 1));
6742}
6743
6744Qt::strong_ordering compareThreeWay(const QByteArray &lhs, char16_t rhs) noexcept
6745{
6746 const int res = QtPrivate::compareStrings(QUtf8StringView(lhs), QStringView(&rhs, 1));
6747 return Qt::compareThreeWay(res, 0);
6748}
6749
6750/*!
6751 \internal
6752 \since 6.8
6753*/
6754bool QT_FASTCALL QChar::equal_helper(QChar lhs, const char *rhs) noexcept
6755{
6756 return QtPrivate::equalStrings(QStringView(&lhs, 1), QUtf8StringView(rhs));
6757}
6758
6759int QT_FASTCALL QChar::compare_helper(QChar lhs, const char *rhs) noexcept
6760{
6761 return QtPrivate::compareStrings(QStringView(&lhs, 1), QUtf8StringView(rhs));
6762}
6763
6764/*!
6765 \internal
6766 \since 6.8
6767*/
6768bool QStringView::equal_helper(QStringView sv, const char *data, qsizetype len)
6769{
6770 Q_ASSERT(len >= 0);
6771 Q_ASSERT(data || len == 0);
6772 return QtPrivate::equalStrings(sv, QUtf8StringView(data, len));
6773}
6774
6775/*!
6776 \internal
6777 \since 6.8
6778*/
6779int QStringView::compare_helper(QStringView sv, const char *data, qsizetype len)
6780{
6781 Q_ASSERT(len >= 0);
6782 Q_ASSERT(data || len == 0);
6783 return QtPrivate::compareStrings(sv, QUtf8StringView(data, len));
6784}
6785
6786/*!
6787 \internal
6788 \since 6.8
6789*/
6790bool QLatin1StringView::equal_helper(QLatin1StringView s1, const char *s2, qsizetype len) noexcept
6791{
6792 // because qlatin1stringview.h can't include qutf8stringview.h
6793 Q_ASSERT(len >= 0);
6794 Q_ASSERT(s2 || len == 0);
6795 return QtPrivate::equalStrings(s1, QUtf8StringView(s2, len));
6796}
6797
6798/*!
6799 \internal
6800 \since 6.6
6801*/
6802int QLatin1StringView::compare_helper(const QLatin1StringView &s1, const char *s2, qsizetype len) noexcept
6803{
6804 // because qlatin1stringview.h can't include qutf8stringview.h
6805 Q_ASSERT(len >= 0);
6806 Q_ASSERT(s2 || len == 0);
6807 return QtPrivate::compareStrings(s1, QUtf8StringView(s2, len));
6808}
6809
6810/*!
6811 \internal
6812 \since 4.5
6813*/
6814int QLatin1StringView::compare_helper(const QChar *data1, qsizetype length1, QLatin1StringView s2,
6815 Qt::CaseSensitivity cs) noexcept
6816{
6817 Q_ASSERT(length1 >= 0);
6818 Q_ASSERT(data1 || length1 == 0);
6819 return QtPrivate::compareStrings(QStringView(data1, length1), s2, cs);
6820}
6821
6822/*!
6823 \fn int QString::localeAwareCompare(const QString & s1, const QString & s2)
6824
6825 Compares \a s1 with \a s2 and returns an integer less than, equal
6826 to, or greater than zero if \a s1 is less than, equal to, or
6827 greater than \a s2.
6828
6829 The comparison is performed in a locale- and also
6830 platform-dependent manner. Use this function to present sorted
6831 lists of strings to the user.
6832
6833 \sa compare(), QLocale, {Comparing Strings}
6834*/
6835
6836/*!
6837 \fn int QString::localeAwareCompare(QStringView other) const
6838 \since 6.0
6839 \overload localeAwareCompare()
6840
6841 Compares this string with the \a other string and returns an
6842 integer less than, equal to, or greater than zero if this string
6843 is less than, equal to, or greater than the \a other string.
6844
6845 The comparison is performed in a locale- and also
6846 platform-dependent manner. Use this function to present sorted
6847 lists of strings to the user.
6848
6849 Same as \c {localeAwareCompare(*this, other)}.
6850
6851 \sa {Comparing Strings}
6852*/
6853
6854/*!
6855 \fn int QString::localeAwareCompare(QStringView s1, QStringView s2)
6856 \since 6.0
6857 \overload localeAwareCompare()
6858
6859 Compares \a s1 with \a s2 and returns an integer less than, equal
6860 to, or greater than zero if \a s1 is less than, equal to, or
6861 greater than \a s2.
6862
6863 The comparison is performed in a locale- and also
6864 platform-dependent manner. Use this function to present sorted
6865 lists of strings to the user.
6866
6867 \sa {Comparing Strings}
6868*/
6869
6870
6871#if !defined(CSTR_LESS_THAN)
6872#define CSTR_LESS_THAN 1
6873#define CSTR_EQUAL 2
6874#define CSTR_GREATER_THAN 3
6875#endif
6876
6877/*!
6878 \overload localeAwareCompare()
6879
6880 Compares this string with the \a other string and returns an
6881 integer less than, equal to, or greater than zero if this string
6882 is less than, equal to, or greater than the \a other string.
6883
6884 The comparison is performed in a locale- and also
6885 platform-dependent manner. Use this function to present sorted
6886 lists of strings to the user.
6887
6888 Same as \c {localeAwareCompare(*this, other)}.
6889
6890 \sa {Comparing Strings}
6891*/
6892int QString::localeAwareCompare(const QString &other) const
6893{
6894 return localeAwareCompare_helper(constData(), size(), other.constData(), other.size());
6895}
6896
6897/*!
6898 \internal
6899 \since 4.5
6900*/
6901int QString::localeAwareCompare_helper(const QChar *data1, qsizetype length1,
6902 const QChar *data2, qsizetype length2)
6903{
6904 Q_ASSERT(length1 >= 0);
6905 Q_ASSERT(data1 || length1 == 0);
6906 Q_ASSERT(length2 >= 0);
6907 Q_ASSERT(data2 || length2 == 0);
6908
6909 // do the right thing for null and empty
6910 if (length1 == 0 || length2 == 0)
6911 return QtPrivate::compareStrings(QStringView(data1, length1), QStringView(data2, length2),
6912 Qt::CaseSensitive);
6913
6914#if QT_CONFIG(icu) || defined(Q_OS_ANDROID)
6915 return QCollator::defaultCompare(QStringView(data1, length1), QStringView(data2, length2));
6916#else
6917 const QString lhs = QString::fromRawData(data1, length1).normalized(QString::NormalizationForm_C);
6918 const QString rhs = QString::fromRawData(data2, length2).normalized(QString::NormalizationForm_C);
6919# if defined(Q_OS_WIN)
6920 int res = CompareStringEx(LOCALE_NAME_USER_DEFAULT, 0, (LPWSTR)lhs.constData(), lhs.length(), (LPWSTR)rhs.constData(), rhs.length(), NULL, NULL, 0);
6921
6922 switch (res) {
6923 case CSTR_LESS_THAN:
6924 return -1;
6925 case CSTR_GREATER_THAN:
6926 return 1;
6927 default:
6928 return 0;
6929 }
6930# elif defined (Q_OS_DARWIN)
6931 // Use CFStringCompare for comparing strings on Mac. This makes Qt order
6932 // strings the same way as native applications do, and also respects
6933 // the "Order for sorted lists" setting in the International preferences
6934 // panel.
6935 const CFStringRef thisString =
6936 CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault,
6937 reinterpret_cast<const UniChar *>(lhs.constData()), lhs.length(), kCFAllocatorNull);
6938 const CFStringRef otherString =
6939 CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault,
6940 reinterpret_cast<const UniChar *>(rhs.constData()), rhs.length(), kCFAllocatorNull);
6941
6942 const int result = CFStringCompare(thisString, otherString, kCFCompareLocalized);
6943 CFRelease(thisString);
6944 CFRelease(otherString);
6945 return result;
6946# elif defined(Q_OS_UNIX)
6947 // declared in <string.h> (no better than QtPrivate::compareStrings() on Android, sadly)
6948 return strcoll(lhs.toLocal8Bit().constData(), rhs.toLocal8Bit().constData());
6949# else
6950# error "This case shouldn't happen"
6951 return QtPrivate::compareStrings(lhs, rhs, Qt::CaseSensitive);
6952# endif
6953#endif // !QT_CONFIG(icu)
6954}
6955
6956
6957/*!
6958 \fn const QChar *QString::unicode() const
6959
6960 Returns a Unicode representation of the string.
6961 The result remains valid until the string is modified.
6962
6963 \note The returned string may not be '\\0'-terminated.
6964 Use size() to determine the length of the array.
6965
6966 \sa utf16(), fromRawData()
6967*/
6968
6969/*!
6970 \fn const ushort *QString::utf16() const
6971 \obsolete [6.11] Use nullTerminate() and cast data() to \c{const char16_t *}.
6972
6973 Returns the QString as a '\\0\'-terminated array of unsigned
6974 shorts. The result remains valid until the string is modified.
6975
6976 The returned string is in host byte order.
6977
6978 \sa unicode()
6979*/
6980
6981const ushort *QString::utf16() const
6982{
6983 if (!d.isMutable()) {
6984 // ensure '\0'-termination for ::fromRawData strings
6985 const_cast<QString*>(this)->reallocData(d.size, QArrayData::KeepSize);
6986 }
6987 return reinterpret_cast<const ushort *>(d.data());
6988}
6989
6990/*!
6991 \fn QString &QString::nullTerminate()
6992 \since 6.10
6993
6994 If this string data isn't null-terminated, this method will make a deep
6995 copy of the data and make it null-terminated.
6996
6997 A QString is null-terminated by default, however in some cases (e.g.
6998 when using fromRawData()), the string data doesn't necessarily end
6999 with a \c {\0} character, which could be a problem when calling methods
7000 that expect a null-terminated string.
7001
7002 \sa nullTerminated(), fromRawData(), setRawData()
7003*/
7004QString &QString::nullTerminate()
7005{
7006 // ensure '\0'-termination for ::fromRawData strings
7007 if (!d.isMutable())
7008 *this = QString{constData(), size()};
7009 return *this;
7010}
7011
7012/*!
7013 \fn QString QString::nullTerminated() const &
7014 \fn QString QString::nullTerminated() &&
7015 \since 6.10
7016
7017 Returns a copy of this string that is always null-terminated.
7018
7019 \sa nullTerminate(), fromRawData(), setRawData()
7020*/
7021QString QString::nullTerminated() const &
7022{
7023 // ensure '\0'-termination for ::fromRawData strings
7024 if (!d.isMutable())
7025 return QString{constData(), size()};
7026 return *this;
7027}
7028
7029QString QString::nullTerminated() &&
7030{
7031 nullTerminate();
7032 return std::move(*this);
7033}
7034
7035/*!
7036 Returns a string of size \a width that contains this string
7037 padded by the \a fill character.
7038
7039 If \a truncate is \c false and the size() of the string is more than
7040 \a width, then the returned string is a copy of the string.
7041
7042 \snippet qstring/main.cpp 32
7043
7044 If \a truncate is \c true and the size() of the string is more than
7045 \a width, then any characters in a copy of the string after
7046 position \a width are removed, and the copy is returned.
7047
7048 \snippet qstring/main.cpp 33
7049
7050 \sa rightJustified()
7051*/
7052
7053QString QString::leftJustified(qsizetype width, QChar fill, bool truncate) const
7054{
7055 QString result;
7056 qsizetype len = size();
7057 qsizetype padlen = width - len;
7058 if (padlen > 0) {
7059 result.resize(len+padlen);
7060 if (len)
7061 memcpy(result.d.data(), d.data(), sizeof(QChar)*len);
7062 QChar *uc = (QChar*)result.d.data() + len;
7063 while (padlen--)
7064 * uc++ = fill;
7065 } else {
7066 if (truncate)
7067 result = left(width);
7068 else
7069 result = *this;
7070 }
7071 return result;
7072}
7073
7074/*!
7075 Returns a string of size() \a width that contains the \a fill
7076 character followed by the string. For example:
7077
7078 \snippet qstring/main.cpp 49
7079
7080 If \a truncate is \c false and the size() of the string is more than
7081 \a width, then the returned string is a copy of the string.
7082
7083 If \a truncate is true and the size() of the string is more than
7084 \a width, then the resulting string is truncated at position \a
7085 width.
7086
7087 \snippet qstring/main.cpp 50
7088
7089 \sa leftJustified()
7090*/
7091
7092QString QString::rightJustified(qsizetype width, QChar fill, bool truncate) const
7093{
7094 QString result;
7095 qsizetype len = size();
7096 qsizetype padlen = width - len;
7097 if (padlen > 0) {
7098 result.resize(len+padlen);
7099 QChar *uc = (QChar*)result.d.data();
7100 while (padlen--)
7101 * uc++ = fill;
7102 if (len)
7103 memcpy(static_cast<void *>(uc), static_cast<const void *>(d.data()), sizeof(QChar)*len);
7104 } else {
7105 if (truncate)
7106 result = left(width);
7107 else
7108 result = *this;
7109 }
7110 return result;
7111}
7112
7113/*!
7114 \fn QString QString::toLower() const
7115
7116 Returns a lowercase copy of the string.
7117
7118 \snippet qstring/main.cpp 75
7119
7120 The case conversion will always happen in the 'C' locale. For
7121 locale-dependent case folding use QLocale::toLower()
7122
7123 \sa toUpper(), QLocale::toLower()
7124*/
7125
7126namespace QUnicodeTables {
7127/*
7128 \internal
7129 Converts the \a str string starting from the position pointed to by the \a
7130 it iterator, using the Unicode case traits \c Traits, and returns the
7131 result. The input string must not be empty (the convertCase function below
7132 guarantees that).
7133
7134 The string type \c{T} is also a template and is either \c{const QString} or
7135 \c{QString}. This function can do both copy-conversion and in-place
7136 conversion depending on the state of the \a str parameter:
7137 \list
7138 \li \c{T} is \c{const QString}: copy-convert
7139 \li \c{T} is \c{QString} and its refcount != 1: copy-convert
7140 \li \c{T} is \c{QString} and its refcount == 1: in-place convert
7141 \endlist
7142
7143 In copy-convert mode, the local variable \c{s} is detached from the input
7144 \a str. In the in-place convert mode, \a str is in moved-from state and
7145 \c{s} contains the only copy of the string, without reallocation (thus,
7146 \a it is still valid).
7147
7148 There is one pathological case left: when the in-place conversion needs to
7149 reallocate memory to grow the buffer. In that case, we need to adjust the \a
7150 it pointer.
7151 */
7152template <typename T>
7153Q_NEVER_INLINE
7155{
7156 Q_ASSERT(!str.isEmpty());
7157 QString s = std::move(str); // will copy if T is const QString
7158 QChar *pp = s.begin() + it.index(); // will detach if necessary
7159
7160 do {
7161 const auto folded = fullConvertCase(it.next(), which);
7162 if (Q_UNLIKELY(folded.size() > 1)) {
7163 if (folded.chars[0] == *pp && folded.size() == 2) {
7164 // special case: only second actually changed (e.g. surrogate pairs),
7165 // avoid slow case
7166 ++pp;
7167 *pp++ = folded.chars[1];
7168 } else {
7169 // slow path: the string is growing
7170 qsizetype inpos = it.index() - 1;
7172
7173 s.replace(outpos, 1, reinterpret_cast<const QChar *>(folded.data()), folded.size());
7174 pp = const_cast<QChar *>(s.constBegin()) + outpos + folded.size();
7175
7176 // Adjust the input iterator if we are performing an in-place conversion
7177 if constexpr (!std::is_const<T>::value)
7179 }
7180 } else {
7181 *pp++ = folded.chars[0];
7182 }
7183 } while (it.hasNext());
7184
7185 return s;
7186}
7187
7188template <typename T>
7189static QString convertCase(T &str, QUnicodeTables::Case which)
7190{
7191 const QChar *p = str.constBegin();
7192 const QChar *e = p + str.size();
7193
7194 // this avoids out of bounds check in the loop
7195 while (e != p && e[-1].isHighSurrogate())
7196 --e;
7197
7198 QStringIterator it(p, e);
7199 while (it.hasNext()) {
7200 const char32_t uc = it.next();
7201 if (caseConversion(uc)[which].diff) {
7202 it.recede();
7203 return detachAndConvertCase(str, it, which);
7204 }
7205 }
7206 return std::move(str);
7207}
7208} // namespace QUnicodeTables
7209
7210QString QString::toLower_helper(const QString &str)
7211{
7212 return QUnicodeTables::convertCase(str, QUnicodeTables::LowerCase);
7213}
7214
7215QString QString::toLower_helper(QString &str)
7216{
7217 return QUnicodeTables::convertCase(str, QUnicodeTables::LowerCase);
7218}
7219
7220/*!
7221 \fn QString QString::toCaseFolded() const
7222
7223 Returns the case folded equivalent of the string. For most Unicode
7224 characters this is the same as toLower().
7225*/
7226
7227QString QString::toCaseFolded_helper(const QString &str)
7228{
7229 return QUnicodeTables::convertCase(str, QUnicodeTables::CaseFold);
7230}
7231
7232QString QString::toCaseFolded_helper(QString &str)
7233{
7234 return QUnicodeTables::convertCase(str, QUnicodeTables::CaseFold);
7235}
7236
7237/*!
7238 \fn QString QString::toUpper() const
7239
7240 Returns an uppercase copy of the string.
7241
7242 \snippet qstring/main.cpp 81
7243
7244 The case conversion will always happen in the 'C' locale. For
7245 locale-dependent case folding use QLocale::toUpper().
7246
7247 \note In some cases the uppercase form of a string may be longer than the
7248 original.
7249
7250 \note Since 2024, the German language officially prefers to uppercase ß
7251 (U+00DF LATIN SMALL LETTER SHARP S) as ẞ (U+1E9E LATIN CAPITAL LETTER SHARP S).
7252 Qt's implementation follows Unicode, which still mandates the use of "SS".
7253 If you need to implement the new German rules, you need to manually do
7254 \c{replace(u'ß', u'ẞ')} \e{before} calling this function.
7255
7256 \sa toLower(), QLocale::toLower()
7257*/
7258
7259QString QString::toUpper_helper(const QString &str)
7260{
7261 return QUnicodeTables::convertCase(str, QUnicodeTables::UpperCase);
7262}
7263
7264QString QString::toUpper_helper(QString &str)
7265{
7266 return QUnicodeTables::convertCase(str, QUnicodeTables::UpperCase);
7267}
7268
7269/*!
7270 \since 5.5
7271
7272 Safely builds a formatted string from the format string \a cformat
7273 and an arbitrary list of arguments.
7274
7275 The format string supports the conversion specifiers, length modifiers,
7276 and flags provided by printf() in the standard C++ library. The \a cformat
7277 string and \c{%s} arguments must be UTF-8 encoded.
7278
7279 \note The \c{%lc} escape sequence expects a unicode character of type
7280 \c char16_t (as returned by QChar::unicode()), or \c ushort.
7281 The \c{%ls} escape sequence expects a pointer to a zero-terminated array
7282 of unicode characters of type \c char16_t, or \c ushort (as returned by
7283 QString::utf16()). This is at odds with the printf() in the standard C++
7284 library, which defines \c {%lc} to print a wchar_t and \c{%ls} to print
7285 a \c{wchar_t*}, and might also produce compiler warnings on platforms
7286 where the size of \c {wchar_t} is not 16 bits.
7287
7288 \warning We do not recommend using QString::asprintf() in new Qt
7289 code. Instead, consider using QTextStream or arg(), both of
7290 which support Unicode strings seamlessly and are type-safe.
7291 Here is an example that uses QTextStream:
7292
7293 \snippet qstring/main.cpp 64
7294
7295 For \l {QObject::tr()}{translations}, especially if the strings
7296 contains more than one escape sequence, you should consider using
7297 the arg() function instead. This allows the order of the
7298 replacements to be controlled by the translator.
7299
7300 \sa arg()
7301*/
7302
7303QString QString::asprintf(const char *cformat, ...)
7304{
7305 va_list ap;
7306 va_start(ap, cformat);
7307 QString s = vasprintf(cformat, ap);
7308 va_end(ap);
7309 return s;
7310}
7311
7312static void append_utf8(QString &qs, const char *cs, qsizetype len)
7313{
7314 const qsizetype oldSize = qs.size();
7315 qs.resize(oldSize + len);
7316 const QChar *newEnd = QUtf8::convertToUnicode(qs.data() + oldSize, QByteArrayView(cs, len));
7317 qs.resize(newEnd - qs.constData());
7318}
7319
7320static uint parse_flag_characters(const char * &c) noexcept
7321{
7322 uint flags = QLocaleData::ZeroPadExponent;
7323 while (true) {
7324 switch (*c) {
7325 case '#':
7328 break;
7329 case '0': flags |= QLocaleData::ZeroPadded; break;
7330 case '-': flags |= QLocaleData::LeftAdjusted; break;
7331 case ' ': flags |= QLocaleData::BlankBeforePositive; break;
7332 case '+': flags |= QLocaleData::AlwaysShowSign; break;
7333 case '\'': flags |= QLocaleData::GroupDigits; break;
7334 default: return flags;
7335 }
7336 ++c;
7337 }
7338}
7339
7340static int parse_field_width(const char *&c, qsizetype size)
7341{
7342 Q_ASSERT(isAsciiDigit(*c));
7343 const char *const stop = c + size;
7344
7345 // can't be negative - started with a digit
7346 // contains at least one digit
7347 auto [result, used] = qstrntoull(c, size, 10);
7348 c += used;
7349 if (used <= 0)
7350 return false;
7351 // preserve Qt 5.5 behavior of consuming all digits, no matter how many
7352 while (c < stop && isAsciiDigit(*c))
7353 ++c;
7354 return result < qulonglong(std::numeric_limits<int>::max()) ? int(result) : 0;
7355}
7356
7358
7359static inline bool can_consume(const char * &c, char ch) noexcept
7360{
7361 if (*c == ch) {
7362 ++c;
7363 return true;
7364 }
7365 return false;
7366}
7367
7368static LengthMod parse_length_modifier(const char * &c) noexcept
7369{
7370 switch (*c++) {
7371 case 'h': return can_consume(c, 'h') ? lm_hh : lm_h;
7372 case 'l': return can_consume(c, 'l') ? lm_ll : lm_l;
7373 case 'L': return lm_L;
7374 case 'j': return lm_j;
7375 case 'z':
7376 case 'Z': return lm_z;
7377 case 't': return lm_t;
7378 }
7379 --c; // don't consume *c - it wasn't a flag
7380 return lm_none;
7381}
7382
7383/*!
7384 \fn QString QString::vasprintf(const char *cformat, va_list ap)
7385 \since 5.5
7386
7387 Equivalent method to asprintf(), but takes a va_list \a ap
7388 instead a list of variable arguments. See the asprintf()
7389 documentation for an explanation of \a cformat.
7390
7391 This method does not call the va_end macro, the caller
7392 is responsible to call va_end on \a ap.
7393
7394 \sa asprintf()
7395*/
7396
7397QString QString::vasprintf(const char *cformat, va_list ap)
7398{
7399 if (!cformat || !*cformat) {
7400 // Qt 1.x compat
7401 return fromLatin1("");
7402 }
7403
7404 // Parse cformat
7405
7406 QString result;
7407 const char *c = cformat;
7408 const char *formatEnd = cformat + qstrlen(cformat);
7409 for (;;) {
7410 // Copy non-escape chars to result
7411 const char *cb = c;
7412 while (*c != '\0' && *c != '%')
7413 c++;
7414 append_utf8(result, cb, qsizetype(c - cb));
7415
7416 if (*c == '\0')
7417 break;
7418
7419 // Found '%'
7420 const char *escape_start = c;
7421 ++c;
7422
7423 if (*c == '\0') {
7424 result.append(u'%'); // a % at the end of the string - treat as non-escape text
7425 break;
7426 }
7427 if (*c == '%') {
7428 result.append(u'%'); // %%
7429 ++c;
7430 continue;
7431 }
7432
7433 uint flags = parse_flag_characters(c);
7434
7435 if (*c == '\0') {
7436 result.append(QLatin1StringView(escape_start)); // incomplete escape, treat as non-escape text
7437 break;
7438 }
7439
7440 // Parse field width
7441 int width = -1; // -1 means unspecified
7442 if (isAsciiDigit(*c)) {
7443 width = parse_field_width(c, formatEnd - c);
7444 } else if (*c == '*') { // can't parse this in another function, not portably, at least
7445 width = va_arg(ap, int);
7446 if (width < 0)
7447 width = -1; // treat all negative numbers as unspecified
7448 ++c;
7449 }
7450
7451 if (*c == '\0') {
7452 result.append(QLatin1StringView(escape_start)); // incomplete escape, treat as non-escape text
7453 break;
7454 }
7455
7456 // Parse precision
7457 int precision = -1; // -1 means unspecified
7458 if (*c == '.') {
7459 ++c;
7460 precision = 0;
7461 if (isAsciiDigit(*c)) {
7462 precision = parse_field_width(c, formatEnd - c);
7463 } else if (*c == '*') { // can't parse this in another function, not portably, at least
7464 precision = va_arg(ap, int);
7465 if (precision < 0)
7466 precision = -1; // treat all negative numbers as unspecified
7467 ++c;
7468 }
7469 }
7470
7471 if (*c == '\0') {
7472 result.append(QLatin1StringView(escape_start)); // incomplete escape, treat as non-escape text
7473 break;
7474 }
7475
7476 const LengthMod length_mod = parse_length_modifier(c);
7477
7478 if (*c == '\0') {
7479 result.append(QLatin1StringView(escape_start)); // incomplete escape, treat as non-escape text
7480 break;
7481 }
7482
7483 // Parse the conversion specifier and do the conversion
7484 QString subst;
7485 switch (*c) {
7486 case 'd':
7487 case 'i': {
7488 qint64 i;
7489 switch (length_mod) {
7490 case lm_none: i = va_arg(ap, int); break;
7491 case lm_hh: i = va_arg(ap, int); break;
7492 case lm_h: i = va_arg(ap, int); break;
7493 case lm_l: i = va_arg(ap, long int); break;
7494 case lm_ll: i = va_arg(ap, qint64); break;
7495 case lm_j: i = va_arg(ap, long int); break;
7496
7497 /* ptrdiff_t actually, but it should be the same for us */
7498 case lm_z: i = va_arg(ap, qsizetype); break;
7499 case lm_t: i = va_arg(ap, qsizetype); break;
7500 default: i = 0; break;
7501 }
7502 subst = QLocaleData::c()->longLongToString(i, precision, 10, width, flags);
7503 ++c;
7504 break;
7505 }
7506 case 'o':
7507 case 'u':
7508 case 'x':
7509 case 'X': {
7510 quint64 u;
7511 switch (length_mod) {
7512 case lm_none: u = va_arg(ap, uint); break;
7513 case lm_hh: u = va_arg(ap, uint); break;
7514 case lm_h: u = va_arg(ap, uint); break;
7515 case lm_l: u = va_arg(ap, ulong); break;
7516 case lm_ll: u = va_arg(ap, quint64); break;
7517 case lm_t: u = va_arg(ap, size_t); break;
7518 case lm_z: u = va_arg(ap, size_t); break;
7519 default: u = 0; break;
7520 }
7521
7522 if (isAsciiUpper(*c))
7523 flags |= QLocaleData::CapitalEorX;
7524
7525 int base = 10;
7526 switch (QtMiscUtils::toAsciiLower(*c)) {
7527 case 'o':
7528 base = 8; break;
7529 case 'u':
7530 base = 10; break;
7531 case 'x':
7532 base = 16; break;
7533 default: break;
7534 }
7535 subst = QLocaleData::c()->unsLongLongToString(u, precision, base, width, flags);
7536 ++c;
7537 break;
7538 }
7539 case 'E':
7540 case 'e':
7541 case 'F':
7542 case 'f':
7543 case 'G':
7544 case 'g':
7545 case 'A':
7546 case 'a': {
7547 double d;
7548 if (length_mod == lm_L)
7549 d = va_arg(ap, long double); // not supported - converted to a double
7550 else
7551 d = va_arg(ap, double);
7552
7553 if (isAsciiUpper(*c))
7554 flags |= QLocaleData::CapitalEorX;
7555
7556 QLocaleData::DoubleForm form = QLocaleData::DFDecimal;
7557 switch (QtMiscUtils::toAsciiLower(*c)) {
7558 case 'e': form = QLocaleData::DFExponent; break;
7559 case 'a': // not supported - decimal form used instead
7560 case 'f': form = QLocaleData::DFDecimal; break;
7561 case 'g': form = QLocaleData::DFSignificantDigits; break;
7562 default: break;
7563 }
7564 subst = QLocaleData::c()->doubleToString(d, precision, form, width, flags);
7565 ++c;
7566 break;
7567 }
7568 case 'c': {
7569 if (length_mod == lm_l)
7570 subst = QChar::fromUcs2(va_arg(ap, int));
7571 else
7572 subst = QLatin1Char((uchar) va_arg(ap, int));
7573 ++c;
7574 break;
7575 }
7576 case 's': {
7577 if (length_mod == lm_l) {
7578 const char16_t *buff = va_arg(ap, const char16_t*);
7579 const auto *ch = buff;
7580 while (precision != 0 && *ch != 0) {
7581 ++ch;
7582 --precision;
7583 }
7584 subst.setUtf16(buff, ch - buff);
7585 } else if (precision == -1) {
7586 subst = QString::fromUtf8(va_arg(ap, const char*));
7587 } else {
7588 const char *buff = va_arg(ap, const char*);
7589 subst = QString::fromUtf8(buff, qstrnlen(buff, precision));
7590 }
7591 ++c;
7592 break;
7593 }
7594 case 'p': {
7595 void *arg = va_arg(ap, void*);
7596 const quint64 i = reinterpret_cast<quintptr>(arg);
7597 flags |= QLocaleData::ShowBase;
7598 subst = QLocaleData::c()->unsLongLongToString(i, precision, 16, width, flags);
7599 ++c;
7600 break;
7601 }
7602 case 'n':
7603 switch (length_mod) {
7604 case lm_hh: {
7605 signed char *n = va_arg(ap, signed char*);
7606 *n = result.size();
7607 break;
7608 }
7609 case lm_h: {
7610 short int *n = va_arg(ap, short int*);
7611 *n = result.size();
7612 break;
7613 }
7614 case lm_l: {
7615 long int *n = va_arg(ap, long int*);
7616 *n = result.size();
7617 break;
7618 }
7619 case lm_ll: {
7620 qint64 *n = va_arg(ap, qint64*);
7621 *n = result.size();
7622 break;
7623 }
7624 default: {
7625 int *n = va_arg(ap, int*);
7626 *n = int(result.size());
7627 break;
7628 }
7629 }
7630 ++c;
7631 break;
7632
7633 default: // bad escape, treat as non-escape text
7634 for (const char *cc = escape_start; cc != c; ++cc)
7635 result.append(QLatin1Char(*cc));
7636 continue;
7637 }
7638
7639 if (flags & QLocaleData::LeftAdjusted)
7640 result.append(subst.leftJustified(width));
7641 else
7642 result.append(subst.rightJustified(width));
7643 }
7644
7645 return result;
7646}
7647
7648/*!
7649 \fn QString::toLongLong(bool *ok, int base) const
7650
7651 Returns the string converted to a \c{long long} using base \a
7652 base, which is 10 by default and must be between 2 and 36, or 0.
7653 Returns 0 if the conversion fails.
7654
7655 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7656 to \c false, and success by setting *\a{ok} to \c true.
7657
7658 If \a base is 0, the C language convention is used: if the string begins
7659 with "0x", base 16 is used; otherwise, if the string begins with "0b", base
7660 2 is used; otherwise, if the string begins with "0", base 8 is used;
7661 otherwise, base 10 is used.
7662
7663 The string conversion will always happen in the 'C' locale. For
7664 locale-dependent conversion use QLocale::toLongLong()
7665
7666 Example:
7667
7668 \snippet qstring/main.cpp 74
7669
7670 This function ignores leading and trailing whitespace.
7671
7672 \note Support for the "0b" prefix was added in Qt 6.4.
7673
7674 \sa number(), toULongLong(), toInt(), QLocale::toLongLong()
7675*/
7676
7677template <typename Int>
7678static Int toIntegral(QStringView string, bool *ok, int base)
7679{
7680#if defined(QT_CHECK_RANGE)
7681 if (base != 0 && (base < 2 || base > 36)) {
7682 qWarning("QString::toIntegral: Invalid base (%d)", base);
7683 base = 10;
7684 }
7685#endif
7686
7687 QVarLengthArray<uchar> latin1(string.size());
7688 qt_to_latin1(latin1.data(), string.utf16(), string.size());
7689 QSimpleParsedNumber<Int> r;
7690 if constexpr (std::is_signed_v<Int>)
7691 r = QLocaleData::bytearrayToLongLong(latin1, base);
7692 else
7693 r = QLocaleData::bytearrayToUnsLongLong(latin1, base);
7694 if (ok)
7695 *ok = r.ok();
7696 return r.result;
7697}
7698
7699qlonglong QString::toIntegral_helper(QStringView string, bool *ok, int base)
7700{
7701 return toIntegral<qlonglong>(string, ok, base);
7702}
7703
7704/*!
7705 \fn QString::toULongLong(bool *ok, int base) const
7706
7707 Returns the string converted to an \c{unsigned long long} using base \a
7708 base, which is 10 by default and must be between 2 and 36, or 0.
7709 Returns 0 if the conversion fails.
7710
7711 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7712 to \c false, and success by setting *\a{ok} to \c true.
7713
7714 If \a base is 0, the C language convention is used: if the string begins
7715 with "0x", base 16 is used; otherwise, if the string begins with "0b", base
7716 2 is used; otherwise, if the string begins with "0", base 8 is used;
7717 otherwise, base 10 is used.
7718
7719 The string conversion will always happen in the 'C' locale. For
7720 locale-dependent conversion use QLocale::toULongLong()
7721
7722 Example:
7723
7724 \snippet qstring/main.cpp 79
7725
7726 This function ignores leading and trailing whitespace.
7727
7728 \note Support for the "0b" prefix was added in Qt 6.4.
7729
7730 \sa number(), toLongLong(), QLocale::toULongLong()
7731*/
7732
7733qulonglong QString::toIntegral_helper(QStringView string, bool *ok, uint base)
7734{
7735 return toIntegral<qulonglong>(string, ok, base);
7736}
7737
7738/*!
7739 \fn long QString::toLong(bool *ok, int base) const
7740
7741 Returns the string converted to a \c long using base \a
7742 base, which is 10 by default and must be between 2 and 36, or 0.
7743 Returns 0 if the conversion fails.
7744
7745 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7746 to \c false, and success by setting *\a{ok} to \c true.
7747
7748 If \a base is 0, the C language convention is used: if the string begins
7749 with "0x", base 16 is used; otherwise, if the string begins with "0b", base
7750 2 is used; otherwise, if the string begins with "0", base 8 is used;
7751 otherwise, base 10 is used.
7752
7753 The string conversion will always happen in the 'C' locale. For
7754 locale-dependent conversion use QLocale::toLongLong()
7755
7756 Example:
7757
7758 \snippet qstring/main.cpp 73
7759
7760 This function ignores leading and trailing whitespace.
7761
7762 \note Support for the "0b" prefix was added in Qt 6.4.
7763
7764 \sa number(), toULong(), toInt(), QLocale::toInt()
7765*/
7766
7767/*!
7768 \fn ulong QString::toULong(bool *ok, int base) const
7769
7770 Returns the string converted to an \c{unsigned long} using base \a
7771 base, which is 10 by default and must be between 2 and 36, or 0.
7772 Returns 0 if the conversion fails.
7773
7774 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7775 to \c false, and success by setting *\a{ok} to \c true.
7776
7777 If \a base is 0, the C language convention is used: if the string begins
7778 with "0x", base 16 is used; otherwise, if the string begins with "0b", base
7779 2 is used; otherwise, if the string begins with "0", base 8 is used;
7780 otherwise, base 10 is used.
7781
7782 The string conversion will always happen in the 'C' locale. For
7783 locale-dependent conversion use QLocale::toULongLong()
7784
7785 Example:
7786
7787 \snippet qstring/main.cpp 78
7788
7789 This function ignores leading and trailing whitespace.
7790
7791 \note Support for the "0b" prefix was added in Qt 6.4.
7792
7793 \sa number(), QLocale::toUInt()
7794*/
7795
7796/*!
7797 \fn int QString::toInt(bool *ok, int base) const
7798 Returns the string converted to an \c int using base \a
7799 base, which is 10 by default and must be between 2 and 36, or 0.
7800 Returns 0 if the conversion fails.
7801
7802 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7803 to \c false, and success by setting *\a{ok} to \c true.
7804
7805 If \a base is 0, the C language convention is used: if the string begins
7806 with "0x", base 16 is used; otherwise, if the string begins with "0b", base
7807 2 is used; otherwise, if the string begins with "0", base 8 is used;
7808 otherwise, base 10 is used.
7809
7810 The string conversion will always happen in the 'C' locale. For
7811 locale-dependent conversion use QLocale::toInt()
7812
7813 Example:
7814
7815 \snippet qstring/main.cpp 72
7816
7817 This function ignores leading and trailing whitespace.
7818
7819 \note Support for the "0b" prefix was added in Qt 6.4.
7820
7821 \sa number(), toUInt(), toDouble(), QLocale::toInt()
7822*/
7823
7824/*!
7825 \fn uint QString::toUInt(bool *ok, int base) const
7826 Returns the string converted to an \c{unsigned int} using base \a
7827 base, which is 10 by default and must be between 2 and 36, or 0.
7828 Returns 0 if the conversion fails.
7829
7830 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7831 to \c false, and success by setting *\a{ok} to \c true.
7832
7833 If \a base is 0, the C language convention is used: if the string begins
7834 with "0x", base 16 is used; otherwise, if the string begins with "0b", base
7835 2 is used; otherwise, if the string begins with "0", base 8 is used;
7836 otherwise, base 10 is used.
7837
7838 The string conversion will always happen in the 'C' locale. For
7839 locale-dependent conversion use QLocale::toUInt()
7840
7841 Example:
7842
7843 \snippet qstring/main.cpp 77
7844
7845 This function ignores leading and trailing whitespace.
7846
7847 \note Support for the "0b" prefix was added in Qt 6.4.
7848
7849 \sa number(), toInt(), QLocale::toUInt()
7850*/
7851
7852/*!
7853 \fn short QString::toShort(bool *ok, int base) const
7854
7855 Returns the string converted to a \c short using base \a
7856 base, which is 10 by default and must be between 2 and 36, or 0.
7857 Returns 0 if the conversion fails.
7858
7859 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7860 to \c false, and success by setting *\a{ok} to \c true.
7861
7862 If \a base is 0, the C language convention is used: if the string begins
7863 with "0x", base 16 is used; otherwise, if the string begins with "0b", base
7864 2 is used; otherwise, if the string begins with "0", base 8 is used;
7865 otherwise, base 10 is used.
7866
7867 The string conversion will always happen in the 'C' locale. For
7868 locale-dependent conversion use QLocale::toShort()
7869
7870 Example:
7871
7872 \snippet qstring/main.cpp 76
7873
7874 This function ignores leading and trailing whitespace.
7875
7876 \note Support for the "0b" prefix was added in Qt 6.4.
7877
7878 \sa number(), toUShort(), toInt(), QLocale::toShort()
7879*/
7880
7881/*!
7882 \fn ushort QString::toUShort(bool *ok, int base) const
7883
7884 Returns the string converted to an \c{unsigned short} using base \a
7885 base, which is 10 by default and must be between 2 and 36, or 0.
7886 Returns 0 if the conversion fails.
7887
7888 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7889 to \c false, and success by setting *\a{ok} to \c true.
7890
7891 If \a base is 0, the C language convention is used: if the string begins
7892 with "0x", base 16 is used; otherwise, if the string begins with "0b", base
7893 2 is used; otherwise, if the string begins with "0", base 8 is used;
7894 otherwise, base 10 is used.
7895
7896 The string conversion will always happen in the 'C' locale. For
7897 locale-dependent conversion use QLocale::toUShort()
7898
7899 Example:
7900
7901 \snippet qstring/main.cpp 80
7902
7903 This function ignores leading and trailing whitespace.
7904
7905 \note Support for the "0b" prefix was added in Qt 6.4.
7906
7907 \sa number(), toShort(), QLocale::toUShort()
7908*/
7909
7910/*!
7911 Returns the string converted to a \c double value.
7912
7913 Returns an infinity if the conversion overflows or 0.0 if the
7914 conversion fails for other reasons (e.g. underflow).
7915
7916 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7917 to \c false, and success by setting *\a{ok} to \c true.
7918
7919 \snippet qstring/main.cpp 66
7920
7921 \warning The QString content may only contain valid numerical characters
7922 which includes the plus/minus sign, the character e used in scientific
7923 notation, and the decimal point. Including the unit or additional characters
7924 leads to a conversion error.
7925
7926 \snippet qstring/main.cpp 67
7927
7928 The string conversion will always happen in the 'C' locale. For
7929 locale-dependent conversion use QLocale::toDouble()
7930
7931 \snippet qstring/main.cpp 68
7932
7933 For historical reasons, this function does not handle
7934 thousands group separators. If you need to convert such numbers,
7935 use QLocale::toDouble().
7936
7937 \snippet qstring/main.cpp 69
7938
7939 This function ignores leading and trailing whitespace.
7940
7941 \sa number(), QLocale::setDefault(), QLocale::toDouble(), trimmed()
7942*/
7943
7944double QString::toDouble(bool *ok) const
7945{
7946 return QStringView(*this).toDouble(ok);
7947}
7948
7949double QStringView::toDouble(bool *ok) const
7950{
7951 QStringView string = qt_trimmed(*this);
7952 QVarLengthArray<uchar> latin1(string.size());
7953 qt_to_latin1(latin1.data(), string.utf16(), string.size());
7954 auto r = qt_asciiToDouble(reinterpret_cast<const char *>(latin1.data()), string.size());
7955 if (ok != nullptr)
7956 *ok = r.ok();
7957 return r.result;
7958}
7959
7960/*!
7961 Returns the string converted to a \c float value.
7962
7963 Returns an infinity if the conversion overflows or 0.0 if the
7964 conversion fails for other reasons (e.g. underflow).
7965
7966 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
7967 to \c false, and success by setting *\a{ok} to \c true.
7968
7969 \warning The QString content may only contain valid numerical characters
7970 which includes the plus/minus sign, the character e used in scientific
7971 notation, and the decimal point. Including the unit or additional characters
7972 leads to a conversion error.
7973
7974 The string conversion will always happen in the 'C' locale. For
7975 locale-dependent conversion use QLocale::toFloat()
7976
7977 For historical reasons, this function does not handle
7978 thousands group separators. If you need to convert such numbers,
7979 use QLocale::toFloat().
7980
7981 Example:
7982
7983 \snippet qstring/main.cpp 71
7984
7985 This function ignores leading and trailing whitespace.
7986
7987 \sa number(), toDouble(), toInt(), QLocale::toFloat(), trimmed()
7988*/
7989
7990float QString::toFloat(bool *ok) const
7991{
7992 return QLocaleData::convertDoubleToFloat(toDouble(ok), ok);
7993}
7994
7995float QStringView::toFloat(bool *ok) const
7996{
7997 return QLocaleData::convertDoubleToFloat(toDouble(ok), ok);
7998}
7999
8000/*! \fn QString &QString::setNum(int n, int base)
8001
8002 Sets the string to the printed value of \a n in the specified \a
8003 base, and returns a reference to the string.
8004
8005 The base is 10 by default and must be between 2 and 36.
8006
8007 \snippet qstring/main.cpp 56
8008
8009 The formatting always uses QLocale::C, i.e., English/UnitedStates.
8010 To get a localized string representation of a number, use
8011 QLocale::toString() with the appropriate locale.
8012
8013 \sa number()
8014*/
8015
8016/*! \fn QString &QString::setNum(uint n, int base)
8017
8018 \overload
8019*/
8020
8021/*! \fn QString &QString::setNum(long n, int base)
8022
8023 \overload
8024*/
8025
8026/*! \fn QString &QString::setNum(ulong n, int base)
8027
8028 \overload
8029*/
8030
8031/*!
8032 \overload
8033*/
8034QString &QString::setNum(qlonglong n, int base)
8035{
8036 return *this = number(n, base);
8037}
8038
8039/*!
8040 \overload
8041*/
8042QString &QString::setNum(qulonglong n, int base)
8043{
8044 return *this = number(n, base);
8045}
8046
8047/*! \fn QString &QString::setNum(short n, int base)
8048
8049 \overload
8050*/
8051
8052/*! \fn QString &QString::setNum(ushort n, int base)
8053
8054 \overload
8055*/
8056
8057/*!
8058 \overload
8059
8060 Sets the string to the printed value of \a n, formatted according to the
8061 given \a format and \a precision, and returns a reference to the string.
8062
8063 \sa number(), QLocale::FloatingPointPrecisionOption, {Number formats}
8064*/
8065
8066QString &QString::setNum(double n, char format, int precision)
8067{
8068 return *this = number(n, format, precision);
8069}
8070
8071/*!
8072 \fn QString &QString::setNum(float n, char format, int precision)
8073 \overload
8074
8075 Sets the string to the printed value of \a n, formatted according
8076 to the given \a format and \a precision, and returns a reference
8077 to the string.
8078
8079 The formatting always uses QLocale::C, i.e., English/UnitedStates.
8080 To get a localized string representation of a number, use
8081 QLocale::toString() with the appropriate locale.
8082
8083 \sa number()
8084*/
8085
8086
8087/*!
8088 \fn QString QString::number(long n, int base)
8089
8090 Returns a string equivalent of the number \a n according to the
8091 specified \a base.
8092
8093 The base is 10 by default and must be between 2
8094 and 36. For bases other than 10, \a n is treated as an
8095 unsigned integer.
8096
8097 The formatting always uses QLocale::C, i.e., English/UnitedStates.
8098 To get a localized string representation of a number, use
8099 QLocale::toString() with the appropriate locale.
8100
8101 \snippet qstring/main.cpp 35
8102
8103 \sa setNum()
8104*/
8105
8106QString QString::number(long n, int base)
8107{
8108 return number(qlonglong(n), base);
8109}
8110
8111/*!
8112 \fn QString QString::number(ulong n, int base)
8113
8114 \overload
8115*/
8116QString QString::number(ulong n, int base)
8117{
8118 return number(qulonglong(n), base);
8119}
8120
8121/*!
8122 \overload
8123*/
8124QString QString::number(int n, int base)
8125{
8126 return number(qlonglong(n), base);
8127}
8128
8129/*!
8130 \overload
8131*/
8132QString QString::number(uint n, int base)
8133{
8134 return number(qulonglong(n), base);
8135}
8136
8137/*!
8138 \overload
8139*/
8140QString QString::number(qlonglong n, int base)
8141{
8142#if defined(QT_CHECK_RANGE)
8143 if (base < 2 || base > 36) {
8144 qWarning("QString::setNum: Invalid base (%d)", base);
8145 base = 10;
8146 }
8147#endif
8148 bool negative = n < 0;
8149 /*
8150 Negating std::numeric_limits<qlonglong>::min() hits undefined behavior, so
8151 taking an absolute value has to take a slight detour.
8152 */
8153 return qulltoBasicLatin(negative ? 1u + qulonglong(-(n + 1)) : qulonglong(n), base, negative);
8154}
8155
8156/*!
8157 \overload
8158*/
8159QString QString::number(qulonglong n, int base)
8160{
8161#if defined(QT_CHECK_RANGE)
8162 if (base < 2 || base > 36) {
8163 qWarning("QString::setNum: Invalid base (%d)", base);
8164 base = 10;
8165 }
8166#endif
8167 return qulltoBasicLatin(n, base, false);
8168}
8169
8170
8171/*!
8172 Returns a string representing the floating-point number \a n.
8173
8174 Returns a string that represents \a n, formatted according to the specified
8175 \a format and \a precision.
8176
8177 For formats with an exponent, the exponent will show its sign and have at
8178 least two digits, left-padding the exponent with zero if needed.
8179
8180 \sa setNum(), QLocale::toString(), QLocale::FloatingPointPrecisionOption, {Number formats}
8181*/
8182QString QString::number(double n, char format, int precision)
8183{
8184 QLocaleData::DoubleForm form = QLocaleData::DFDecimal;
8185
8186 switch (QtMiscUtils::toAsciiLower(format)) {
8187 case 'f':
8188 form = QLocaleData::DFDecimal;
8189 break;
8190 case 'e':
8191 form = QLocaleData::DFExponent;
8192 break;
8193 case 'g':
8194 form = QLocaleData::DFSignificantDigits;
8195 break;
8196 default:
8197#if defined(QT_CHECK_RANGE)
8198 qWarning("QString::setNum: Invalid format char '%c'", format);
8199#endif
8200 break;
8201 }
8202
8203 return qdtoBasicLatin(n, form, precision, isAsciiUpper(format));
8204}
8205
8206namespace {
8207template<class ResultList, class StringSource>
8208static ResultList splitString(const StringSource &source, QStringView sep,
8209 Qt::SplitBehavior behavior, Qt::CaseSensitivity cs)
8210{
8211 ResultList list;
8212 typename StringSource::size_type start = 0;
8213 typename StringSource::size_type end;
8214 typename StringSource::size_type extra = 0;
8215 while ((end = QtPrivate::findString(QStringView(source.constData(), source.size()), start + extra, sep, cs)) != -1) {
8216 if (start != end || behavior == Qt::KeepEmptyParts)
8217 list.append(source.sliced(start, end - start));
8218 start = end + sep.size();
8219 extra = (sep.size() == 0 ? 1 : 0);
8220 }
8221 if (start != source.size() || behavior == Qt::KeepEmptyParts)
8222 list.append(source.sliced(start));
8223 return list;
8224}
8225
8226} // namespace
8227
8228/*!
8229 Splits the string into substrings wherever \a sep occurs, and
8230 returns the list of those strings. If \a sep does not match
8231 anywhere in the string, split() returns a single-element list
8232 containing this string.
8233
8234 \a cs specifies whether \a sep should be matched case
8235 sensitively or case insensitively.
8236
8237 If \a behavior is Qt::SkipEmptyParts, empty entries don't
8238 appear in the result. By default, empty entries are kept.
8239
8240 Example:
8241
8242 \snippet qstring/main.cpp 62
8243
8244 If \a sep is empty, split() returns an empty string, followed
8245 by each of the string's characters, followed by another empty string:
8246
8247 \snippet qstring/main.cpp 62-empty
8248
8249 To understand this behavior, recall that the empty string matches
8250 everywhere, so the above is qualitatively the same as:
8251
8252 \snippet qstring/main.cpp 62-slashes
8253
8254 \sa QStringList::join(), section()
8255
8256 \since 5.14
8257*/
8258QStringList QString::split(const QString &sep, Qt::SplitBehavior behavior, Qt::CaseSensitivity cs) const
8259{
8260 return splitString<QStringList>(*this, sep, behavior, cs);
8261}
8262
8263/*!
8264 \overload
8265 \since 5.14
8266*/
8267QStringList QString::split(QChar sep, Qt::SplitBehavior behavior, Qt::CaseSensitivity cs) const
8268{
8269 return splitString<QStringList>(*this, QStringView(&sep, 1), behavior, cs);
8270}
8271
8272/*!
8273 \fn QList<QStringView> QStringView::split(QChar sep, Qt::SplitBehavior behavior, Qt::CaseSensitivity cs) const
8274 \fn QList<QStringView> QStringView::split(QStringView sep, Qt::SplitBehavior behavior, Qt::CaseSensitivity cs) const
8275
8276
8277 Splits the view into substring views wherever \a sep occurs, and
8278 returns the list of those string views.
8279
8280 See QString::split() for how \a sep, \a behavior and \a cs interact to form
8281 the result.
8282
8283 \note All the returned views are valid as long as the data referenced by
8284 this string view is valid. Destroying the data will cause all views to
8285 become dangling.
8286
8287 \since 6.0
8288*/
8289QList<QStringView> QStringView::split(QStringView sep, Qt::SplitBehavior behavior, Qt::CaseSensitivity cs) const
8290{
8291 return splitString<QList<QStringView>>(QStringView(*this), sep, behavior, cs);
8292}
8293
8294QList<QStringView> QStringView::split(QChar sep, Qt::SplitBehavior behavior, Qt::CaseSensitivity cs) const
8295{
8296 return split(QStringView(&sep, 1), behavior, cs);
8297}
8298
8299#if QT_CONFIG(regularexpression)
8300namespace {
8301template<class ResultList, typename String, typename MatchingFunction>
8302static ResultList splitString(const String &source, const QRegularExpression &re,
8303 MatchingFunction matchingFunction,
8304 Qt::SplitBehavior behavior)
8305{
8306 ResultList list;
8307 if (!re.isValid()) {
8308 qtWarnAboutInvalidRegularExpression(re, "QString", "split");
8309 return list;
8310 }
8311
8312 qsizetype start = 0;
8313 qsizetype end = 0;
8314 QRegularExpressionMatchIterator iterator = (re.*matchingFunction)(source, 0, QRegularExpression::NormalMatch, QRegularExpression::NoMatchOption);
8315 while (iterator.hasNext()) {
8316 QRegularExpressionMatch match = iterator.next();
8317 end = match.capturedStart();
8318 if (start != end || behavior == Qt::KeepEmptyParts)
8319 list.append(source.sliced(start, end - start));
8320 start = match.capturedEnd();
8321 }
8322
8323 if (start != source.size() || behavior == Qt::KeepEmptyParts)
8324 list.append(source.sliced(start));
8325
8326 return list;
8327}
8328} // namespace
8329
8330/*!
8331 \overload
8332 \since 5.14
8333
8334 Splits the string into substrings wherever the regular expression
8335 \a re matches, and returns the list of those strings. If \a re
8336 does not match anywhere in the string, split() returns a
8337 single-element list containing this string.
8338
8339 Here is an example where we extract the words in a sentence
8340 using one or more whitespace characters as the separator:
8341
8342 \snippet qstring/main.cpp 90
8343
8344 Here is a similar example, but this time we use any sequence of
8345 non-word characters as the separator:
8346
8347 \snippet qstring/main.cpp 91
8348
8349 Here is a third example where we use a zero-length assertion,
8350 \b{\\b} (word boundary), to split the string into an
8351 alternating sequence of non-word and word tokens:
8352
8353 \snippet qstring/main.cpp 92
8354
8355 \sa QStringList::join(), section()
8356*/
8357QStringList QString::split(const QRegularExpression &re, Qt::SplitBehavior behavior) const
8358{
8359#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
8360 const auto matchingFunction = qOverload<const QString &, qsizetype, QRegularExpression::MatchType, QRegularExpression::MatchOptions>(&QRegularExpression::globalMatch);
8361#else
8362 const auto matchingFunction = &QRegularExpression::globalMatch;
8363#endif
8364 return splitString<QStringList>(*this,
8365 re,
8366 matchingFunction,
8367 behavior);
8368}
8369
8370/*!
8371 \overload
8372 \since 6.0
8373
8374 Splits the string into substring views wherever the regular expression \a re
8375 matches, and returns the list of those strings. If \a re does not match
8376 anywhere in the string, split() returns a single-element list containing
8377 this string as view.
8378
8379 \note The views in the returned list are sub-views of this view; as such,
8380 they reference the same data as it and only remain valid for as long as that
8381 data remains live.
8382*/
8383QList<QStringView> QStringView::split(const QRegularExpression &re, Qt::SplitBehavior behavior) const
8384{
8385 return splitString<QList<QStringView>>(*this, re, &QRegularExpression::globalMatchView, behavior);
8386}
8387
8388#endif // QT_CONFIG(regularexpression)
8389
8390/*!
8391 \enum QString::NormalizationForm
8392
8393 This enum describes the various normalized forms of Unicode text.
8394
8395 \value NormalizationForm_D Canonical Decomposition
8396 \value NormalizationForm_C Canonical Decomposition followed by Canonical Composition
8397 \value NormalizationForm_KD Compatibility Decomposition
8398 \value NormalizationForm_KC Compatibility Decomposition followed by Canonical Composition
8399
8400 \sa normalized(),
8401 {https://www.unicode.org/reports/tr15/}{Unicode Standard Annex #15}
8402*/
8403
8404/*!
8405 \since 4.5
8406
8407 Returns a copy of this string repeated the specified number of \a times.
8408
8409 If \a times is less than 1, an empty string is returned.
8410
8411 Example:
8412
8413 \snippet code/src_corelib_text_qstring.cpp 8
8414*/
8415QString QString::repeated(qsizetype times) const
8416{
8417 if (d.size == 0)
8418 return *this;
8419
8420 if (times <= 1) {
8421 if (times == 1)
8422 return *this;
8423 return QString();
8424 }
8425
8426 const qsizetype resultSize = times * d.size;
8427
8428 QString result;
8429 result.reserve(resultSize);
8430 if (result.capacity() != resultSize)
8431 return QString(); // not enough memory
8432
8433 memcpy(result.d.data(), d.data(), d.size * sizeof(QChar));
8434
8435 qsizetype sizeSoFar = d.size;
8436 char16_t *end = result.d.data() + sizeSoFar;
8437
8438 const qsizetype halfResultSize = resultSize >> 1;
8439 while (sizeSoFar <= halfResultSize) {
8440 memcpy(end, result.d.data(), sizeSoFar * sizeof(QChar));
8441 end += sizeSoFar;
8442 sizeSoFar <<= 1;
8443 }
8444 memcpy(end, result.d.data(), (resultSize - sizeSoFar) * sizeof(QChar));
8445 result.d.data()[resultSize] = '\0';
8446 result.d.size = resultSize;
8447 return result;
8448}
8449
8450void qt_string_normalize(QString *data, QString::NormalizationForm mode, QChar::UnicodeVersion version, qsizetype from)
8451{
8452 {
8453 // check if it's fully ASCII first, because then we have no work
8454 auto start = reinterpret_cast<const char16_t *>(data->constData());
8455 const char16_t *p = start + from;
8456 if (isAscii_helper(p, p + data->size() - from))
8457 return;
8458 if (p > start + from)
8459 from = p - start - 1; // need one before the non-ASCII to perform NFC
8460 }
8461
8462 if (version == QChar::Unicode_Unassigned) {
8463 version = QChar::currentUnicodeVersion();
8464 } else if (int(version) <= NormalizationCorrectionsVersionMax) {
8465 const QString &s = *data;
8466 QChar *d = nullptr;
8468 if (n.version > version) {
8469 qsizetype pos = from;
8470 if (QChar::requiresSurrogates(n.ucs4)) {
8471 char16_t ucs4High = QChar::highSurrogate(n.ucs4);
8472 char16_t ucs4Low = QChar::lowSurrogate(n.ucs4);
8473
8474 // scan for this codepoint
8475 for ( ; pos < s.size() - 1; ++pos) {
8476 if (s.at(pos).unicode() == ucs4High && s.at(pos + 1).unicode() == ucs4Low)
8477 break;
8478 }
8479 if (pos == s.size())
8480 continue; // no correction necessary
8481
8482 // detach if necessary
8483 if (!d)
8484 d = data->data();
8485 if (QChar::requiresSurrogates(n.old_mapping)) {
8486 // no shrinking
8487 char16_t oldHigh = QChar::highSurrogate(n.old_mapping);
8488 char16_t oldLow = QChar::lowSurrogate(n.old_mapping);
8489 while (pos < s.size() - 1) {
8490 if (s.at(pos).unicode() == ucs4High && s.at(pos + 1).unicode() == ucs4Low) {
8491 d[pos] = QChar(oldHigh);
8492 d[++pos] = QChar(oldLow);
8493 }
8494 ++pos;
8495 }
8496 } else {
8497 // shrinking, so a little harder
8498 char16_t old = char16_t(n.old_mapping);
8499 qsizetype outpos = pos;
8500 for ( ; pos < s.size(); ++outpos, ++pos) {
8501 if (pos < s.size() - 1 && s.at(pos).unicode() == ucs4High
8502 && s.at(pos + 1).unicode() == ucs4Low) {
8503 d[outpos] = QChar(old);
8504 ++pos;
8505 }
8506 }
8507 data->truncate(outpos);
8508 d = nullptr;
8509 }
8510 } else {
8511 Q_ASSERT(!QChar::requiresSurrogates(n.old_mapping)); // BMP maps to BMP
8512 while (pos < s.size()) {
8513 if (s.at(pos).unicode() == n.ucs4) {
8514 if (!d)
8515 d = data->data();
8516 d[pos] = QChar(n.old_mapping);
8517 }
8518 ++pos;
8519 }
8520 }
8521 }
8522 }
8523 }
8524
8525 if (normalizationQuickCheckHelper(data, mode, from, &from))
8526 return;
8527
8528 decomposeHelper(data, mode < QString::NormalizationForm_KD, version, from);
8529
8530 canonicalOrderHelper(data, version, from);
8531
8532 if (mode == QString::NormalizationForm_D || mode == QString::NormalizationForm_KD)
8533 return;
8534
8535 composeHelper(data, version, from);
8536}
8537
8538/*!
8539 Returns the string in the given Unicode normalization \a mode,
8540 according to the given \a version of the Unicode standard.
8541*/
8542QString QString::normalized(QString::NormalizationForm mode, QChar::UnicodeVersion version) const
8543{
8544 QString copy = *this;
8545 qt_string_normalize(&copy, mode, version, 0);
8546 return copy;
8547}
8548
8549#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0) && !defined(QT_BOOTSTRAPPED)
8550static void checkArgEscape(QStringView s)
8551{
8552 // If we're in here, it means that qArgDigitValue has accepted the
8553 // digit. We can skip the check in case we already know it will
8554 // succeed.
8555 if (!supportUnicodeDigitValuesInArg())
8556 return;
8557
8558 const auto isNonAsciiDigit = [](QChar c) {
8559 return c.unicode() < u'0' || c.unicode() > u'9';
8560 };
8561
8562 if (std::any_of(s.begin(), s.end(), isNonAsciiDigit)) {
8563 const auto accumulateDigit = [](int partial, QChar digit) {
8564 return partial * 10 + digit.digitValue();
8565 };
8566 const int parsedNumber = std::accumulate(s.begin(), s.end(), 0, accumulateDigit);
8567
8568 qWarning("QString::arg(): the replacement \"%%%ls\" contains non-ASCII digits;\n"
8569 " it is currently being interpreted as the %d-th substitution.\n"
8570 " This is deprecated; support for non-ASCII digits will be dropped\n"
8571 " in a future version of Qt.",
8572 qUtf16Printable(s.toString()),
8573 parsedNumber);
8574 }
8575}
8576#endif
8577
8579{
8580 int min_escape; // lowest escape sequence number
8581 qsizetype occurrences; // number of occurrences of the lowest escape sequence number
8582 qsizetype locale_occurrences; // number of occurrences of the lowest escape sequence number that
8583 // contain 'L'
8584 qsizetype escape_len; // total length of escape sequences which will be replaced
8585};
8586
8587static ArgEscapeData findArgEscapes(QStringView s)
8588{
8589 const QChar *uc_begin = s.begin();
8590 const QChar *uc_end = s.end();
8591
8592 ArgEscapeData d;
8593
8594 d.min_escape = INT_MAX;
8595 d.occurrences = 0;
8596 d.escape_len = 0;
8597 d.locale_occurrences = 0;
8598
8599 const QChar *c = uc_begin;
8600 while (c != uc_end) {
8601 while (c != uc_end && c->unicode() != '%')
8602 ++c;
8603
8604 if (c == uc_end)
8605 break;
8606 const QChar *escape_start = c;
8607 if (++c == uc_end)
8608 break;
8609
8610 bool locale_arg = false;
8611 if (c->unicode() == 'L') {
8612 locale_arg = true;
8613 if (++c == uc_end)
8614 break;
8615 }
8616
8617 int escape = qArgDigitValue(*c);
8618 if (escape == -1)
8619 continue;
8620
8621 // ### Qt 7: do not allow anything but ASCII digits
8622 // in arg()'s replacements.
8623#if QT_VERSION <= QT_VERSION_CHECK(7, 0, 0) && !defined(QT_BOOTSTRAPPED)
8624 const QChar *escapeBegin = c;
8625 const QChar *escapeEnd = escapeBegin + 1;
8626#endif
8627
8628 ++c;
8629
8630 if (c != uc_end) {
8631 const int next_escape = qArgDigitValue(*c);
8632 if (next_escape != -1) {
8633 escape = (10 * escape) + next_escape;
8634 ++c;
8635#if QT_VERSION <= QT_VERSION_CHECK(7, 0, 0) && !defined(QT_BOOTSTRAPPED)
8636 ++escapeEnd;
8637#endif
8638 }
8639 }
8640
8641#if QT_VERSION <= QT_VERSION_CHECK(7, 0, 0) && !defined(QT_BOOTSTRAPPED)
8642 checkArgEscape(QStringView(escapeBegin, escapeEnd));
8643#endif
8644
8645 if (escape > d.min_escape)
8646 continue;
8647
8648 if (escape < d.min_escape) {
8649 d.min_escape = escape;
8650 d.occurrences = 0;
8651 d.escape_len = 0;
8652 d.locale_occurrences = 0;
8653 }
8654
8655 ++d.occurrences;
8656 if (locale_arg)
8657 ++d.locale_occurrences;
8658 d.escape_len += c - escape_start;
8659 }
8660 return d;
8661}
8662
8663static QString replaceArgEscapes(QStringView s, const ArgEscapeData &d, qsizetype field_width,
8664 QStringView arg, QStringView larg, QChar fillChar)
8665{
8666 // Negative field-width for right-padding, positive for left-padding:
8667 const qsizetype abs_field_width = qAbs(field_width);
8668 const qsizetype result_len =
8669 s.size() - d.escape_len
8670 + (d.occurrences - d.locale_occurrences) * qMax(abs_field_width, arg.size())
8671 + d.locale_occurrences * qMax(abs_field_width, larg.size());
8672
8673 QString result(result_len, Qt::Uninitialized);
8674 QChar *rc = const_cast<QChar *>(result.unicode());
8675 QChar *const result_end = rc + result_len;
8676 qsizetype repl_cnt = 0;
8677
8678 const QChar *c = s.begin();
8679 const QChar *const uc_end = s.end();
8680 while (c != uc_end) {
8681 Q_ASSERT(d.occurrences > repl_cnt);
8682 /* We don't have to check increments of c against uc_end because, as
8683 long as d.occurrences > repl_cnt, we KNOW there are valid escape
8684 sequences remaining. */
8685
8686 const QChar *text_start = c;
8687 while (c->unicode() != '%')
8688 ++c;
8689
8690 const QChar *escape_start = c++;
8691 const bool localize = c->unicode() == 'L';
8692 if (localize)
8693 ++c;
8694
8695 int escape = qArgDigitValue(*c);
8696 if (escape != -1 && c + 1 != uc_end) {
8697 const int digit = qArgDigitValue(c[1]);
8698 if (digit != -1) {
8699 ++c;
8700 escape = 10 * escape + digit;
8701 }
8702 }
8703
8704 if (escape != d.min_escape) {
8705 memcpy(rc, text_start, (c - text_start) * sizeof(QChar));
8706 rc += c - text_start;
8707 } else {
8708 ++c;
8709
8710 memcpy(rc, text_start, (escape_start - text_start) * sizeof(QChar));
8711 rc += escape_start - text_start;
8712
8713 const QStringView use = localize ? larg : arg;
8714 const qsizetype pad_chars = abs_field_width - use.size();
8715 // (If negative, relevant loops are no-ops: no need to check.)
8716
8717 if (field_width > 0) { // left padded
8718 rc = std::fill_n(rc, pad_chars, fillChar);
8719 }
8720
8721 if (use.size())
8722 memcpy(rc, use.data(), use.size() * sizeof(QChar));
8723 rc += use.size();
8724
8725 if (field_width < 0) { // right padded
8726 rc = std::fill_n(rc, pad_chars, fillChar);
8727 }
8728
8729 if (++repl_cnt == d.occurrences) {
8730 memcpy(rc, c, (uc_end - c) * sizeof(QChar));
8731 rc += uc_end - c;
8732 Q_ASSERT(rc == result_end);
8733 c = uc_end;
8734 }
8735 }
8736 }
8737 Q_ASSERT(rc == result_end);
8738
8739 return result;
8740}
8741
8742/*!
8743 \fn template <typename T, QString::if_string_like<T> = true> QString QString::arg(const T &a, int fieldWidth, QChar fillChar) const
8744
8745 Returns a copy of this string with the lowest-numbered place-marker
8746 replaced by string \a a, i.e., \c %1, \c %2, ..., \c %99.
8747
8748 \a fieldWidth specifies the minimum amount of space that \a a
8749 shall occupy. If \a a requires less space than \a fieldWidth, it
8750 is padded to \a fieldWidth with character \a fillChar. A positive
8751 \a fieldWidth produces right-aligned text. A negative \a fieldWidth
8752 produces left-aligned text.
8753
8754 This example shows how we might create a \c status string for
8755 reporting progress while processing a list of files:
8756
8757 \snippet qstring/main.cpp 11-qstringview
8758
8759 First, \c arg(i) replaces \c %1. Then \c arg(total) replaces \c
8760 %2. Finally, \c arg(fileName) replaces \c %3.
8761
8762 One advantage of using arg() over asprintf() is that the order of the
8763 numbered place markers can change, if the application's strings are
8764 translated into other languages, but each arg() will still replace
8765 the lowest-numbered unreplaced place-marker, no matter where it
8766 appears. Also, if place-marker \c %i appears more than once in the
8767 string, arg() replaces all of them.
8768
8769 If there is no unreplaced place-marker remaining, a warning message
8770 is printed and the result is undefined. Place-marker numbers must be
8771 in the range 1 to 99.
8772
8773 \note In Qt versions prior to 6.9, this function was overloaded on
8774 \c{char}, QChar, QString, QStringView, and QLatin1StringView and in some
8775 cases, \c{wchar_t} and \c{char16_t} arguments would resolve to the integer
8776 overloads. In Qt versions prior to 5.10, this function lacked the
8777 QStringView and QLatin1StringView overloads.
8778*/
8779QString QString::arg_impl(QAnyStringView a, int fieldWidth, QChar fillChar) const
8780{
8781 ArgEscapeData d = findArgEscapes(*this);
8782
8783 if (Q_UNLIKELY(d.occurrences == 0)) {
8784 qWarning("QString::arg: Argument missing: \"%ls\", \"%ls\"", qUtf16Printable(*this),
8785 qUtf16Printable(a.toString()));
8786 return *this;
8787 }
8788 struct {
8789 QVarLengthArray<char16_t> out;
8790 QStringView operator()(QStringView in) noexcept { return in; }
8791 QStringView operator()(QLatin1StringView in)
8792 {
8793 out.resize(in.size());
8794 qt_from_latin1(out.data(), in.data(), size_t(in.size()));
8795 return out;
8796 }
8797 QStringView operator()(QUtf8StringView in)
8798 {
8799 out.resize(in.size());
8800 return QStringView{out.data(), QUtf8::convertToUnicode(out.data(), in)};
8801 }
8802 } convert;
8803
8804 QStringView sv = a.visit(std::ref(convert));
8805 return replaceArgEscapes(*this, d, fieldWidth, sv, sv, fillChar);
8806}
8807
8808/*!
8809 \fn template <typename T, QString::if_integral_non_char<T> = true> QString QString::arg(T a, int fieldWidth, int base, QChar fillChar) const
8810 \overload arg()
8811
8812 The \a a argument is expressed in base \a base, which is 10 by
8813 default and must be between 2 and 36. For bases other than 10, \a a
8814 is treated as an unsigned integer.
8815
8816 \a fieldWidth specifies the minimum amount of space that \a a is
8817 padded to and filled with the character \a fillChar. A positive
8818 value produces right-aligned text; a negative value produces
8819 left-aligned text.
8820
8821 The '%' can be followed by an 'L', in which case the sequence is
8822 replaced with a localized representation of \a a. The conversion
8823 uses the default locale, set by QLocale::setDefault(). If no default
8824 locale was specified, the system locale is used. The 'L' flag is
8825 ignored if \a base is not 10.
8826
8827 \snippet qstring/main.cpp 12
8828 \snippet qstring/main.cpp 14
8829
8830 \note In Qt versions prior to 6.10.1, this function accepted arguments of
8831 types that implicitly convert to integral types. This is no longer supported,
8832 except for (unscoped) enums, because it also accepted types convertible to
8833 floating-point types, losing precision when those were printed as integers. A
8834 backwards-compatible fix is to cast such types to a C++ type whose displayed
8835 form matches your intent (\c int, \c float, ...).
8836
8837 \note In Qt versions prior to 6.9, this function was overloaded on various
8838 integral types and sometimes incorrectly accepted \c char and \c char16_t
8839 arguments.
8840
8841 \sa {Number formats}
8842*/
8843QString QString::arg_impl(qlonglong a, int fieldWidth, int base, QChar fillChar) const
8844{
8845 ArgEscapeData d = findArgEscapes(*this);
8846
8847 if (d.occurrences == 0) {
8848 qWarning("QString::arg: Argument missing: \"%ls\", %llu", qUtf16Printable(*this), a);
8849 return *this;
8850 }
8851
8852 unsigned flags = QLocaleData::NoFlags;
8853 // ZeroPadded sorts out left-padding when the fill is zero, to the right of sign:
8854 if (fillChar == u'0')
8855 flags = QLocaleData::ZeroPadded;
8856
8857 QString arg;
8858 if (d.occurrences > d.locale_occurrences) {
8859 arg = QLocaleData::c()->longLongToString(a, -1, base, fieldWidth, flags);
8860 Q_ASSERT(fillChar != u'0' || fieldWidth <= arg.size());
8861 }
8862
8863 QString localeArg;
8864 if (d.locale_occurrences > 0) {
8865 QLocale locale;
8866 if (!(locale.numberOptions() & QLocale::OmitGroupSeparator))
8867 flags |= QLocaleData::GroupDigits;
8868 localeArg = locale.d->m_data->longLongToString(a, -1, base, fieldWidth, flags);
8869 Q_ASSERT(fillChar != u'0' || fieldWidth <= localeArg.size());
8870 }
8871
8872 return replaceArgEscapes(*this, d, fieldWidth, arg, localeArg, fillChar);
8873}
8874
8875QString QString::arg_impl(qulonglong a, int fieldWidth, int base, QChar fillChar) const
8876{
8877 ArgEscapeData d = findArgEscapes(*this);
8878
8879 if (d.occurrences == 0) {
8880 qWarning("QString::arg: Argument missing: \"%ls\", %lld", qUtf16Printable(*this), a);
8881 return *this;
8882 }
8883
8884 unsigned flags = QLocaleData::NoFlags;
8885 // ZeroPadded sorts out left-padding when the fill is zero, to the right of sign:
8886 if (fillChar == u'0')
8887 flags = QLocaleData::ZeroPadded;
8888
8889 QString arg;
8890 if (d.occurrences > d.locale_occurrences) {
8891 arg = QLocaleData::c()->unsLongLongToString(a, -1, base, fieldWidth, flags);
8892 Q_ASSERT(fillChar != u'0' || fieldWidth <= arg.size());
8893 }
8894
8895 QString localeArg;
8896 if (d.locale_occurrences > 0) {
8897 QLocale locale;
8898 if (!(locale.numberOptions() & QLocale::OmitGroupSeparator))
8899 flags |= QLocaleData::GroupDigits;
8900 localeArg = locale.d->m_data->unsLongLongToString(a, -1, base, fieldWidth, flags);
8901 Q_ASSERT(fillChar != u'0' || fieldWidth <= localeArg.size());
8902 }
8903
8904 return replaceArgEscapes(*this, d, fieldWidth, arg, localeArg, fillChar);
8905}
8906
8907/*!
8908 \fn template <typename T, QString::if_floating_point<T> = true> QString QString::arg(T a, int fieldWidth, char format, int precision, QChar fillChar) const
8909 \overload arg()
8910
8911 Argument \a a is formatted according to the specified \a format and
8912 \a precision. See \l{Floating-point Formats} for details.
8913
8914 \a fieldWidth specifies the minimum amount of space that \a a is
8915 padded to and filled with the character \a fillChar. A positive
8916 value produces right-aligned text; a negative value produces
8917 left-aligned text.
8918
8919 \snippet code/src_corelib_text_qstring.cpp 2
8920
8921 \note In Qt versions prior to 6.9, this function was a regular function
8922 taking \c double. As a consequence of being a template function now, it no
8923 longer accepts arguments that merely implicitly convert to floating-point
8924 types. A backwards-compatible fix is to cast such types to one of the C++
8925 floating-point types.
8926
8927 \sa QLocale::toString(), QLocale::FloatingPointPrecisionOption, {Number formats}
8928*/
8929QString QString::arg_impl(double a, int fieldWidth, char format, int precision, QChar fillChar) const
8930{
8931 ArgEscapeData d = findArgEscapes(*this);
8932
8933 if (d.occurrences == 0) {
8934 qWarning("QString::arg: Argument missing: \"%ls\", %g", qUtf16Printable(*this), a);
8935 return *this;
8936 }
8937
8938 unsigned flags = QLocaleData::NoFlags;
8939 // ZeroPadded sorts out left-padding when the fill is zero, to the right of sign:
8940 if (fillChar == u'0')
8941 flags |= QLocaleData::ZeroPadded;
8942
8943 if (isAsciiUpper(format))
8944 flags |= QLocaleData::CapitalEorX;
8945
8946 QLocaleData::DoubleForm form = QLocaleData::DFDecimal;
8947 switch (QtMiscUtils::toAsciiLower(format)) {
8948 case 'f':
8949 form = QLocaleData::DFDecimal;
8950 break;
8951 case 'e':
8952 form = QLocaleData::DFExponent;
8953 break;
8954 case 'g':
8955 form = QLocaleData::DFSignificantDigits;
8956 break;
8957 default:
8958#if defined(QT_CHECK_RANGE)
8959 qWarning("QString::arg: Invalid format char '%c'", format);
8960#endif
8961 break;
8962 }
8963
8964 QString arg;
8965 if (d.occurrences > d.locale_occurrences) {
8966 arg = QLocaleData::c()->doubleToString(a, precision, form, fieldWidth,
8967 flags | QLocaleData::ZeroPadExponent);
8968 Q_ASSERT(fillChar != u'0' || !qt_is_finite(a)
8969 || fieldWidth <= arg.size());
8970 }
8971
8972 QString localeArg;
8973 if (d.locale_occurrences > 0) {
8974 QLocale locale;
8975
8976 const QLocale::NumberOptions numberOptions = locale.numberOptions();
8977 if (!(numberOptions & QLocale::OmitGroupSeparator))
8978 flags |= QLocaleData::GroupDigits;
8979 if (!(numberOptions & QLocale::OmitLeadingZeroInExponent))
8980 flags |= QLocaleData::ZeroPadExponent;
8981 if (numberOptions & QLocale::IncludeTrailingZeroesAfterDot)
8982 flags |= QLocaleData::AddTrailingZeroes;
8983 localeArg = locale.d->m_data->doubleToString(a, precision, form, fieldWidth, flags);
8984 Q_ASSERT(fillChar != u'0' || !qt_is_finite(a)
8985 || fieldWidth <= localeArg.size());
8986 }
8987
8988 return replaceArgEscapes(*this, d, fieldWidth, arg, localeArg, fillChar);
8989}
8990
8991static inline char16_t to_unicode(const QChar c) { return c.unicode(); }
8992static inline char16_t to_unicode(const char c) { return QLatin1Char{c}.unicode(); }
8993
8994template <typename Char>
8995static int getEscape(const Char *uc, qsizetype *pos, qsizetype len)
8996{
8997 qsizetype i = *pos;
8998 ++i;
8999 if (i < len && uc[i] == u'L')
9000 ++i;
9001 if (i < len) {
9002 int escape = to_unicode(uc[i]) - '0';
9003 if (uint(escape) >= 10U)
9004 return -1;
9005 ++i;
9006 if (i < len) {
9007 // there's a second digit
9008 int digit = to_unicode(uc[i]) - '0';
9009 if (uint(digit) < 10U) {
9010 escape = (escape * 10) + digit;
9011 ++i;
9012 }
9013 }
9014 *pos = i;
9015 return escape;
9016 }
9017 return -1;
9018}
9019
9020/*
9021 Algorithm for multiArg:
9022
9023 1. Parse the string as a sequence of verbatim text and placeholders (%L?\d{,3}).
9024 The L is parsed and accepted for compatibility with non-multi-arg, but since
9025 multiArg only accepts strings as replacements, the localization request can
9026 be safely ignored.
9027 2. The result of step (1) is a list of (string-ref,int)-tuples. The string-ref
9028 either points at text to be copied verbatim (in which case the int is -1),
9029 or, initially, at the textual representation of the placeholder. In that case,
9030 the int contains the numerical number as parsed from the placeholder.
9031 3. Next, collect all the non-negative ints found, sort them in ascending order and
9032 remove duplicates.
9033 3a. If the result has more entries than multiArg() was given replacement strings,
9034 we have found placeholders we can't satisfy with replacement strings. That is
9035 fine (there could be another .arg() call coming after this one), so just
9036 truncate the result to the number of actual multiArg() replacement strings.
9037 3b. If the result has less entries than multiArg() was given replacement strings,
9038 the string is missing placeholders. This is an error that the user should be
9039 warned about.
9040 4. The result of step (3) is a mapping from the index of any replacement string to
9041 placeholder number. This is the wrong way around, but since placeholder
9042 numbers could get as large as 999, while we typically don't have more than 9
9043 replacement strings, we trade 4K of sparsely-used memory for doing a reverse lookup
9044 each time we need to map a placeholder number to a replacement string index
9045 (that's a linear search; but still *much* faster than using an associative container).
9046 5. Next, for each of the tuples found in step (1), do the following:
9047 5a. If the int is negative, do nothing.
9048 5b. Otherwise, if the int is found in the result of step (3) at index I, replace
9049 the string-ref with a string-ref for the (complete) I'th replacement string.
9050 5c. Otherwise, do nothing.
9051 6. Concatenate all string refs into a single result string.
9052*/
9053
9054namespace {
9055struct Part
9056{
9057 Part() = default; // for QVarLengthArray; do not use
9058 constexpr Part(QAnyStringView s, int num = -1)
9059 : string{s}, number{num} {}
9060
9061 void reset(QAnyStringView s) noexcept { *this = {s, number}; }
9062
9063 QAnyStringView string;
9064 int number;
9065};
9066} // unnamed namespace
9067
9069
9070namespace {
9071
9072enum { ExpectedParts = 32 };
9073
9074typedef QVarLengthArray<Part, ExpectedParts> ParseResult;
9075typedef QVarLengthArray<int, ExpectedParts/2> ArgIndexToPlaceholderMap;
9076
9077template <typename StringView>
9078static ParseResult parseMultiArgFormatString_impl(StringView s)
9079{
9080 ParseResult result;
9081
9082 const auto uc = s.data();
9083 const auto len = s.size();
9084 const auto end = len - 1;
9085 qsizetype i = 0;
9086 qsizetype last = 0;
9087
9088 while (i < end) {
9089 if (uc[i] == u'%') {
9090 qsizetype percent = i;
9091 int number = getEscape(uc, &i, len);
9092 if (number != -1) {
9093 if (last != percent)
9094 result.push_back(Part{s.sliced(last, percent - last)}); // literal text (incl. failed placeholders)
9095 result.push_back(Part{s.sliced(percent, i - percent), number}); // parsed placeholder
9096 last = i;
9097 continue;
9098 }
9099 }
9100 ++i;
9101 }
9102
9103 if (last < len)
9104 result.push_back(Part{s.sliced(last, len - last)}); // trailing literal text
9105
9106 return result;
9107}
9108
9109static ParseResult parseMultiArgFormatString(QAnyStringView s)
9110{
9111 return s.visit([] (auto s) { return parseMultiArgFormatString_impl(s); });
9112}
9113
9114static ArgIndexToPlaceholderMap makeArgIndexToPlaceholderMap(const ParseResult &parts)
9115{
9116 ArgIndexToPlaceholderMap result;
9117
9118 for (const Part &part : parts) {
9119 if (part.number >= 0)
9120 result.push_back(part.number);
9121 }
9122
9123 std::sort(result.begin(), result.end());
9124 result.erase(std::unique(result.begin(), result.end()),
9125 result.end());
9126
9127 return result;
9128}
9129
9130static qsizetype resolveStringRefsAndReturnTotalSize(ParseResult &parts, const ArgIndexToPlaceholderMap &argIndexToPlaceholderMap, const QtPrivate::ArgBase *args[])
9131{
9132 using namespace QtPrivate;
9133 qsizetype totalSize = 0;
9134 for (Part &part : parts) {
9135 if (part.number != -1) {
9136 const auto it = std::find(argIndexToPlaceholderMap.begin(), argIndexToPlaceholderMap.end(), part.number);
9137 if (it != argIndexToPlaceholderMap.end()) {
9138 const auto &arg = *args[it - argIndexToPlaceholderMap.begin()];
9139 switch (arg.tag) {
9140 case ArgBase::L1:
9141 part.reset(static_cast<const QLatin1StringArg&>(arg).string);
9142 break;
9143 case ArgBase::Any:
9144 part.reset(static_cast<const QAnyStringArg&>(arg).string);
9145 break;
9146 case ArgBase::U16:
9147 part.reset(static_cast<const QStringViewArg&>(arg).string);
9148 break;
9149 }
9150 }
9151 }
9152 totalSize += part.string.size();
9153 }
9154 return totalSize;
9155}
9156
9157} // unnamed namespace
9158
9159QString QtPrivate::argToQString(QAnyStringView pattern, size_t numArgs, const ArgBase **args)
9160{
9161 // Step 1-2 above
9162 ParseResult parts = parseMultiArgFormatString(pattern);
9163
9164 // 3-4
9165 ArgIndexToPlaceholderMap argIndexToPlaceholderMap = makeArgIndexToPlaceholderMap(parts);
9166
9167 if (static_cast<size_t>(argIndexToPlaceholderMap.size()) > numArgs) // 3a
9168 argIndexToPlaceholderMap.resize(qsizetype(numArgs));
9169 else if (Q_UNLIKELY(static_cast<size_t>(argIndexToPlaceholderMap.size()) < numArgs)) // 3b
9170 qWarning("QString::arg: %d argument(s) missing in %ls",
9171 int(numArgs - argIndexToPlaceholderMap.size()), qUtf16Printable(pattern.toString()));
9172
9173 // 5
9174 const qsizetype totalSize = resolveStringRefsAndReturnTotalSize(parts, argIndexToPlaceholderMap, args);
9175
9176 // 6:
9177 QString result(totalSize, Qt::Uninitialized);
9178 auto out = const_cast<QChar*>(result.constData());
9179
9180 struct Concatenate {
9181 QChar *out;
9182 QChar *operator()(QLatin1String part) noexcept
9183 {
9184 if (part.size()) {
9185 qt_from_latin1(reinterpret_cast<char16_t*>(out),
9186 part.data(), part.size());
9187 }
9188 return out + part.size();
9189 }
9190 QChar *operator()(QUtf8StringView part) noexcept
9191 {
9192 return QUtf8::convertToUnicode(out, part);
9193 }
9194 QChar *operator()(QStringView part) noexcept
9195 {
9196 if (part.size())
9197 memcpy(out, part.data(), part.size() * sizeof(QChar));
9198 return out + part.size();
9199 }
9200 };
9201
9202 for (const Part &part : parts)
9203 out = part.string.visit(Concatenate{out});
9204
9205 // UTF-8 decoding may have caused an overestimate of totalSize - correct it:
9206 result.truncate(out - result.cbegin());
9207
9208 return result;
9209}
9210
9211/*! \fn bool QString::isRightToLeft() const
9212
9213 Returns \c true if the string is read right to left.
9214
9215 \sa QStringView::isRightToLeft()
9216*/
9217bool QString::isRightToLeft() const
9218{
9219 return QtPrivate::isRightToLeft(QStringView(*this));
9220}
9221
9222/*!
9223 \fn bool QString::isValidUtf16() const noexcept
9224 \since 5.15
9225
9226 Returns \c true if the string contains valid UTF-16 encoded data,
9227 or \c false otherwise.
9228
9229 Note that this function does not perform any special validation of the
9230 data; it merely checks if it can be successfully decoded from UTF-16.
9231 The data is assumed to be in host byte order; the presence of a BOM
9232 is meaningless.
9233
9234 \sa QStringView::isValidUtf16()
9235*/
9236
9237/*! \fn QChar *QString::data()
9238
9239 Returns a pointer to the data stored in the QString. The pointer
9240 can be used to access and modify the characters that compose the
9241 string.
9242
9243 Unlike constData() and unicode(), the returned data is always
9244 '\\0'-terminated.
9245
9246 Example:
9247
9248 \snippet qstring/main.cpp 19
9249
9250 Note that the pointer remains valid only as long as the string is
9251 not modified by other means. For read-only access, constData() is
9252 faster because it never causes a \l{deep copy} to occur.
9253
9254 \sa constData(), operator[]()
9255*/
9256
9257/*! \fn const QChar *QString::data() const
9258
9259 \overload
9260
9261 \note The returned string may not be '\\0'-terminated.
9262 Use size() to determine the length of the array.
9263
9264 \sa fromRawData()
9265*/
9266
9267/*! \fn const QChar *QString::constData() const
9268
9269 Returns a pointer to the data stored in the QString. The pointer
9270 can be used to access the characters that compose the string.
9271
9272 Note that the pointer remains valid only as long as the string is
9273 not modified.
9274
9275 \note The returned string may not be '\\0'-terminated.
9276 Use size() to determine the length of the array.
9277
9278 \sa data(), operator[](), fromRawData()
9279*/
9280
9281/*! \fn void QString::push_front(const QString &other)
9282
9283 This function is provided for STL compatibility, prepending the
9284 given \a other string to the beginning of this string. It is
9285 equivalent to \c prepend(other).
9286
9287 \sa prepend()
9288*/
9289
9290/*! \fn void QString::push_front(QChar ch)
9291
9292 \overload
9293
9294 Prepends the given \a ch character to the beginning of this string.
9295*/
9296
9297/*! \fn void QString::push_back(const QString &other)
9298
9299 This function is provided for STL compatibility, appending the
9300 given \a other string onto the end of this string. It is
9301 equivalent to \c append(other).
9302
9303 \sa append()
9304*/
9305
9306/*! \fn void QString::push_back(QChar ch)
9307
9308 \overload
9309
9310 Appends the given \a ch character onto the end of this string.
9311*/
9312
9313/*!
9314 \since 6.1
9315
9316 Removes from the string the characters in the half-open range
9317 [ \a first , \a last ). Returns an iterator to the character
9318 immediately after the last erased character (i.e. the character
9319 referred to by \a last before the erase).
9320*/
9321QString::iterator QString::erase(QString::const_iterator first, QString::const_iterator last)
9322{
9323 const auto start = std::distance(cbegin(), first);
9324 const auto len = std::distance(first, last);
9325 remove(start, len);
9326 return begin() + start;
9327}
9328
9329/*!
9330 \fn QString::iterator QString::erase(QString::const_iterator it)
9331
9332 \overload
9333 \since 6.5
9334
9335 Removes the character denoted by \c it from the string.
9336 Returns an iterator to the character immediately after the
9337 erased character.
9338
9339 \code
9340 QString c = "abcdefg";
9341 auto it = c.erase(c.cbegin()); // c is now "bcdefg"; "it" points to "b"
9342 \endcode
9343*/
9344
9345/*! \fn void QString::shrink_to_fit()
9346 \since 5.10
9347
9348 This function is provided for STL compatibility. It is
9349 equivalent to squeeze().
9350
9351 \sa squeeze()
9352*/
9353
9354/*!
9355 \fn std::string QString::toStdString() const
9356
9357 Returns a std::string object with the data contained in this
9358 QString. The Unicode data is converted into 8-bit characters using
9359 the toUtf8() function.
9360
9361 This method is mostly useful to pass a QString to a function
9362 that accepts a std::string object.
9363
9364 \sa toLatin1(), toUtf8(), toLocal8Bit(), QByteArray::toStdString()
9365*/
9366std::string QString::toStdString() const
9367{
9368 std::string result;
9369 if (isEmpty())
9370 return result;
9371
9372 auto writeToBuffer = [this](char *out, size_t) {
9373 char *last = QUtf8::convertFromUnicode(out, *this);
9374 return last - out;
9375 };
9376 size_t maxSize = size() * 3; // worst case for UTF-8
9377#ifdef __cpp_lib_string_resize_and_overwrite
9378 // C++23
9379 result.resize_and_overwrite(maxSize, writeToBuffer);
9380#else
9381 result.resize(maxSize);
9382 result.resize(writeToBuffer(result.data(), result.size()));
9383#endif
9384 return result;
9385}
9386
9387/*!
9388 \fn QString QString::fromRawData(const char16_t *unicode, qsizetype size)
9389 \since 6.10
9390
9391 Constructs a QString that uses the first \a size Unicode characters
9392 in the array \a unicode. The data in \a unicode is \e not
9393 copied. The caller must be able to guarantee that \a unicode will
9394 not be deleted or modified as long as the QString (or an
9395 unmodified copy of it) exists.
9396
9397 Any attempts to modify the QString or copies of it will cause it
9398 to create a deep copy of the data, ensuring that the raw data
9399 isn't modified.
9400
9401 Here is an example of how we can use a QRegularExpression on raw data in
9402 memory without requiring to copy the data into a QString:
9403
9404 \snippet qstring/main.cpp 22
9405 \snippet qstring/main.cpp 23
9406
9407 \warning A string created with fromRawData() is \e not
9408 '\\0'-terminated, unless the raw data contains a '\\0' character
9409 at position \a size. This means unicode() will \e not return a
9410 '\\0'-terminated string (although utf16() does, at the cost of
9411 copying the raw data).
9412
9413 \sa fromUtf16(), setRawData(), data(), constData(),
9414 nullTerminate(), nullTerminated()
9415*/
9416
9417/*!
9418 \fn QString QString::fromRawData(const QChar *unicode, qsizetype size)
9419 \overload
9420*/
9421
9422/*!
9423 \since 4.7
9424
9425 Resets the QString to use the first \a size Unicode characters
9426 in the array \a unicode. The data in \a unicode is \e not
9427 copied. The caller must be able to guarantee that \a unicode will
9428 not be deleted or modified as long as the QString (or an
9429 unmodified copy of it) exists.
9430
9431 This function can be used instead of fromRawData() to re-use
9432 existings QString objects to save memory re-allocations.
9433
9434 \sa fromRawData(), nullTerminate(), nullTerminated()
9435*/
9436QString &QString::setRawData(const QChar *unicode, qsizetype size)
9437{
9438 if (!unicode || !size) {
9439 clear();
9440 }
9441 *this = fromRawData(unicode, size);
9442 return *this;
9443}
9444
9445/*! \fn QString QString::fromStdU16String(const std::u16string &str)
9446 \since 5.5
9447
9448 \include qstring.cpp {from-std-string} {UTF-16} {fromUtf16()}
9449
9450 \sa fromUtf16(), fromStdWString(), fromStdU32String()
9451*/
9452
9453/*!
9454 \fn std::u16string QString::toStdU16String() const
9455 \since 5.5
9456
9457 Returns a std::u16string object with the data contained in this
9458 QString. The Unicode data is the same as returned by the utf16()
9459 method.
9460
9461 \sa utf16(), toStdWString(), toStdU32String()
9462*/
9463
9464/*! \fn QString QString::fromStdU32String(const std::u32string &str)
9465 \since 5.5
9466
9467 \include qstring.cpp {from-std-string} {UTF-32} {fromUcs4()}
9468
9469 \sa fromUcs4(), fromStdWString(), fromStdU16String()
9470*/
9471
9472/*!
9473 \fn std::u32string QString::toStdU32String() const
9474 \since 5.5
9475
9476 Returns a std::u32string object with the data contained in this
9477 QString. The Unicode data is the same as returned by the toUcs4()
9478 method.
9479
9480 \sa toUcs4(), toStdWString(), toStdU16String()
9481*/
9482
9483#if !defined(QT_NO_DATASTREAM)
9484/*!
9485 \fn QDataStream &operator<<(QDataStream &stream, const QString &string)
9486 \relates QString
9487
9488 Writes the given \a string to the specified \a stream.
9489
9490 \sa {Serializing Qt Data Types}
9491*/
9492
9493QDataStream &operator<<(QDataStream &out, const QString &str)
9494{
9495 if (out.version() == 1) {
9496 out << str.toLatin1();
9497 } else {
9498 if (!str.isNull() || out.version() < 3) {
9499 if ((out.byteOrder() == QDataStream::BigEndian) == (QSysInfo::ByteOrder == QSysInfo::BigEndian)) {
9500 out.writeBytes(reinterpret_cast<const char *>(str.unicode()),
9501 static_cast<qsizetype>(sizeof(QChar) * str.size()));
9502 } else {
9503 QVarLengthArray<char16_t> buffer(str.size());
9504 qbswap<sizeof(char16_t)>(str.constData(), str.size(), buffer.data());
9505 out.writeBytes(reinterpret_cast<const char *>(buffer.data()),
9506 static_cast<qsizetype>(sizeof(char16_t) * buffer.size()));
9507 }
9508 } else {
9509 QDataStream::writeQSizeType(out, -1); // write null marker
9510 }
9511 }
9512 return out;
9513}
9514
9515/*!
9516 \fn QDataStream &operator>>(QDataStream &stream, QString &string)
9517 \relates QString
9518
9519 Reads a string from the specified \a stream into the given \a string.
9520
9521 \sa {Serializing Qt Data Types}
9522*/
9523
9524QDataStream &operator>>(QDataStream &in, QString &str)
9525{
9526 if (in.version() == 1) {
9527 QByteArray l;
9528 in >> l;
9529 str = QString::fromLatin1(l);
9530 } else {
9531 qint64 size = QDataStream::readQSizeType(in);
9532 qsizetype bytes = size;
9533 if (size != bytes || size < -1) {
9534 str.clear();
9535 in.setStatus(QDataStream::SizeLimitExceeded);
9536 return in;
9537 }
9538 if (bytes == -1) { // null string
9539 str = QString();
9540 } else if (bytes > 0) {
9541 if (bytes & 0x1) {
9542 str.clear();
9543 in.setStatus(QDataStream::ReadCorruptData);
9544 return in;
9545 }
9546
9547 const qsizetype Step = 1024 * 1024;
9548 qsizetype len = bytes / 2;
9549 qsizetype allocated = 0;
9550
9551 while (allocated < len) {
9552 int blockSize = qMin(Step, len - allocated);
9553 str.resize(allocated + blockSize);
9554 if (in.readRawData(reinterpret_cast<char *>(str.data()) + allocated * 2,
9555 blockSize * 2) != blockSize * 2) {
9556 str.clear();
9557 in.setStatus(QDataStream::ReadPastEnd);
9558 return in;
9559 }
9560 allocated += blockSize;
9561 }
9562
9563 if ((in.byteOrder() == QDataStream::BigEndian)
9564 != (QSysInfo::ByteOrder == QSysInfo::BigEndian)) {
9565 char16_t *data = reinterpret_cast<char16_t *>(str.data());
9566 qbswap<sizeof(*data)>(data, len, data);
9567 }
9568 } else {
9569 str = QString(QLatin1StringView(""));
9570 }
9571 }
9572 return in;
9573}
9574#endif // QT_NO_DATASTREAM
9575
9576/*!
9577 \typedef QString::Data
9578 \internal
9579*/
9580
9581/*!
9582 \typedef QString::DataPtr
9583 \internal
9584*/
9585
9586/*!
9587 \fn DataPtr & QString::data_ptr()
9588 \internal
9589*/
9590
9591/*!
9592 \since 5.11
9593 \internal
9594 \relates QStringView
9595
9596 Returns \c true if the string is read right to left.
9597
9598 \sa QString::isRightToLeft()
9599*/
9600bool QtPrivate::isRightToLeft(QStringView string) noexcept
9601{
9602 int isolateLevel = 0;
9603
9604 for (QStringIterator i(string); i.hasNext();) {
9605 const char32_t c = i.next();
9606
9607 switch (QChar::direction(c)) {
9608 case QChar::DirRLI:
9609 case QChar::DirLRI:
9610 case QChar::DirFSI:
9611 ++isolateLevel;
9612 break;
9613 case QChar::DirPDI:
9614 if (isolateLevel)
9615 --isolateLevel;
9616 break;
9617 case QChar::DirL:
9618 if (isolateLevel)
9619 break;
9620 return false;
9621 case QChar::DirR:
9622 case QChar::DirAL:
9623 if (isolateLevel)
9624 break;
9625 return true;
9626 case QChar::DirEN:
9627 case QChar::DirES:
9628 case QChar::DirET:
9629 case QChar::DirAN:
9630 case QChar::DirCS:
9631 case QChar::DirB:
9632 case QChar::DirS:
9633 case QChar::DirWS:
9634 case QChar::DirON:
9635 case QChar::DirLRE:
9636 case QChar::DirLRO:
9637 case QChar::DirRLE:
9638 case QChar::DirRLO:
9639 case QChar::DirPDF:
9640 case QChar::DirNSM:
9641 case QChar::DirBN:
9642 break;
9643 }
9644 }
9645 return false;
9646}
9647
9648qsizetype QtPrivate::count(QStringView haystack, QStringView needle, Qt::CaseSensitivity cs) noexcept
9649{
9650 qsizetype num = 0;
9651 qsizetype i = -1;
9652 if (haystack.size() > 500 && needle.size() > 5) {
9653 QStringMatcher matcher(needle, cs);
9654 while ((i = matcher.indexIn(haystack, i + 1)) != -1)
9655 ++num;
9656 } else {
9657 while ((i = QtPrivate::findString(haystack, i + 1, needle, cs)) != -1)
9658 ++num;
9659 }
9660 return num;
9661}
9662
9663qsizetype QtPrivate::count(QStringView haystack, QChar needle, Qt::CaseSensitivity cs) noexcept
9664{
9665 if (cs == Qt::CaseSensitive)
9666 return std::count(haystack.cbegin(), haystack.cend(), needle);
9667
9668 needle = foldCase(needle);
9669 return std::count_if(haystack.cbegin(), haystack.cend(),
9670 [needle](const QChar c) { return foldAndCompare(c, needle); });
9671}
9672
9673qsizetype QtPrivate::count(QLatin1StringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs)
9674{
9675 qsizetype num = 0;
9676 qsizetype i = -1;
9677
9678 QLatin1StringMatcher matcher(needle, cs);
9679 while ((i = matcher.indexIn(haystack, i + 1)) != -1)
9680 ++num;
9681
9682 return num;
9683}
9684
9685qsizetype QtPrivate::count(QLatin1StringView haystack, QStringView needle, Qt::CaseSensitivity cs)
9686{
9687 if (haystack.size() < needle.size())
9688 return 0;
9689
9690 if (!QtPrivate::isLatin1(needle)) // won't find non-L1 UTF-16 needles in a L1 haystack!
9691 return 0;
9692
9693 qsizetype num = 0;
9694 qsizetype i = -1;
9695
9696 QVarLengthArray<uchar> s(needle.size());
9697 qt_to_latin1_unchecked(s.data(), needle.utf16(), needle.size());
9698
9699 QLatin1StringMatcher matcher(QLatin1StringView(reinterpret_cast<char *>(s.data()), s.size()),
9700 cs);
9701 while ((i = matcher.indexIn(haystack, i + 1)) != -1)
9702 ++num;
9703
9704 return num;
9705}
9706
9707qsizetype QtPrivate::count(QStringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs)
9708{
9709 if (haystack.size() < needle.size())
9710 return -1;
9711
9712 QVarLengthArray<char16_t> s = qt_from_latin1_to_qvla(needle);
9713 return QtPrivate::count(haystack, QStringView(s.data(), s.size()), cs);
9714}
9715
9716qsizetype QtPrivate::count(QLatin1StringView haystack, QChar needle, Qt::CaseSensitivity cs) noexcept
9717{
9718 // non-L1 needles cannot possibly match in L1-only haystacks
9719 if (needle.unicode() > 0xff)
9720 return 0;
9721
9722 if (cs == Qt::CaseSensitive) {
9723 return std::count(haystack.cbegin(), haystack.cend(), needle.toLatin1());
9724 } else {
9725 return std::count_if(haystack.cbegin(), haystack.cend(),
9726 CaseInsensitiveL1::matcher(needle.toLatin1()));
9727 }
9728}
9729
9730/*!
9731 \fn bool QtPrivate::startsWith(QStringView haystack, QStringView needle, Qt::CaseSensitivity cs)
9732 \since 5.10
9733 \fn bool QtPrivate::startsWith(QStringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs)
9734 \since 5.10
9735 \fn bool QtPrivate::startsWith(QLatin1StringView haystack, QStringView needle, Qt::CaseSensitivity cs)
9736 \since 5.10
9737 \fn bool QtPrivate::startsWith(QLatin1StringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs)
9738 \since 5.10
9739 \internal
9740 \relates QStringView
9741
9742 Returns \c true if \a haystack starts with \a needle,
9743 otherwise returns \c false.
9744
9745 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
9746
9747 \sa QtPrivate::endsWith(), QString::endsWith(), QStringView::endsWith(), QLatin1StringView::endsWith()
9748*/
9749
9750bool QtPrivate::startsWith(QStringView haystack, QStringView needle, Qt::CaseSensitivity cs) noexcept
9751{
9752 return qt_starts_with_impl(haystack, needle, cs);
9753}
9754
9755bool QtPrivate::startsWith(QStringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs) noexcept
9756{
9757 return qt_starts_with_impl(haystack, needle, cs);
9758}
9759
9760bool QtPrivate::startsWith(QLatin1StringView haystack, QStringView needle, Qt::CaseSensitivity cs) noexcept
9761{
9762 return qt_starts_with_impl(haystack, needle, cs);
9763}
9764
9765bool QtPrivate::startsWith(QLatin1StringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs) noexcept
9766{
9767 return qt_starts_with_impl(haystack, needle, cs);
9768}
9769
9770/*!
9771 \fn bool QtPrivate::endsWith(QStringView haystack, QStringView needle, Qt::CaseSensitivity cs)
9772 \since 5.10
9773 \fn bool QtPrivate::endsWith(QStringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs)
9774 \since 5.10
9775 \fn bool QtPrivate::endsWith(QLatin1StringView haystack, QStringView needle, Qt::CaseSensitivity cs)
9776 \since 5.10
9777 \fn bool QtPrivate::endsWith(QLatin1StringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs)
9778 \since 5.10
9779 \internal
9780 \relates QStringView
9781
9782 Returns \c true if \a haystack ends with \a needle,
9783 otherwise returns \c false.
9784
9785 \include qstring.qdocinc {search-comparison-case-sensitivity} {search}
9786
9787 \sa QtPrivate::startsWith(), QString::endsWith(), QStringView::endsWith(), QLatin1StringView::endsWith()
9788*/
9789
9790bool QtPrivate::endsWith(QStringView haystack, QStringView needle, Qt::CaseSensitivity cs) noexcept
9791{
9792 return qt_ends_with_impl(haystack, needle, cs);
9793}
9794
9795bool QtPrivate::endsWith(QStringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs) noexcept
9796{
9797 return qt_ends_with_impl(haystack, needle, cs);
9798}
9799
9800bool QtPrivate::endsWith(QLatin1StringView haystack, QStringView needle, Qt::CaseSensitivity cs) noexcept
9801{
9802 return qt_ends_with_impl(haystack, needle, cs);
9803}
9804
9805bool QtPrivate::endsWith(QLatin1StringView haystack, QLatin1StringView needle, Qt::CaseSensitivity cs) noexcept
9806{
9807 return qt_ends_with_impl(haystack, needle, cs);
9808}
9809
9810qsizetype QtPrivate::findString(QStringView haystack0, qsizetype from, QStringView needle0, Qt::CaseSensitivity cs) noexcept
9811{
9812 const qsizetype l = haystack0.size();
9813 const qsizetype sl = needle0.size();
9814 if (sl == 1)
9815 return findString(haystack0, from, needle0[0], cs);
9816 if (from < 0)
9817 from += l;
9818 if (std::size_t(sl + from) > std::size_t(l))
9819 return -1;
9820 if (!sl)
9821 return from;
9822 if (!l)
9823 return -1;
9824
9825 /*
9826 We use the Boyer-Moore algorithm in cases where the overhead
9827 for the skip table should pay off, otherwise we use a simple
9828 hash function.
9829 */
9830 if (l > 500 && sl > 5)
9831 return qFindStringBoyerMoore(haystack0, from, needle0, cs);
9832
9833 auto sv = [sl](const char16_t *v) { return QStringView(v, sl); };
9834 /*
9835 We use some hashing for efficiency's sake. Instead of
9836 comparing strings, we compare the hash value of str with that
9837 of a part of this QString. Only if that matches, we call
9838 qt_string_compare().
9839 */
9840 const char16_t *needle = needle0.utf16();
9841 const char16_t *haystack = haystack0.utf16() + from;
9842 const char16_t *end = haystack0.utf16() + (l - sl);
9843 const qregisteruint sl_minus_1 = sl - 1;
9844 qregisteruint hashNeedle = 0, hashHaystack = 0;
9845 qsizetype idx;
9846
9847 if (cs == Qt::CaseSensitive) {
9848 for (idx = 0; idx < sl; ++idx) {
9849 hashNeedle = ((hashNeedle<<1) + needle[idx]);
9850 hashHaystack = ((hashHaystack<<1) + haystack[idx]);
9851 }
9852 hashHaystack -= haystack[sl_minus_1];
9853
9854 while (haystack <= end) {
9855 hashHaystack += haystack[sl_minus_1];
9856 if (hashHaystack == hashNeedle
9857 && QtPrivate::compareStrings(needle0, sv(haystack), Qt::CaseSensitive) == 0)
9858 return haystack - haystack0.utf16();
9859
9860 REHASH(*haystack);
9861 ++haystack;
9862 }
9863 } else {
9864 const char16_t *haystack_start = haystack0.utf16();
9865 for (idx = 0; idx < sl; ++idx) {
9866 hashNeedle = (hashNeedle<<1) + foldCase(needle + idx, needle);
9867 hashHaystack = (hashHaystack<<1) + foldCase(haystack + idx, haystack_start);
9868 }
9869 hashHaystack -= foldCase(haystack + sl_minus_1, haystack_start);
9870
9871 while (haystack <= end) {
9872 hashHaystack += foldCase(haystack + sl_minus_1, haystack_start);
9873 if (hashHaystack == hashNeedle
9874 && QtPrivate::compareStrings(needle0, sv(haystack), Qt::CaseInsensitive) == 0)
9875 return haystack - haystack0.utf16();
9876
9877 REHASH(foldCase(haystack, haystack_start));
9878 ++haystack;
9879 }
9880 }
9881 return -1;
9882}
9883
9884qsizetype QtPrivate::findString(QStringView haystack, qsizetype from, QLatin1StringView needle, Qt::CaseSensitivity cs) noexcept
9885{
9886 if (haystack.size() < needle.size())
9887 return -1;
9888
9889 QVarLengthArray<char16_t> s = qt_from_latin1_to_qvla(needle);
9890 return QtPrivate::findString(haystack, from, QStringView(reinterpret_cast<const QChar*>(s.constData()), s.size()), cs);
9891}
9892
9893qsizetype QtPrivate::findString(QLatin1StringView haystack, qsizetype from, QStringView needle, Qt::CaseSensitivity cs) noexcept
9894{
9895 if (haystack.size() < needle.size())
9896 return -1;
9897
9898 if (!QtPrivate::isLatin1(needle)) // won't find non-L1 UTF-16 needles in a L1 haystack!
9899 return -1;
9900
9901 if (needle.size() == 1) {
9902 const char n = needle.front().toLatin1();
9903 return QtPrivate::findString(haystack, from, QLatin1StringView(&n, 1), cs);
9904 }
9905
9906 QVarLengthArray<char> s(needle.size());
9907 qt_to_latin1_unchecked(reinterpret_cast<uchar *>(s.data()), needle.utf16(), needle.size());
9908 return QtPrivate::findString(haystack, from, QLatin1StringView(s.data(), s.size()), cs);
9909}
9910
9911qsizetype QtPrivate::findString(QLatin1StringView haystack, qsizetype from, QLatin1StringView needle, Qt::CaseSensitivity cs) noexcept
9912{
9913 if (from < 0)
9914 from += haystack.size();
9915 if (from < 0)
9916 return -1;
9917 qsizetype adjustedSize = haystack.size() - from;
9918 if (adjustedSize < needle.size())
9919 return -1;
9920 if (needle.size() == 0)
9921 return from;
9922
9923 if (cs == Qt::CaseSensitive) {
9924
9925 if (needle.size() == 1) {
9926 Q_ASSERT(haystack.data() != nullptr); // see size check above
9927 if (auto it = memchr(haystack.data() + from, needle.front().toLatin1(), adjustedSize))
9928 return static_cast<const char *>(it) - haystack.data();
9929 return -1;
9930 }
9931
9932 const QLatin1StringMatcher matcher(needle, Qt::CaseSensitivity::CaseSensitive);
9933 return matcher.indexIn(haystack, from);
9934 }
9935
9936 // If the needle is sufficiently small we simply iteratively search through
9937 // the haystack. When the needle is too long we use a boyer-moore searcher
9938 // from the standard library, if available. If it is not available then the
9939 // QLatin1Strings are converted to QString and compared as such. Though
9940 // initialization is slower the boyer-moore search it employs still makes up
9941 // for it when haystack and needle are sufficiently long.
9942 // The needle size was chosen by testing various lengths using the
9943 // qstringtokenizer benchmark with the
9944 // "tokenize_qlatin1string_qlatin1string" test.
9945#ifdef Q_CC_MSVC
9946 const qsizetype threshold = 1;
9947#else
9948 const qsizetype threshold = 13;
9949#endif
9950 if (needle.size() <= threshold) {
9951 const auto begin = haystack.begin();
9952 const auto end = haystack.end() - needle.size() + 1;
9953 auto ciMatch = CaseInsensitiveL1::matcher(needle[0].toLatin1());
9954 const qsizetype nlen1 = needle.size() - 1;
9955 for (auto it = std::find_if(begin + from, end, ciMatch); it != end;
9956 it = std::find_if(it + 1, end, ciMatch)) {
9957 // In this comparison we skip the first character because we know it's a match
9958 if (!nlen1 || QLatin1StringView(it + 1, nlen1).compare(needle.sliced(1), cs) == 0)
9959 return std::distance(begin, it);
9960 }
9961 return -1;
9962 }
9963
9964 QLatin1StringMatcher matcher(needle, Qt::CaseSensitivity::CaseInsensitive);
9965 return matcher.indexIn(haystack, from);
9966}
9967
9968qsizetype QtPrivate::lastIndexOf(QStringView haystack, qsizetype from, char16_t needle, Qt::CaseSensitivity cs) noexcept
9969{
9970 return qLastIndexOf(haystack, QChar(needle), from, cs);
9971}
9972
9973qsizetype QtPrivate::lastIndexOf(QStringView haystack, qsizetype from, QStringView needle, Qt::CaseSensitivity cs) noexcept
9974{
9975 return qLastIndexOf(haystack, from, needle, cs);
9976}
9977
9978qsizetype QtPrivate::lastIndexOf(QStringView haystack, qsizetype from, QLatin1StringView needle, Qt::CaseSensitivity cs) noexcept
9979{
9980 return qLastIndexOf(haystack, from, needle, cs);
9981}
9982
9983qsizetype QtPrivate::lastIndexOf(QLatin1StringView haystack, qsizetype from, QStringView needle, Qt::CaseSensitivity cs) noexcept
9984{
9985 return qLastIndexOf(haystack, from, needle, cs);
9986}
9987
9988qsizetype QtPrivate::lastIndexOf(QLatin1StringView haystack, qsizetype from, QLatin1StringView needle, Qt::CaseSensitivity cs) noexcept
9989{
9990 return qLastIndexOf(haystack, from, needle, cs);
9991}
9992
9993#if QT_CONFIG(regularexpression)
9994qsizetype QtPrivate::indexOf(QStringView viewHaystack, const QString *stringHaystack, const QRegularExpression &re, qsizetype from, QRegularExpressionMatch *rmatch)
9995{
9996 if (!re.isValid()) {
9997 qtWarnAboutInvalidRegularExpression(re, "QString(View)", "indexOf");
9998 return -1;
9999 }
10000
10001 QRegularExpressionMatch match = stringHaystack
10002 ? re.match(*stringHaystack, from)
10003 : re.matchView(viewHaystack, from);
10004 if (match.hasMatch()) {
10005 const qsizetype ret = match.capturedStart();
10006 if (rmatch)
10007 *rmatch = std::move(match);
10008 return ret;
10009 }
10010
10011 return -1;
10012}
10013
10014qsizetype QtPrivate::indexOf(QStringView haystack, const QRegularExpression &re, qsizetype from, QRegularExpressionMatch *rmatch)
10015{
10016 return indexOf(haystack, nullptr, re, from, rmatch);
10017}
10018
10019qsizetype QtPrivate::lastIndexOf(QStringView viewHaystack, const QString *stringHaystack, const QRegularExpression &re, qsizetype from, QRegularExpressionMatch *rmatch)
10020{
10021 if (!re.isValid()) {
10022 qtWarnAboutInvalidRegularExpression(re, "QString(View)", "lastIndexOf");
10023 return -1;
10024 }
10025
10026 qsizetype endpos = (from < 0) ? (viewHaystack.size() + from + 1) : (from + 1);
10027 QRegularExpressionMatchIterator iterator = stringHaystack
10028 ? re.globalMatch(*stringHaystack)
10029 : re.globalMatchView(viewHaystack);
10030 qsizetype lastIndex = -1;
10031 while (iterator.hasNext()) {
10032 QRegularExpressionMatch match = iterator.next();
10033 qsizetype start = match.capturedStart();
10034 if (start < endpos) {
10035 lastIndex = start;
10036 if (rmatch)
10037 *rmatch = std::move(match);
10038 } else {
10039 break;
10040 }
10041 }
10042
10043 return lastIndex;
10044}
10045
10046qsizetype QtPrivate::lastIndexOf(QStringView haystack, const QRegularExpression &re, qsizetype from, QRegularExpressionMatch *rmatch)
10047{
10048 return lastIndexOf(haystack, nullptr, re, from, rmatch);
10049}
10050
10051bool QtPrivate::contains(QStringView viewHaystack, const QString *stringHaystack, const QRegularExpression &re, QRegularExpressionMatch *rmatch)
10052{
10053 if (!re.isValid()) {
10054 qtWarnAboutInvalidRegularExpression(re, "QString(View)", "contains");
10055 return false;
10056 }
10057 QRegularExpressionMatch m = stringHaystack
10058 ? re.match(*stringHaystack)
10059 : re.matchView(viewHaystack);
10060 bool hasMatch = m.hasMatch();
10061 if (hasMatch && rmatch)
10062 *rmatch = std::move(m);
10063 return hasMatch;
10064}
10065
10066bool QtPrivate::contains(QStringView haystack, const QRegularExpression &re, QRegularExpressionMatch *rmatch)
10067{
10068 return contains(haystack, nullptr, re, rmatch);
10069}
10070
10071qsizetype QtPrivate::count(QStringView haystack, const QRegularExpression &re)
10072{
10073 if (!re.isValid()) {
10074 qtWarnAboutInvalidRegularExpression(re, "QString(View)", "count");
10075 return 0;
10076 }
10077 qsizetype count = 0;
10078 qsizetype index = -1;
10079 qsizetype len = haystack.size();
10080 while (index <= len - 1) {
10081 QRegularExpressionMatch match = re.matchView(haystack, index + 1);
10082 if (!match.hasMatch())
10083 break;
10084 count++;
10085
10086 // Search again, from the next character after the beginning of this
10087 // capture. If the capture starts with a surrogate pair, both together
10088 // count as "one character".
10089 index = match.capturedStart();
10090 if (index < len && haystack[index].isHighSurrogate())
10091 ++index;
10092 }
10093 return count;
10094}
10095
10096#endif // QT_CONFIG(regularexpression)
10097
10098/*!
10099 \since 5.0
10100
10101 Converts a plain text string to an HTML string with
10102 HTML metacharacters \c{<}, \c{>}, \c{&}, and \c{"} replaced by HTML
10103 entities.
10104
10105 Example:
10106
10107 \snippet code/src_corelib_text_qstring.cpp 7
10108*/
10109QString QString::toHtmlEscaped() const
10110{
10111 const auto pos = std::u16string_view(*this).find_first_of(u"<>&\"");
10112 if (pos == std::u16string_view::npos)
10113 return *this;
10114 QString rich;
10115 const qsizetype len = size();
10116 rich.reserve(qsizetype(len * 1.1));
10117 rich += qToStringViewIgnoringNull(*this).first(pos);
10118 for (auto ch : qToStringViewIgnoringNull(*this).sliced(pos)) {
10119 if (ch == u'<')
10120 rich += "&lt;"_L1;
10121 else if (ch == u'>')
10122 rich += "&gt;"_L1;
10123 else if (ch == u'&')
10124 rich += "&amp;"_L1;
10125 else if (ch == u'"')
10126 rich += "&quot;"_L1;
10127 else
10128 rich += ch;
10129 }
10130 rich.squeeze();
10131 return rich;
10132}
10133
10134/*!
10135 \macro QStringLiteral(str)
10136 \relates QString
10137
10138 The macro generates the data for a QString out of the string literal \a str
10139 at compile time. Creating a QString from it is free in this case, and the
10140 generated string data is stored in the read-only segment of the compiled
10141 object file.
10142
10143 If you have code that looks like this:
10144
10145 \snippet code/src_corelib_text_qstring.cpp 9
10146
10147 then a temporary QString will be created to be passed as the \c{hasAttribute}
10148 function parameter. This can be quite expensive, as it involves a memory
10149 allocation and the copy/conversion of the data into QString's internal
10150 encoding.
10151
10152 This cost can be avoided by using QStringLiteral instead:
10153
10154 \snippet code/src_corelib_text_qstring.cpp 10
10155
10156 In this case, QString's internal data will be generated at compile time; no
10157 conversion or allocation will occur at runtime.
10158
10159 Using QStringLiteral instead of a double quoted plain C++ string literal can
10160 significantly speed up creation of QString instances from data known at
10161 compile time.
10162
10163 \note QLatin1StringView can still be more efficient than QStringLiteral
10164 when the string is passed to a function that has an overload taking
10165 QLatin1StringView and this overload avoids conversion to QString. For
10166 instance, QString::operator==() can compare to a QLatin1StringView
10167 directly:
10168
10169 \snippet code/src_corelib_text_qstring.cpp 11
10170
10171 \note Some compilers have bugs encoding strings containing characters outside
10172 the US-ASCII character set. Make sure you prefix your string with \c{u} in
10173 those cases. It is optional otherwise.
10174
10175 \note QStringLiteral is interchangeable with \l operator""_s. The latter saves
10176 typing when many string literals are present in the code.
10177
10178 \sa QByteArrayLiteral
10179*/
10180
10181#if QT_DEPRECATED_SINCE(6, 8)
10182/*!
10183 \fn QtLiterals::operator""_qs(const char16_t *str, size_t size)
10184
10185 \relates QString
10186 \since 6.2
10187 \deprecated [6.8] Use \c _s from Qt::StringLiterals namespace instead.
10188
10189 Literal operator that creates a QString out of the first \a size characters in
10190 the char16_t string literal \a str.
10191
10192 The QString is created at compile time, and the generated string data is stored
10193 in the read-only segment of the compiled object file. Duplicate literals may
10194 share the same read-only memory. This functionality is interchangeable with
10195 QStringLiteral, but saves typing when many string literals are present in the
10196 code.
10197
10198 The following code creates a QString:
10199 \code
10200 auto str = u"hello"_qs;
10201 \endcode
10202
10203 \sa QStringLiteral, QtLiterals::operator""_qba(const char *str, size_t size)
10204*/
10205#endif // QT_DEPRECATED_SINCE(6, 8)
10206
10207/*!
10208 \fn Qt::Literals::StringLiterals::operator""_s(const char16_t *str, size_t size)
10209
10210 \relates QString
10211 \since 6.4
10212
10213 Literal operator that creates a QString out of the first \a size characters in
10214 the char16_t string literal \a str.
10215
10216 The QString is created at compile time, and the generated string data is stored
10217 in the read-only segment of the compiled object file. Duplicate literals may
10218 share the same read-only memory. This functionality is interchangeable with
10219 QStringLiteral, but saves typing when many string literals are present in the
10220 code.
10221
10222 The following code creates a QString:
10223 \code
10224 using namespace Qt::StringLiterals;
10225
10226 auto str = u"hello"_s;
10227 \endcode
10228
10229 \sa Qt::Literals::StringLiterals
10230*/
10231
10232/*!
10233 \internal
10234 */
10235void QAbstractConcatenable::appendLatin1To(QLatin1StringView in, QChar *out) noexcept
10236{
10237 qt_from_latin1(reinterpret_cast<char16_t *>(out), in.data(), size_t(in.size()));
10238}
10239
10240/*!
10241 \fn template <typename T> qsizetype erase(QString &s, const T &t)
10242 \relates QString
10243 \since 6.1
10244
10245 Removes all elements that compare equal to \a t from the
10246 string \a s. Returns the number of elements removed, if any.
10247
10248 \sa erase_if
10249*/
10250
10251/*!
10252 \fn template <typename Predicate> qsizetype erase_if(QString &s, Predicate pred)
10253 \relates QString
10254 \since 6.1
10255
10256 Removes all elements for which the predicate \a pred returns true
10257 from the string \a s. Returns the number of elements removed, if
10258 any.
10259
10260 \sa erase
10261*/
10262
10263/*!
10264 \macro const char *qPrintable(const QString &str)
10265 \relates QString
10266
10267 Returns \a str as a \c{const char *}. This is equivalent to
10268 \a{str}.toLocal8Bit().\l{QByteArray::}{constData()}.
10269
10270 The char pointer will be invalid after the statement in which
10271 qPrintable() is used. This is because the array returned by
10272 QString::toLocal8Bit() will fall out of scope.
10273
10274 \note qDebug(), qInfo(), qWarning(), qCritical(), qFatal() expect
10275 %s arguments to be UTF-8 encoded, while qPrintable() converts to
10276 local 8-bit encoding. Therefore qUtf8Printable() should be used
10277 for logging strings instead of qPrintable().
10278
10279 \sa qUtf8Printable()
10280*/
10281
10282/*!
10283 \macro const char *qUtf8Printable(const QString &str)
10284 \relates QString
10285 \since 5.4
10286
10287 Returns \a str as a \c{const char *}. This is equivalent to
10288 \a{str}.toUtf8().\l{QByteArray::}{constData()}.
10289
10290 The char pointer will be invalid after the statement in which
10291 qUtf8Printable() is used. This is because the array returned by
10292 QString::toUtf8() will fall out of scope.
10293
10294 Example:
10295
10296 \snippet code/src_corelib_text_qstring.cpp qUtf8Printable
10297
10298 \sa qPrintable(), qDebug(), qInfo(), qWarning(), qCritical(), qFatal()
10299*/
10300
10301/*!
10302 \macro const wchar_t *qUtf16Printable(const QString &str)
10303 \relates QString
10304 \since 5.7
10305
10306 Returns \a str as a \c{const ushort *}, but cast to a \c{const wchar_t *}
10307 to avoid warnings. This is equivalent to \a{str}.utf16() plus some casting.
10308
10309 The only useful thing you can do with the return value of this macro is to
10310 pass it to QString::asprintf() for use in a \c{%ls} conversion. In particular,
10311 the return value is \e{not} a valid \c{const wchar_t*}!
10312
10313 In general, the pointer will be invalid after the statement in which
10314 qUtf16Printable() is used. This is because the pointer may have been
10315 obtained from a temporary expression, which will fall out of scope.
10316
10317 Example:
10318
10319 \snippet code/src_corelib_text_qstring.cpp qUtf16Printable
10320
10321 \sa qPrintable(), qDebug(), qInfo(), qWarning(), qCritical(), qFatal()
10322*/
10323
10324QT_END_NAMESPACE
10325
10326#undef REHASH
QString convertToQString(QAnyStringView string)
Definition qstring.cpp:5559
Definition qlist.h:82
char32_t next(char32_t invalidAs=QChar::ReplacementCharacter)
bool hasNext() const
\inmodule QtCore
QList< uint > convertToUcs4(QStringView string)
Definition qstring.cpp:5815
QByteArray convertToUtf8(QStringView string)
Definition qstring.cpp:5760
QByteArray convertToLocal8Bit(QStringView string)
Definition qstring.cpp:5717
QByteArray convertToLatin1(QStringView string)
Definition qstring.cpp:5576
Combined button and popup list for selecting options.
static QString convertCase(T &str, QUnicodeTables::Case which)
Definition qstring.cpp:7189
static constexpr NormalizationCorrection uc_normalization_corrections[]
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION bool startsWith(QStringView haystack, QStringView needle, Qt::CaseSensitivity cs=Qt::CaseSensitive) noexcept
Definition qstring.cpp:9750
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION bool endsWith(QStringView haystack, QStringView needle, Qt::CaseSensitivity cs=Qt::CaseSensitive) noexcept
Definition qstring.cpp:9790
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION bool isLower(QStringView s) noexcept
Definition qstring.cpp:5496
const QString & asString(const QString &s)
Definition qstring.h:1708
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION bool isValidUtf16(QStringView s) noexcept
Definition qstring.cpp:905
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION bool equalStrings(QStringView lhs, QStringView rhs) noexcept
Definition qstring.cpp:1373
qsizetype findString(QStringView str, qsizetype from, QChar needle, Qt::CaseSensitivity cs=Qt::CaseSensitive) noexcept
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION bool isRightToLeft(QStringView string) noexcept
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION int compareStrings(QStringView lhs, QStringView rhs, Qt::CaseSensitivity cs=Qt::CaseSensitive) noexcept
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION bool isAscii(QLatin1StringView s) noexcept
Definition qstring.cpp:850
constexpr bool isLatin1(QLatin1StringView s) noexcept
Definition qstring.h:77
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION const char16_t * qustrcasechr(QStringView str, char16_t ch) noexcept
Definition qstring.cpp:775
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION bool isUpper(QStringView s) noexcept
Definition qstring.cpp:5501
Q_CORE_EXPORT Q_DECL_PURE_FUNCTION const char16_t * qustrchr(QStringView str, char16_t ch) noexcept
Definition qstring.cpp:687
void qt_to_latin1_unchecked(uchar *dst, const char16_t *uc, qsizetype len)
Definition qstring.cpp:1188
static char16_t foldCase(char16_t ch) noexcept
Definition qchar.cpp:1696
#define __has_feature(x)
uint QT_FASTCALL fetch1Pixel< QPixelLayout::BPP1LSB >(const uchar *src, int index)
bool comparesEqual(const QFileInfo &lhs, const QFileInfo &rhs)
static bool isAscii_helper(const char16_t *&ptr, const char16_t *end)
Definition qstring.cpp:858
static Int toIntegral(QStringView string, bool *ok, int base)
Definition qstring.cpp:7678
void qt_to_latin1(uchar *dst, const char16_t *src, qsizetype length)
Definition qstring.cpp:1183
Qt::strong_ordering compareThreeWay(const QByteArray &lhs, const QChar &rhs) noexcept
Definition qstring.cpp:6733
static void append_utf8(QString &qs, const char *cs, qsizetype len)
Definition qstring.cpp:7312
#define ATTRIBUTE_NO_SANITIZE
Definition qstring.cpp:366
bool qt_is_ascii(const char *&ptr, const char *end) noexcept
Definition qstring.cpp:786
static bool checkCase(QStringView s, QUnicodeTables::Case c) noexcept
Definition qstring.cpp:5485
static void replace_helper(QString &str, QSpan< qsizetype > indices, qsizetype blen, QStringView after)
Definition qstring.cpp:3686
Q_CORE_EXPORT void qt_from_latin1(char16_t *dst, const char *str, size_t size) noexcept
Definition qstring.cpp:920
static int ucstrcmp(const char16_t *a, size_t alen, const Char2 *b, size_t blen)
Definition qstring.cpp:1346
bool comparesEqual(const QByteArray &lhs, char16_t rhs) noexcept
Definition qstring.cpp:6739
Q_DECLARE_TYPEINFO(Part, Q_PRIMITIVE_TYPE)
static void removeStringImpl(QString &s, const T &needle, Qt::CaseSensitivity cs)
Definition qstring.cpp:3495
static bool needsReallocate(const QString &str, qsizetype newSize)
Definition qstring.cpp:2637
static int qArgDigitValue(QChar ch) noexcept
Definition qstring.cpp:1613
bool comparesEqual(const QByteArray &lhs, const QChar &rhs) noexcept
Definition qstring.cpp:6728
#define REHASH(a)
Definition qstring.cpp:65
bool comparesEqual(const QByteArrayView &lhs, char16_t rhs) noexcept
Definition qstring.cpp:6717
static int ucstrncmp(const char16_t *a, const char16_t *b, size_t l)
Definition qstring.cpp:1264
static Q_NEVER_INLINE int ucstricmp(qsizetype alen, const char16_t *a, qsizetype blen, const char *b)
Definition qstring.cpp:1219
static QByteArray qt_convert_to_latin1(QStringView string)
Definition qstring.cpp:5582
static bool ucstreq(const char16_t *a, size_t alen, const Char2 *b)
Definition qstring.cpp:1339
static QList< uint > qt_convert_to_ucs4(QStringView string)
Definition qstring.cpp:5787
qsizetype qFindStringBoyerMoore(QStringView haystack, qsizetype from, QStringView needle, Qt::CaseSensitivity cs)
static QByteArray qt_convert_to_local_8bit(QStringView string)
Definition qstring.cpp:5694
static LengthMod parse_length_modifier(const char *&c) noexcept
Definition qstring.cpp:7368
static ArgEscapeData findArgEscapes(QStringView s)
Definition qstring.cpp:8587
static QByteArray qt_convert_to_utf8(QStringView str)
Definition qstring.cpp:5740
static void qt_to_latin1_internal(uchar *dst, const char16_t *src, qsizetype length)
Definition qstring.cpp:1004
QtPrivate::QCaseInsensitiveLatin1Hash CaseInsensitiveL1
Definition qstring.cpp:1353
LengthMod
Definition qstring.cpp:7357
@ lm_z
Definition qstring.cpp:7357
@ lm_none
Definition qstring.cpp:7357
@ lm_t
Definition qstring.cpp:7357
@ lm_l
Definition qstring.cpp:7357
@ lm_ll
Definition qstring.cpp:7357
@ lm_hh
Definition qstring.cpp:7357
@ lm_L
Definition qstring.cpp:7357
@ lm_h
Definition qstring.cpp:7357
@ lm_j
Definition qstring.cpp:7357
static void insert_helper(QString &str, qsizetype i, const T &toInsert)
Definition qstring.cpp:2970
static int latin1nicmp(const char *lhsChar, qsizetype lSize, const char *rhsChar, qsizetype rSize)
Definition qstring.cpp:1355
Qt::strong_ordering compareThreeWay(const QByteArrayView &lhs, const QChar &rhs) noexcept
Definition qstring.cpp:6711
static char16_t to_unicode(const char c)
Definition qstring.cpp:8992
Qt::strong_ordering compareThreeWay(const QByteArray &lhs, char16_t rhs) noexcept
Definition qstring.cpp:6744
static QString replaceArgEscapes(QStringView s, const ArgEscapeData &d, qsizetype field_width, QStringView arg, QStringView larg, QChar fillChar)
Definition qstring.cpp:8663
static QVarLengthArray< char16_t > qt_from_latin1_to_qvla(QLatin1StringView str)
Definition qstring.cpp:995
static Q_NEVER_INLINE int ucstricmp8(const char *utf8, const char *utf8end, const QChar *utf16, const QChar *utf16end)
Definition qstring.cpp:1237
void qt_string_normalize(QString *data, QString::NormalizationForm mode, QChar::UnicodeVersion version, qsizetype from)
Definition qstring.cpp:8450
static uint parse_flag_characters(const char *&c) noexcept
Definition qstring.cpp:7320
static Q_NEVER_INLINE int ucstricmp(qsizetype alen, const char16_t *a, qsizetype blen, const char16_t *b)
Definition qstring.cpp:1194
static char16_t to_unicode(const QChar c)
Definition qstring.cpp:8991
QDataStream & operator>>(QDataStream &in, QString &str)
Definition qstring.cpp:9524
static int getEscape(const Char *uc, qsizetype *pos, qsizetype len)
Definition qstring.cpp:8995
static int ucstrncmp(const char16_t *a, const char *b, size_t l)
Definition qstring.cpp:1317
static bool can_consume(const char *&c, char ch) noexcept
Definition qstring.cpp:7359
static int parse_field_width(const char *&c, qsizetype size)
Definition qstring.cpp:7340
Qt::strong_ordering compareThreeWay(const QByteArrayView &lhs, char16_t rhs) noexcept
Definition qstring.cpp:6722
#define qUtf16Printable(string)
Definition qstring.h:1725
qsizetype occurrences
Definition qstring.cpp:8581
qsizetype escape_len
Definition qstring.cpp:8584
qsizetype locale_occurrences
Definition qstring.cpp:8582
\inmodule QtCore \reentrant
Definition qchar.h:18
constexpr char16_t unicode() const noexcept
Converts a Latin-1 character to an 16-bit-encoded Unicode representation of the character.
Definition qchar.h:22
constexpr QLatin1Char(char c) noexcept
Constructs a Latin-1 character for c.
Definition qchar.h:20
@ BlankBeforePositive
Definition qlocale_p.h:270
@ AddTrailingZeroes
Definition qlocale_p.h:267
static int difference(char lhs, char rhs)