Merge remote-tracking branch 'origin/master' into api_changes
[profile/ivi/qtbase.git] / src / corelib / tools / qstring.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtCore module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qstringlist.h"
43 #include "qregexp.h"
44 #include "qregularexpression.h"
45 #include "qunicodetables_p.h"
46 #ifndef QT_NO_TEXTCODEC
47 #include <qtextcodec.h>
48 #endif
49 #include <private/qutfcodec_p.h>
50 #include "qsimd_p.h"
51 #include <qdatastream.h>
52 #include <qlist.h>
53 #include "qlocale.h"
54 #include "qlocale_p.h"
55 #include "qstringmatcher.h"
56 #include "qvarlengtharray.h"
57 #include "qtools_p.h"
58 #include "qhash.h"
59 #include "qdebug.h"
60 #include "qendian.h"
61
62 #ifdef Q_OS_MAC
63 #include <private/qcore_mac_p.h>
64 #endif
65
66 #include <private/qfunctions_p.h>
67
68 #include <limits.h>
69 #include <string.h>
70 #include <stdlib.h>
71 #include <stdio.h>
72 #include <stdarg.h>
73
74 #include "qchar.cpp"
75 #include "qstringmatcher.cpp"
76
77 #ifdef Q_OS_WIN
78 #  include <qt_windows.h>
79 #  ifdef Q_OS_WINCE
80 #    include <winnls.h>
81 #  endif
82 #endif
83
84 #ifdef truncate
85 #  undef truncate
86 #endif
87
88 #ifndef LLONG_MAX
89 #define LLONG_MAX qint64_C(9223372036854775807)
90 #endif
91 #ifndef LLONG_MIN
92 #define LLONG_MIN (-LLONG_MAX - qint64_C(1))
93 #endif
94 #ifndef ULLONG_MAX
95 #define ULLONG_MAX quint64_C(18446744073709551615)
96 #endif
97
98 #define IS_RAW_DATA(d) ((d)->offset != sizeof(QStringData))
99
100 QT_BEGIN_NAMESPACE
101
102 #ifdef QT_USE_ICU
103 // qlocale_icu.cpp
104 extern bool qt_ucol_strcoll(const QChar *source, int sourceLength, const QChar *target, int targetLength, int *result);
105 #endif
106
107
108 // internal
109 int qFindString(const QChar *haystack, int haystackLen, int from,
110     const QChar *needle, int needleLen, Qt::CaseSensitivity cs);
111 int qFindStringBoyerMoore(const QChar *haystack, int haystackLen, int from,
112     const QChar *needle, int needleLen, Qt::CaseSensitivity cs);
113 static inline int qt_last_index_of(const QChar *haystack, int haystackLen, QChar needle,
114                                    int from, Qt::CaseSensitivity cs);
115 static inline int qt_string_count(const QChar *haystack, int haystackLen,
116                                   const QChar *needle, int needleLen,
117                                   Qt::CaseSensitivity cs);
118 static inline int qt_string_count(const QChar *haystack, int haystackLen,
119                                   QChar needle, Qt::CaseSensitivity cs);
120 static inline int qt_find_latin1_string(const QChar *hay, int size, const QLatin1String &needle,
121                                         int from, Qt::CaseSensitivity cs);
122 static inline bool qt_starts_with(const QChar *haystack, int haystackLen,
123                                   const QChar *needle, int needleLen, Qt::CaseSensitivity cs);
124 static inline bool qt_starts_with(const QChar *haystack, int haystackLen,
125                                   QLatin1String needle, Qt::CaseSensitivity cs);
126 static inline bool qt_ends_with(const QChar *haystack, int haystackLen,
127                                 const QChar *needle, int needleLen, Qt::CaseSensitivity cs);
128 static inline bool qt_ends_with(const QChar *haystack, int haystackLen,
129                                 QLatin1String needle, Qt::CaseSensitivity cs);
130
131 // Unicode case-insensitive comparison
132 static int ucstricmp(const ushort *a, const ushort *ae, const ushort *b, const ushort *be)
133 {
134     if (a == b)
135         return (ae - be);
136     if (a == 0)
137         return 1;
138     if (b == 0)
139         return -1;
140
141     const ushort *e = ae;
142     if (be - b < ae - a)
143         e = a + (be - b);
144
145     uint alast = 0;
146     uint blast = 0;
147     while (a < e) {
148 //         qDebug() << hex << alast << blast;
149 //         qDebug() << hex << "*a=" << *a << "alast=" << alast << "folded=" << foldCase (*a, alast);
150 //         qDebug() << hex << "*b=" << *b << "blast=" << blast << "folded=" << foldCase (*b, blast);
151         int diff = foldCase(*a, alast) - foldCase(*b, blast);
152         if ((diff))
153             return diff;
154         ++a;
155         ++b;
156     }
157     if (a == ae) {
158         if (b == be)
159             return 0;
160         return -1;
161     }
162     return 1;
163 }
164
165 // Case-insensitive comparison between a Unicode string and a QLatin1String
166 static int ucstricmp(const ushort *a, const ushort *ae, const uchar *b, const uchar *be)
167 {
168     if (a == 0) {
169         if (b == 0)
170             return 0;
171         return 1;
172     }
173     if (b == 0)
174         return -1;
175
176     const ushort *e = ae;
177     if (be - b < ae - a)
178         e = a + (be - b);
179
180     while (a < e) {
181         int diff = foldCase(*a) - foldCase(*b);
182         if ((diff))
183             return diff;
184         ++a;
185         ++b;
186     }
187     if (a == ae) {
188         if (b == be)
189             return 0;
190         return -1;
191     }
192     return 1;
193 }
194
195 // Unicode case-sensitive compare two same-sized strings
196 static int ucstrncmp(const QChar *a, const QChar *b, int l)
197 {
198     while (l-- && *a == *b)
199         a++,b++;
200     if (l==-1)
201         return 0;
202     return a->unicode() - b->unicode();
203 }
204
205 // Unicode case-sensitive comparison
206 static int ucstrcmp(const QChar *a, int alen, const QChar *b, int blen)
207 {
208     if (a == b && alen == blen)
209         return 0;
210     int l = qMin(alen, blen);
211     int cmp = ucstrncmp(a, b, l);
212     return cmp ? cmp : (alen-blen);
213 }
214
215 // Unicode case-insensitive compare two same-sized strings
216 static int ucstrnicmp(const ushort *a, const ushort *b, int l)
217 {
218     return ucstricmp(a, a + l, b, b + l);
219 }
220
221 // Benchmarking indicates that doing memcmp is much slower than
222 // executing the comparison ourselves.
223 //
224 // The profiling was done on a population of calls to qMemEquals, generated
225 // during a run of the demo browser. The profile of the data (32-bit x86
226 // Linux) was:
227 //
228 //  total number of comparisons: 21353
229 //  longest string compared: 95
230 //  average comparison length: 14.8786
231 //  cache-line crosses: 5661 (13.3%)
232 //  alignment histogram:
233 //   0xXXX0 = 512 (1.2%) strings, 0 (0.0%) of which same-aligned
234 //   0xXXX2 = 15087 (35.3%) strings, 5145 (34.1%) of which same-aligned
235 //   0xXXX4 = 525 (1.2%) strings, 0 (0.0%) of which same-aligned
236 //   0xXXX6 = 557 (1.3%) strings, 6 (1.1%) of which same-aligned
237 //   0xXXX8 = 509 (1.2%) strings, 0 (0.0%) of which same-aligned
238 //   0xXXXa = 24358 (57.0%) strings, 9901 (40.6%) of which same-aligned
239 //   0xXXXc = 557 (1.3%) strings, 0 (0.0%) of which same-aligned
240 //   0xXXXe = 601 (1.4%) strings, 15 (2.5%) of which same-aligned
241 //   total  = 42706 (100%) strings, 15067 (35.3%) of which same-aligned
242 //
243 // 92% of the strings have alignment of 2 or 10, which is due to malloc on
244 // 32-bit Linux returning values aligned to 8 bytes, and offsetof(array, QString::Data) == 18.
245 //
246 // The profile on 64-bit will be different since offsetof(array, QString::Data) == 26.
247 //
248 // The benchmark results were, for a Core-i7 @ 2.67 GHz 32-bit, compiled with -O3 -funroll-loops:
249 //   16-bit loads only:           872,301 CPU ticks [Qt 4.5 / memcmp]
250 //   32- and 16-bit loads:        773,362 CPU ticks [Qt 4.6]
251 //   SSE2 "movdqu" 128-bit loads: 618,736 CPU ticks
252 //   SSE3 "lddqu" 128-bit loads:  619,954 CPU ticks
253 //   SSSE3 "palignr" corrections: 852,147 CPU ticks
254 //   SSE4.2 "pcmpestrm":          738,702 CPU ticks
255 //
256 // The same benchmark on an Atom N450 @ 1.66 GHz, is:
257 //  16-bit loads only:            2,185,882 CPU ticks
258 //  32- and 16-bit loads:         1,805,060 CPU ticks
259 //  SSE2 "movdqu" 128-bit loads:  2,529,843 CPU ticks
260 //  SSE3 "lddqu" 128-bit loads:   2,514,858 CPU ticks
261 //  SSSE3 "palignr" corrections:  2,160,325 CPU ticks
262 //  SSE4.2 not available
263 //
264 // The conclusion we reach is that alignment the SSE2 unaligned code can gain
265 // 20% improvement in performance in some systems, but suffers a penalty due
266 // to the unaligned loads on others.
267
268 static bool qMemEquals(const quint16 *a, const quint16 *b, int length)
269 {
270     if (a == b || !length)
271         return true;
272
273     register union {
274         const quint16 *w;
275         const quint32 *d;
276         quintptr value;
277     } sa, sb;
278     sa.w = a;
279     sb.w = b;
280
281     // check alignment
282     if ((sa.value & 2) == (sb.value & 2)) {
283         // both addresses have the same alignment
284         if (sa.value & 2) {
285             // both addresses are not aligned to 4-bytes boundaries
286             // compare the first character
287             if (*sa.w != *sb.w)
288                 return false;
289             --length;
290             ++sa.w;
291             ++sb.w;
292
293             // now both addresses are 4-bytes aligned
294         }
295
296         // both addresses are 4-bytes aligned
297         // do a fast 32-bit comparison
298         register const quint32 *e = sa.d + (length >> 1);
299         for ( ; sa.d != e; ++sa.d, ++sb.d) {
300             if (*sa.d != *sb.d)
301                 return false;
302         }
303
304         // do we have a tail?
305         return (length & 1) ? *sa.w == *sb.w : true;
306     } else {
307         // one of the addresses isn't 4-byte aligned but the other is
308         register const quint16 *e = sa.w + length;
309         for ( ; sa.w != e; ++sa.w, ++sb.w) {
310             if (*sa.w != *sb.w)
311                 return false;
312         }
313     }
314     return true;
315 }
316
317 /*!
318     \internal
319
320     Returns the index position of the first occurrence of the
321     character \a ch in the string given by \a str and \a len,
322     searching forward from index
323     position \a from. Returns -1 if \a ch could not be found.
324 */
325 static int findChar(const QChar *str, int len, QChar ch, int from,
326     Qt::CaseSensitivity cs)
327 {
328     const ushort *s = (const ushort *)str;
329     ushort c = ch.unicode();
330     if (from < 0)
331         from = qMax(from + len, 0);
332     if (from < len) {
333         const ushort *n = s + from - 1;
334         const ushort *e = s + len;
335         if (cs == Qt::CaseSensitive) {
336             while (++n != e)
337                 if (*n == c)
338                     return  n - s;
339         } else {
340             c = foldCase(c);
341             while (++n != e)
342                 if (foldCase(*n) == c)
343                     return  n - s;
344         }
345     }
346     return -1;
347 }
348
349 #define REHASH(a) \
350     if (sl_minus_1 < (int)sizeof(int) * CHAR_BIT)       \
351         hashHaystack -= (a) << sl_minus_1; \
352     hashHaystack <<= 1
353
354 inline bool qIsUpper(char ch)
355 {
356     return ch >= 'A' && ch <= 'Z';
357 }
358
359 inline bool qIsDigit(char ch)
360 {
361     return ch >= '0' && ch <= '9';
362 }
363
364 inline char qToLower(char ch)
365 {
366     if (ch >= 'A' && ch <= 'Z')
367         return ch - 'A' + 'a';
368     else
369         return ch;
370 }
371
372 const QString::Null QString::null = { };
373
374 /*!
375   \macro QT_NO_CAST_FROM_ASCII
376   \relates QString
377
378   Disables automatic conversions from 8-bit strings (char *) to unicode QStrings
379
380   \sa QT_NO_CAST_TO_ASCII, QT_NO_CAST_FROM_BYTEARRAY
381 */
382
383 /*!
384   \macro QT_NO_CAST_TO_ASCII
385   \relates QString
386
387   disables automatic conversion from QString to 8-bit strings (char *)
388
389   \sa QT_NO_CAST_FROM_ASCII, QT_NO_CAST_FROM_BYTEARRAY
390 */
391
392 /*!
393   \macro QT_ASCII_CAST_WARNINGS
394   \internal
395   \relates QString
396
397   This macro can be defined to force a warning whenever a function is
398   called that automatically converts between unicode and 8-bit encodings.
399
400   Note: This only works for compilers that support warnings for
401   deprecated API.
402
403   \sa QT_NO_CAST_TO_ASCII, QT_NO_CAST_FROM_ASCII
404 */
405
406 /*!
407     \class QCharRef
408     \reentrant
409     \brief The QCharRef class is a helper class for QString.
410
411     \internal
412
413     \ingroup string-processing
414
415     When you get an object of type QCharRef, if you can assign to it,
416     the assignment will apply to the character in the string from
417     which you got the reference. That is its whole purpose in life.
418     The QCharRef becomes invalid once modifications are made to the
419     string: if you want to keep the character, copy it into a QChar.
420
421     Most of the QChar member functions also exist in QCharRef.
422     However, they are not explicitly documented here.
423
424     \sa QString::operator[]() QString::at() QChar
425 */
426
427 /*!
428     \class QString
429     \reentrant
430
431     \brief The QString class provides a Unicode character string.
432
433     \ingroup tools
434     \ingroup shared
435     \ingroup string-processing
436
437     QString stores a string of 16-bit \l{QChar}s, where each QChar
438     corresponds one Unicode 4.0 character. (Unicode characters
439     with code values above 65535 are stored using surrogate pairs,
440     i.e., two consecutive \l{QChar}s.)
441
442     \l{Unicode} is an international standard that supports most of the
443     writing systems in use today. It is a superset of US-ASCII (ANSI
444     X3.4-1986) and Latin-1 (ISO 8859-1), and all the US-ASCII/Latin-1
445     characters are available at the same code positions.
446
447     Behind the scenes, QString uses \l{implicit sharing}
448     (copy-on-write) to reduce memory usage and to avoid the needless
449     copying of data. This also helps reduce the inherent overhead of
450     storing 16-bit characters instead of 8-bit characters.
451
452     In addition to QString, Qt also provides the QByteArray class to
453     store raw bytes and traditional 8-bit '\\0'-terminated strings.
454     For most purposes, QString is the class you want to use. It is
455     used throughout the Qt API, and the Unicode support ensures that
456     your applications will be easy to translate if you want to expand
457     your application's market at some point. The two main cases where
458     QByteArray is appropriate are when you need to store raw binary
459     data, and when memory conservation is critical (e.g., with
460     \l{Qt for Embedded Linux}).
461
462     \tableofcontents
463
464     \section1 Initializing a String
465
466     One way to initialize a QString is simply to pass a \c{const char
467     *} to its constructor. For example, the following code creates a
468     QString of size 5 containing the data "Hello":
469
470     \snippet doc/src/snippets/qstring/main.cpp 0
471
472     QString converts the \c{const char *} data into Unicode using the
473     fromAscii() function. fromAscii() treats ordinals above 128 as Latin-1
474     characters.
475
476     In all of the QString functions that take \c{const char *}
477     parameters, the \c{const char *} is interpreted as a classic
478     C-style '\\0'-terminated string. It is legal for the \c{const char
479     *} parameter to be 0.
480
481     You can also provide string data as an array of \l{QChar}s:
482
483     \snippet doc/src/snippets/qstring/main.cpp 1
484
485     QString makes a deep copy of the QChar data, so you can modify it
486     later without experiencing side effects. (If for performance
487     reasons you don't want to take a deep copy of the character data,
488     use QString::fromRawData() instead.)
489
490     Another approach is to set the size of the string using resize()
491     and to initialize the data character per character. QString uses
492     0-based indexes, just like C++ arrays. To access the character at
493     a particular index position, you can use \l operator[](). On
494     non-const strings, \l operator[]() returns a reference to a
495     character that can be used on the left side of an assignment. For
496     example:
497
498     \snippet doc/src/snippets/qstring/main.cpp 2
499
500     For read-only access, an alternative syntax is to use the at()
501     function:
502
503     \snippet doc/src/snippets/qstring/main.cpp 3
504
505     The at() function can be faster than \l operator[](), because it
506     never causes a \l{deep copy} to occur. Alternatively, use the
507     left(), right(), or mid() functions to extract several characters
508     at a time.
509
510     A QString can embed '\\0' characters (QChar::Null). The size()
511     function always returns the size of the whole string, including
512     embedded '\\0' characters.
513
514     After a call to the resize() function, newly allocated characters
515     have undefined values. To set all the characters in the string to
516     a particular value, use the fill() function.
517
518     QString provides dozens of overloads designed to simplify string
519     usage. For example, if you want to compare a QString with a string
520     literal, you can write code like this and it will work as expected:
521
522     \snippet doc/src/snippets/qstring/main.cpp 4
523
524     You can also pass string literals to functions that take QStrings
525     as arguments, invoking the QString(const char *)
526     constructor. Similarly, you can pass a QString to a function that
527     takes a \c{const char *} argument using the \l qPrintable() macro
528     which returns the given QString as a \c{const char *}. This is
529     equivalent to calling <QString>.toLocal8Bit().constData().
530
531     \section1 Manipulating String Data
532
533     QString provides the following basic functions for modifying the
534     character data: append(), prepend(), insert(), replace(), and
535     remove(). For example:
536
537     \snippet doc/src/snippets/qstring/main.cpp 5
538
539     If you are building a QString gradually and know in advance
540     approximately how many characters the QString will contain, you
541     can call reserve(), asking QString to preallocate a certain amount
542     of memory. You can also call capacity() to find out how much
543     memory QString actually allocated.
544
545     The replace() and remove() functions' first two arguments are the
546     position from which to start erasing and the number of characters
547     that should be erased.  If you want to replace all occurrences of
548     a particular substring with another, use one of the two-parameter
549     replace() overloads.
550
551     A frequent requirement is to remove whitespace characters from a
552     string ('\\n', '\\t', ' ', etc.). If you want to remove whitespace
553     from both ends of a QString, use the trimmed() function. If you
554     want to remove whitespace from both ends and replace multiple
555     consecutive whitespaces with a single space character within the
556     string, use simplified().
557
558     If you want to find all occurrences of a particular character or
559     substring in a QString, use the indexOf() or lastIndexOf()
560     functions. The former searches forward starting from a given index
561     position, the latter searches backward. Both return the index
562     position of the character or substring if they find it; otherwise,
563     they return -1.  For example, here's a typical loop that finds all
564     occurrences of a particular substring:
565
566     \snippet doc/src/snippets/qstring/main.cpp 6
567
568     QString provides many functions for converting numbers into
569     strings and strings into numbers. See the arg() functions, the
570     setNum() functions, the number() static functions, and the
571     toInt(), toDouble(), and similar functions.
572
573     To get an upper- or lowercase version of a string use toUpper() or
574     toLower().
575
576     Lists of strings are handled by the QStringList class. You can
577     split a string into a list of strings using the split() function,
578     and join a list of strings into a single string with an optional
579     separator using QStringList::join(). You can obtain a list of
580     strings from a string list that contain a particular substring or
581     that match a particular QRegExp using the QStringList::filter()
582     function.
583
584     \section1 Querying String Data
585
586     If you want to see if a QString starts or ends with a particular
587     substring use startsWith() or endsWith(). If you simply want to
588     check whether a QString contains a particular character or
589     substring, use the contains() function. If you want to find out
590     how many times a particular character or substring occurs in the
591     string, use count().
592
593     QStrings can be compared using overloaded operators such as \l
594     operator<(), \l operator<=(), \l operator==(), \l operator>=(),
595     and so on.  Note that the comparison is based exclusively on the
596     numeric Unicode values of the characters. It is very fast, but is
597     not what a human would expect; the QString::localeAwareCompare()
598     function is a better choice for sorting user-interface strings.
599
600     To obtain a pointer to the actual character data, call data() or
601     constData(). These functions return a pointer to the beginning of
602     the QChar data. The pointer is guaranteed to remain valid until a
603     non-const function is called on the QString.
604
605     \section1 Converting Between 8-Bit Strings and Unicode Strings
606
607     QString provides the following four functions that return a
608     \c{const char *} version of the string as QByteArray: toAscii(),
609     toLatin1(), toUtf8(), and toLocal8Bit().
610
611     \list
612     \li toAscii() returns a Latin-1 (ISO 8859-1) encoded 8-bit string.
613     \li toLatin1() returns a Latin-1 (ISO 8859-1) encoded 8-bit string.
614     \li toUtf8() returns a UTF-8 encoded 8-bit string. UTF-8 is a
615        superset of US-ASCII (ANSI X3.4-1986) that supports the entire
616        Unicode character set through multibyte sequences.
617     \li toLocal8Bit() returns an 8-bit string using the system's local
618        encoding.
619     \endlist
620
621     To convert from one of these encodings, QString provides
622     fromAscii(), fromLatin1(), fromUtf8(), and fromLocal8Bit(). Other
623     encodings are supported through the QTextCodec class.
624
625     As mentioned above, QString provides a lot of functions and
626     operators that make it easy to interoperate with \c{const char *}
627     strings. But this functionality is a double-edged sword: It makes
628     QString more convenient to use if all strings are US-ASCII or
629     Latin-1, but there is always the risk that an implicit conversion
630     from or to \c{const char *} is done using the wrong 8-bit
631     encoding. To minimize these risks, you can turn off these implicit
632     conversions by defining the following two preprocessor symbols:
633
634     \list
635     \li \c QT_NO_CAST_FROM_ASCII disables automatic conversions from
636        C string literals and pointers to Unicode.
637     \li \c QT_NO_CAST_TO_ASCII disables automatic conversion from QString
638        to C strings.
639     \endlist
640
641     One way to define these preprocessor symbols globally for your
642     application is to add the following entry to your
643     \l{qmake Project Files}{qmake project file}:
644
645     \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 0
646
647     You then need to explicitly call fromAscii(), fromLatin1(),
648     fromUtf8(), or fromLocal8Bit() to construct a QString from an
649     8-bit string, or use the lightweight QLatin1String class, for
650     example:
651
652     \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 1
653
654     Similarly, you must call toAscii(), toLatin1(), toUtf8(), or
655     toLocal8Bit() explicitly to convert the QString to an 8-bit
656     string.  (Other encodings are supported through the QTextCodec
657     class.)
658
659     \table 100 %
660     \header
661     \li Note for C Programmers
662
663     \row
664     \li
665     Due to C++'s type system and the fact that QString is
666     \l{implicitly shared}, QStrings may be treated like \c{int}s or
667     other basic types. For example:
668
669     \snippet doc/src/snippets/qstring/main.cpp 7
670
671     The \c result variable, is a normal variable allocated on the
672     stack. When \c return is called, and because we're returning by
673     value, the copy constructor is called and a copy of the string is
674     returned. No actual copying takes place thanks to the implicit
675     sharing.
676
677     \endtable
678
679     \section1 Distinction Between Null and Empty Strings
680
681     For historical reasons, QString distinguishes between a null
682     string and an empty string. A \e null string is a string that is
683     initialized using QString's default constructor or by passing
684     (const char *)0 to the constructor. An \e empty string is any
685     string with size 0. A null string is always empty, but an empty
686     string isn't necessarily null:
687
688     \snippet doc/src/snippets/qstring/main.cpp 8
689
690     All functions except isNull() treat null strings the same as empty
691     strings. For example, toAscii().constData() returns a pointer to a
692     '\\0' character for a null string (\e not a null pointer), and
693     QString() compares equal to QString(""). We recommend that you
694     always use the isEmpty() function and avoid isNull().
695
696     \section1 Argument Formats
697
698     In member functions where an argument \e format can be specified
699     (e.g., arg(), number()), the argument \e format can be one of the
700     following:
701
702     \table
703     \header \li Format \li Meaning
704     \row \li \c e \li format as [-]9.9e[+|-]999
705     \row \li \c E \li format as [-]9.9E[+|-]999
706     \row \li \c f \li format as [-]9.9
707     \row \li \c g \li use \c e or \c f format, whichever is the most concise
708     \row \li \c G \li use \c E or \c f format, whichever is the most concise
709     \endtable
710
711     A \e precision is also specified with the argument \e format. For
712     the 'e', 'E', and 'f' formats, the \e precision represents the
713     number of digits \e after the decimal point. For the 'g' and 'G'
714     formats, the \e precision represents the maximum number of
715     significant digits (trailing zeroes are omitted).
716
717     \section1 More Efficient String Construction
718
719     Many strings are known at compile time. But the trivial
720     constructor QString("Hello"), will copy the contents of the string,
721     treating the contents as Latin-1. To avoid this one can use the
722     QStringLiteral macro to directly create the required data at compile
723     time. Constructing a QString out of the literal does then not cause
724     any overhead at runtime.
725
726     A slightly less efficient way is to use QLatin1String. This class wraps
727     a C string literal, precalculates it length at compile time and can
728     then be used for faster comparison with QStrings and conversion to
729     QStrings than a regular C string literal.
730
731     Using the QString \c{'+'} operator, it is easy to construct a
732     complex string from multiple substrings. You will often write code
733     like this:
734
735     \snippet doc/src/snippets/qstring/stringbuilder.cpp 0
736
737     There is nothing wrong with either of these string constructions,
738     but there are a few hidden inefficiencies. Beginning with Qt 4.6,
739     you can eliminate them.
740
741     First, multiple uses of the \c{'+'} operator usually means
742     multiple memory allocations. When concatenating \e{n} substrings,
743     where \e{n > 2}, there can be as many as \e{n - 1} calls to the
744     memory allocator.
745
746     In 4.6, an internal template class \c{QStringBuilder} has been
747     added along with a few helper functions. This class is marked
748     internal and does not appear in the documentation, because you
749     aren't meant to instantiate it in your code. Its use will be
750     automatic, as described below. The class is found in
751     \c {src/corelib/tools/qstringbuilder.cpp} if you want to have a
752     look at it.
753
754     \c{QStringBuilder} uses expression templates and reimplements the
755     \c{'%'} operator so that when you use \c{'%'} for string
756     concatenation instead of \c{'+'}, multiple substring
757     concatenations will be postponed until the final result is about
758     to be assigned to a QString. At this point, the amount of memory
759     required for the final result is known. The memory allocator is
760     then called \e{once} to get the required space, and the substrings
761     are copied into it one by one.
762
763     Additional efficiency is gained by inlining and reduced reference
764     counting (the QString created from a \c{QStringBuilder} typically
765     has a ref count of 1, whereas QString::append() needs an extra
766     test).
767
768     There are three ways you can access this improved method of string
769     construction. The straightforward way is to include
770     \c{QStringBuilder} wherever you want to use it, and use the
771     \c{'%'} operator instead of \c{'+'} when concatenating strings:
772
773     \snippet doc/src/snippets/qstring/stringbuilder.cpp 5
774
775     A more global approach which is the most convenient but
776     not entirely source compatible, is to this define in your
777     .pro file:
778
779     \snippet doc/src/snippets/qstring/stringbuilder.cpp 3
780
781     and the \c{'+'} will automatically be performed as the
782     \c{QStringBuilder} \c{'%'} everywhere.
783
784     \sa fromRawData(), QChar, QLatin1String, QByteArray, QStringRef
785 */
786
787 /*!
788     \enum QString::SplitBehavior
789
790     This enum specifies how the split() function should behave with
791     respect to empty strings.
792
793     \value KeepEmptyParts  If a field is empty, keep it in the result.
794     \value SkipEmptyParts  If a field is empty, don't include it in the result.
795
796     \sa split()
797 */
798
799 const QStaticStringData<1> QString::shared_null = { Q_STATIC_STRING_DATA_HEADER_INITIALIZER(0), { 0 } };
800 const QStaticStringData<1> QString::shared_empty = { Q_STATIC_STRING_DATA_HEADER_INITIALIZER(0), { 0 } };
801
802 /*! \typedef QString::ConstIterator
803
804     Qt-style synonym for QString::const_iterator.
805 */
806
807 /*! \typedef QString::Iterator
808
809     Qt-style synonym for QString::iterator.
810 */
811
812 /*! \typedef QString::const_iterator
813
814     The QString::const_iterator typedef provides an STL-style const
815     iterator for QString.
816
817     \sa QString::iterator
818 */
819
820 /*! \typedef QString::iterator
821
822     The QString::iterator typedef provides an STL-style non-const
823     iterator for QString.
824
825     \sa QString::const_iterator
826 */
827
828 /*!
829     \typedef QString::const_reference
830
831     The QString::const_reference typedef provides an STL-style
832     const reference for QString.
833 */
834 /*!
835     \typedef QString::reference
836
837     The QString::const_reference typedef provides an STL-style
838     reference for QString.
839 */
840 /*!
841     \typedef QString::value_type
842
843     The QString::const_reference typedef provides an STL-style
844     value type for QString.
845 */
846
847 /*! \fn QString::iterator QString::begin()
848
849     Returns an \l{STL-style iterator} pointing to the first character in
850     the string.
851
852     \sa constBegin(), end()
853 */
854
855 /*! \fn QString::const_iterator QString::begin() const
856
857     \overload begin()
858 */
859
860 /*! \fn QString::const_iterator QString::cbegin() const
861     \since 5.0
862
863     Returns a const \l{STL-style iterator} pointing to the first character
864     in the string.
865
866     \sa begin(), cend()
867 */
868
869 /*! \fn QString::const_iterator QString::constBegin() const
870
871     Returns a const \l{STL-style iterator} pointing to the first character
872     in the string.
873
874     \sa begin(), constEnd()
875 */
876
877 /*! \fn QString::iterator QString::end()
878
879     Returns an \l{STL-style iterator} pointing to the imaginary character
880     after the last character in the string.
881
882     \sa begin(), constEnd()
883 */
884
885 /*! \fn QString::const_iterator QString::end() const
886
887     \overload end()
888 */
889
890 /*! \fn QString::const_iterator QString::cend() const
891     \since 5.0
892
893     Returns a const \l{STL-style iterator} pointing to the imaginary
894     item after the last item in the list.
895
896     \sa cbegin(), end()
897 */
898
899 /*! \fn QString::const_iterator QString::constEnd() const
900
901     Returns a const \l{STL-style iterator} pointing to the imaginary
902     item after the last item in the list.
903
904     \sa constBegin(), end()
905 */
906
907 /*!
908     \fn QString::QString()
909
910     Constructs a null string. Null strings are also empty.
911
912     \sa isEmpty()
913 */
914
915 /*! \fn QString::QString(const char *str)
916
917     Constructs a string initialized with the 8-bit string \a str. The
918     given const char pointer is converted to Unicode using the
919     fromAscii() function.
920
921     You can disable this constructor by defining \c
922     QT_NO_CAST_FROM_ASCII when you compile your applications. This
923     can be useful if you want to ensure that all user-visible strings
924     go through QObject::tr(), for example.
925
926     \sa fromAscii(), fromLatin1(), fromLocal8Bit(), fromUtf8()
927 */
928
929 /*! \fn QString QString::fromStdString(const std::string &str)
930
931     Returns a copy of the \a str string. The given string is converted
932     to Unicode using the fromAscii() function.
933
934     This constructor is only available if Qt is configured with STL
935     compatibility enabled.
936
937     \sa  fromAscii(), fromLatin1(), fromLocal8Bit(), fromUtf8()
938 */
939
940 /*! \fn QString QString::fromStdWString(const std::wstring &str)
941
942     Returns a copy of the \a str string. The given string is assumed
943     to be encoded in utf16 if the size of wchar_t is 2 bytes (e.g. on
944     windows) and ucs4 if the size of wchar_t is 4 bytes (most Unix
945     systems).
946
947     \sa fromUtf16(), fromLatin1(), fromLocal8Bit(), fromUtf8(), fromUcs4()
948 */
949
950 /*! \fn QString QString::fromWCharArray(const wchar_t *string, int size)
951     \since 4.2
952
953     Returns a copy of the \a string, where the encoding of \a string depends on
954     the size of wchar. If wchar is 4 bytes, the \a string is interpreted as ucs-4,
955     if wchar is 2 bytes it is interpreted as ucs-2.
956
957     If \a size is -1 (default), the \a string has to be 0 terminated.
958
959     \sa fromUtf16(), fromLatin1(), fromLocal8Bit(), fromUtf8(), fromUcs4(), fromStdWString()
960 */
961
962 /*! \fn std::wstring QString::toStdWString() const
963
964     Returns a std::wstring object with the data contained in this
965     QString. The std::wstring is encoded in utf16 on platforms where
966     wchar_t is 2 bytes wide (e.g. windows) and in ucs4 on platforms
967     where wchar_t is 4 bytes wide (most Unix systems).
968
969     This operator is mostly useful to pass a QString to a function
970     that accepts a std::wstring object.
971
972     \sa utf16(), toAscii(), toLatin1(), toUtf8(), toLocal8Bit()
973 */
974
975 // ### replace with QCharIterator
976 int QString::toUcs4_helper(const ushort *uc, int length, uint *out)
977 {
978     int i = 0;
979     for (; i < length; ++i) {
980         uint u = uc[i];
981         if (QChar::isHighSurrogate(u) && i + 1 < length) {
982             ushort low = uc[i+1];
983             if (QChar::isLowSurrogate(low)) {
984                 ++i;
985                 u = QChar::surrogateToUcs4(u, low);
986             }
987         }
988         *out++ = u;
989     }
990     return i;
991 }
992
993 /*! \fn int QString::toWCharArray(wchar_t *array) const
994   \since 4.2
995
996   Fills the \a array with the data contained in this QString object.
997   The array is encoded in utf16 on platforms where
998   wchar_t is 2 bytes wide (e.g. windows) and in ucs4 on platforms
999   where wchar_t is 4 bytes wide (most Unix systems).
1000
1001   \a array has to be allocated by the caller and contain enough space to
1002   hold the complete string (allocating the array with the same length as the
1003   string is always sufficient).
1004
1005   returns the actual length of the string in \a array.
1006
1007   \note This function does not append a null character to the array.
1008
1009   \sa utf16(), toUcs4(), toAscii(), toLatin1(), toUtf8(), toLocal8Bit(), toStdWString()
1010 */
1011
1012 /*! \fn QString::QString(const QString &other)
1013
1014     Constructs a copy of \a other.
1015
1016     This operation takes \l{constant time}, because QString is
1017     \l{implicitly shared}. This makes returning a QString from a
1018     function very fast. If a shared instance is modified, it will be
1019     copied (copy-on-write), and that takes \l{linear time}.
1020
1021     \sa operator=()
1022 */
1023
1024 /*!
1025     Constructs a string initialized with the first \a size characters
1026     of the QChar array \a unicode.
1027
1028     If \a unicode is 0, a null string is constructed.
1029
1030     If \a size is negative, \a unicode is assumed to point to a nul-terminated
1031     array and its length is determined dynamically. The terminating
1032     nul-character is not considered part of the string.
1033
1034     QString makes a deep copy of the string data. The unicode data is copied as
1035     is and the Byte Order Mark is preserved if present.
1036
1037     \sa fromRawData()
1038 */
1039 QString::QString(const QChar *unicode, int size)
1040 {
1041    if (!unicode) {
1042         d = shared_null.data_ptr();
1043     } else {
1044         if (size < 0) {
1045             size = 0;
1046             while (unicode[size] != 0)
1047                 ++size;
1048         }
1049         if (!size) {
1050             d = shared_empty.data_ptr();
1051         } else {
1052             d = (Data*) ::malloc(sizeof(Data)+(size+1)*sizeof(QChar));
1053             Q_CHECK_PTR(d);
1054             d->ref.initializeOwned();
1055             d->size = size;
1056             d->alloc = (uint) size;
1057             d->capacityReserved = false;
1058             d->offset = sizeof(QStringData);
1059             memcpy(d->data(), unicode, size * sizeof(QChar));
1060             d->data()[size] = '\0';
1061         }
1062     }
1063 }
1064
1065 /*!
1066     Constructs a string of the given \a size with every character set
1067     to \a ch.
1068
1069     \sa fill()
1070 */
1071 QString::QString(int size, QChar ch)
1072 {
1073    if (size <= 0) {
1074         d = shared_empty.data_ptr();
1075     } else {
1076         d = (Data*) ::malloc(sizeof(Data)+(size+1)*sizeof(QChar));
1077         Q_CHECK_PTR(d);
1078         d->ref.initializeOwned();
1079         d->size = size;
1080         d->alloc = (uint) size;
1081         d->capacityReserved = false;
1082         d->offset = sizeof(QStringData);
1083         d->data()[size] = '\0';
1084         ushort *i = d->data() + size;
1085         ushort *b = d->data();
1086         const ushort value = ch.unicode();
1087         while (i != b)
1088            *--i = value;
1089     }
1090 }
1091
1092 /*! \fn QString::QString(int size, Qt::Initialization)
1093   \internal
1094
1095   Constructs a string of the given \a size without initializing the
1096   characters. This is only used in \c QStringBuilder::toString().
1097 */
1098 QString::QString(int size, Qt::Initialization)
1099 {
1100     d = (Data*) ::malloc(sizeof(Data)+(size+1)*sizeof(QChar));
1101     Q_CHECK_PTR(d);
1102     d->ref.initializeOwned();
1103     d->size = size;
1104     d->alloc = (uint) size;
1105     d->capacityReserved = false;
1106     d->offset = sizeof(QStringData);
1107     d->data()[size] = '\0';
1108 }
1109
1110 /*! \fn QString::QString(const QLatin1String &str)
1111
1112     Constructs a copy of the Latin-1 string \a str.
1113
1114     \sa fromLatin1()
1115 */
1116
1117 /*!
1118     Constructs a string of size 1 containing the character \a ch.
1119 */
1120 QString::QString(QChar ch)
1121 {
1122     d = (Data *) ::malloc(sizeof(Data) + 2*sizeof(QChar));
1123     Q_CHECK_PTR(d);
1124     d->ref.initializeOwned();
1125     d->size = 1;
1126     d->alloc = 1;
1127     d->capacityReserved = false;
1128     d->offset = sizeof(QStringData);
1129     d->data()[0] = ch.unicode();
1130     d->data()[1] = '\0';
1131 }
1132
1133 /*! \fn QString::QString(const QByteArray &ba)
1134
1135     Constructs a string initialized with the byte array \a ba. The
1136     given byte array is converted to Unicode using fromAscii(). Stops
1137     copying at the first 0 character, otherwise copies the entire byte
1138     array.
1139
1140     You can disable this constructor by defining \c
1141     QT_NO_CAST_FROM_ASCII when you compile your applications. This
1142     can be useful if you want to ensure that all user-visible strings
1143     go through QObject::tr(), for example.
1144
1145     \sa fromAscii(), fromLatin1(), fromLocal8Bit(), fromUtf8()
1146 */
1147
1148 /*! \fn QString::QString(const Null &)
1149     \internal
1150 */
1151
1152 /*! \fn QString &QString::operator=(const Null &)
1153     \internal
1154 */
1155
1156 /*!
1157   \fn QString::~QString()
1158
1159     Destroys the string.
1160 */
1161
1162
1163 /*! \fn void QString::swap(QString &other)
1164     \since 4.8
1165
1166     Swaps string \a other with this string. This operation is very fast and
1167     never fails.
1168 */
1169
1170 /*! \fn void QString::detach()
1171
1172     \internal
1173 */
1174
1175 /*! \fn bool QString::isDetached() const
1176
1177     \internal
1178 */
1179
1180 /*! \fn bool QString::isSharedWith(const QString &other) const
1181
1182     \internal
1183 */
1184
1185 // ### Qt 5: rename freeData() to avoid confusion. See task 197625.
1186 void QString::free(Data *d)
1187 {
1188     ::free(d);
1189 }
1190
1191 /*!
1192     Sets the size of the string to \a size characters.
1193
1194     If \a size is greater than the current size, the string is
1195     extended to make it \a size characters long with the extra
1196     characters added to the end. The new characters are uninitialized.
1197
1198     If \a size is less than the current size, characters are removed
1199     from the end.
1200
1201     Example:
1202
1203     \snippet doc/src/snippets/qstring/main.cpp 45
1204
1205     If you want to append a certain number of identical characters to
1206     the string, use \l operator+=() as follows rather than resize():
1207
1208     \snippet doc/src/snippets/qstring/main.cpp 46
1209
1210     If you want to expand the string so that it reaches a certain
1211     width and fill the new positions with a particular character, use
1212     the leftJustified() function:
1213
1214     If \a size is negative, it is equivalent to passing zero.
1215
1216     \snippet doc/src/snippets/qstring/main.cpp 47
1217
1218     \sa truncate(), reserve()
1219 */
1220
1221 void QString::resize(int size)
1222 {
1223     if (size < 0)
1224         size = 0;
1225
1226     if (IS_RAW_DATA(d) && !d->ref.isShared() && size < d->size) {
1227         d->size = size;
1228         return;
1229     }
1230
1231     if (size == 0 && !d->capacityReserved) {
1232         Data *x = shared_empty.data_ptr();
1233         if (!d->ref.deref())
1234             QString::free(d);
1235         d = x;
1236     } else {
1237         if (d->ref.isShared() || size > int(d->alloc) ||
1238             (!d->capacityReserved && size < d->size && size < int(d->alloc) >> 1))
1239             reallocData(size, true);
1240         if (d->alloc) {
1241             d->size = size;
1242             d->data()[size] = '\0';
1243         }
1244     }
1245 }
1246
1247 /*! \fn int QString::capacity() const
1248
1249     Returns the maximum number of characters that can be stored in
1250     the string without forcing a reallocation.
1251
1252     The sole purpose of this function is to provide a means of fine
1253     tuning QString's memory usage. In general, you will rarely ever
1254     need to call this function. If you want to know how many
1255     characters are in the string, call size().
1256
1257     \sa reserve(), squeeze()
1258 */
1259
1260 /*!
1261     \fn void QString::reserve(int size)
1262
1263     Attempts to allocate memory for at least \a size characters. If
1264     you know in advance how large the string will be, you can call
1265     this function, and if you resize the string often you are likely
1266     to get better performance. If \a size is an underestimate, the
1267     worst that will happen is that the QString will be a bit slower.
1268
1269     The sole purpose of this function is to provide a means of fine
1270     tuning QString's memory usage. In general, you will rarely ever
1271     need to call this function. If you want to change the size of the
1272     string, call resize().
1273
1274     This function is useful for code that needs to build up a long
1275     string and wants to avoid repeated reallocation. In this example,
1276     we want to add to the string until some condition is true, and
1277     we're fairly sure that size is large enough to make a call to
1278     reserve() worthwhile:
1279
1280     \snippet doc/src/snippets/qstring/main.cpp 44
1281
1282     \sa squeeze(), capacity()
1283 */
1284
1285 /*!
1286     \fn void QString::squeeze()
1287
1288     Releases any memory not required to store the character data.
1289
1290     The sole purpose of this function is to provide a means of fine
1291     tuning QString's memory usage. In general, you will rarely ever
1292     need to call this function.
1293
1294     \sa reserve(), capacity()
1295 */
1296
1297 void QString::reallocData(int alloc, bool grow)
1298 {
1299     if (grow)
1300         alloc = qAllocMore((alloc+1) * sizeof(QChar), sizeof(Data)) / sizeof(QChar) - 1;
1301
1302     if (d->ref.isShared() || IS_RAW_DATA(d)) {
1303         Data *x = static_cast<Data *>(::malloc(sizeof(Data) + (alloc+1) * sizeof(QChar)));
1304         Q_CHECK_PTR(x);
1305         x->ref.initializeOwned();
1306         x->size = qMin(alloc, d->size);
1307         x->alloc = (uint) alloc;
1308         x->capacityReserved = d->capacityReserved;
1309         x->offset = sizeof(QStringData);
1310         ::memcpy(x->data(), d->data(), x->size * sizeof(QChar));
1311         x->data()[x->size] = 0;
1312         if (!d->ref.deref())
1313             QString::free(d);
1314         d = x;
1315     } else {
1316         Data *p = static_cast<Data *>(::realloc(d, sizeof(Data) + (alloc+1) * sizeof(QChar)));
1317         Q_CHECK_PTR(p);
1318         d = p;
1319         d->alloc = alloc;
1320         d->offset = sizeof(QStringData);
1321     }
1322 }
1323
1324 void QString::expand(int i)
1325 {
1326     int sz = d->size;
1327     resize(qMax(i + 1, sz));
1328     if (d->size - 1 > sz) {
1329         ushort *n = d->data() + d->size - 1;
1330         ushort *e = d->data() + sz;
1331         while (n != e)
1332            * --n = ' ';
1333     }
1334 }
1335
1336 /*! \fn void QString::clear()
1337
1338     Clears the contents of the string and makes it empty.
1339
1340     \sa resize(), isEmpty()
1341 */
1342
1343 /*! \fn QString &QString::operator=(const QString &other)
1344
1345     Assigns \a other to this string and returns a reference to this
1346     string.
1347 */
1348
1349 QString &QString::operator=(const QString &other)
1350 {
1351     other.d->ref.ref();
1352     if (!d->ref.deref())
1353         QString::free(d);
1354     d = other.d;
1355     return *this;
1356 }
1357
1358
1359 /*! \fn QString &QString::operator=(const QLatin1String &str)
1360
1361     \overload operator=()
1362
1363     Assigns the Latin-1 string \a str to this string.
1364 */
1365
1366 /*! \fn QString &QString::operator=(const QByteArray &ba)
1367
1368     \overload operator=()
1369
1370     Assigns \a ba to this string. The byte array is converted to Unicode
1371     using the fromAscii() function. This function stops conversion at the
1372     first NUL character found, or the end of the \a ba byte array.
1373
1374     You can disable this operator by defining \c
1375     QT_NO_CAST_FROM_ASCII when you compile your applications. This
1376     can be useful if you want to ensure that all user-visible strings
1377     go through QObject::tr(), for example.
1378 */
1379
1380 /*! \fn QString &QString::operator=(const char *str)
1381
1382     \overload operator=()
1383
1384     Assigns \a str to this string. The const char pointer is converted
1385     to Unicode using the fromAscii() function.
1386
1387     You can disable this operator by defining \c
1388     QT_NO_CAST_FROM_ASCII when you compile your applications. This
1389     can be useful if you want to ensure that all user-visible strings
1390     go through QObject::tr(), for example.
1391 */
1392
1393 /*! \fn QString &QString::operator=(char ch)
1394
1395     \overload operator=()
1396
1397     Assigns character \a ch to this string. The character is converted
1398     to Unicode using the fromAscii() function.
1399
1400     You can disable this operator by defining \c
1401     QT_NO_CAST_FROM_ASCII when you compile your applications. This
1402     can be useful if you want to ensure that all user-visible strings
1403     go through QObject::tr(), for example.
1404 */
1405
1406 /*!
1407     \overload operator=()
1408
1409     Sets the string to contain the single character \a ch.
1410 */
1411 QString &QString::operator=(QChar ch)
1412 {
1413     return operator=(QString(ch));
1414 }
1415
1416 /*!
1417      \fn QString& QString::insert(int position, const QString &str)
1418
1419     Inserts the string \a str at the given index \a position and
1420     returns a reference to this string.
1421
1422     Example:
1423
1424     \snippet doc/src/snippets/qstring/main.cpp 26
1425
1426     If the given \a position is greater than size(), the array is
1427     first extended using resize().
1428
1429     \sa append(), prepend(), replace(), remove()
1430 */
1431
1432
1433 /*!
1434     \fn QString &QString::insert(int position, const QLatin1String &str)
1435     \overload insert()
1436
1437     Inserts the Latin-1 string \a str at the given index \a position.
1438 */
1439 QString &QString::insert(int i, const QLatin1String &str)
1440 {
1441     const uchar *s = (const uchar *)str.latin1();
1442     if (i < 0 || !s || !(*s))
1443         return *this;
1444
1445     int len = str.size();
1446     expand(qMax(d->size, i) + len - 1);
1447
1448     ::memmove(d->data() + i + len, d->data() + i, (d->size - i - len) * sizeof(QChar));
1449     for (int j = 0; j < len; ++j)
1450         d->data()[i + j] = s[j];
1451     return *this;
1452 }
1453
1454 /*!
1455     \fn QString& QString::insert(int position, const QChar *unicode, int size)
1456     \overload insert()
1457
1458     Inserts the first \a size characters of the QChar array \a unicode
1459     at the given index \a position in the string.
1460 */
1461 QString& QString::insert(int i, const QChar *unicode, int size)
1462 {
1463     if (i < 0 || size <= 0)
1464         return *this;
1465
1466     const ushort *s = (const ushort *)unicode;
1467     if (s >= d->data() && s < d->data() + d->alloc) {
1468         // Part of me - take a copy
1469         ushort *tmp = static_cast<ushort *>(::malloc(size * sizeof(QChar)));
1470         Q_CHECK_PTR(tmp);
1471         memcpy(tmp, s, size * sizeof(QChar));
1472         insert(i, reinterpret_cast<const QChar *>(tmp), size);
1473         ::free(tmp);
1474         return *this;
1475     }
1476
1477     expand(qMax(d->size, i) + size - 1);
1478
1479     ::memmove(d->data() + i + size, d->data() + i, (d->size - i - size) * sizeof(QChar));
1480     memcpy(d->data() + i, s, size * sizeof(QChar));
1481     return *this;
1482 }
1483
1484 /*!
1485     \fn QString& QString::insert(int position, QChar ch)
1486     \overload insert()
1487
1488     Inserts \a ch at the given index \a position in the string.
1489 */
1490
1491 QString& QString::insert(int i, QChar ch)
1492 {
1493     if (i < 0)
1494         i += d->size;
1495     if (i < 0)
1496         return *this;
1497     expand(qMax(i, d->size));
1498     ::memmove(d->data() + i + 1, d->data() + i, (d->size - i - 1) * sizeof(QChar));
1499     d->data()[i] = ch.unicode();
1500     return *this;
1501 }
1502
1503 /*!
1504     Appends the string \a str onto the end of this string.
1505
1506     Example:
1507
1508     \snippet doc/src/snippets/qstring/main.cpp 9
1509
1510     This is the same as using the insert() function:
1511
1512     \snippet doc/src/snippets/qstring/main.cpp 10
1513
1514     The append() function is typically very fast (\l{constant time}),
1515     because QString preallocates extra space at the end of the string
1516     data so it can grow without reallocating the entire string each
1517     time.
1518
1519     \sa operator+=(), prepend(), insert()
1520 */
1521 QString &QString::append(const QString &str)
1522 {
1523     if (str.d != &shared_null.str) {
1524         if (d == &shared_null.str) {
1525             operator=(str);
1526         } else {
1527             if (d->ref.isShared() || d->size + str.d->size > int(d->alloc))
1528                 reallocData(d->size + str.d->size, true);
1529             memcpy(d->data() + d->size, str.d->data(), str.d->size * sizeof(QChar));
1530             d->size += str.d->size;
1531             d->data()[d->size] = '\0';
1532         }
1533     }
1534     return *this;
1535 }
1536
1537 /*!
1538   \overload append()
1539
1540   Appends the Latin-1 string \a str to this string.
1541 */
1542 QString &QString::append(const QLatin1String &str)
1543 {
1544     const uchar *s = (const uchar *)str.latin1();
1545     if (s) {
1546         int len = str.size();
1547         if (d->ref.isShared() || d->size + len > int(d->alloc))
1548             reallocData(d->size + len, true);
1549         ushort *i = d->data() + d->size;
1550         while ((*i++ = *s++))
1551             ;
1552         d->size += len;
1553     }
1554     return *this;
1555 }
1556
1557 /*! \fn QString &QString::append(const QByteArray &ba)
1558
1559     \overload append()
1560
1561     Appends the byte array \a ba to this string. The given byte array
1562     is converted to Unicode using the fromAscii() function.
1563
1564     You can disable this function by defining \c QT_NO_CAST_FROM_ASCII
1565     when you compile your applications. This can be useful if you want
1566     to ensure that all user-visible strings go through QObject::tr(),
1567     for example.
1568 */
1569
1570 /*! \fn QString &QString::append(const char *str)
1571
1572     \overload append()
1573
1574     Appends the string \a str to this string. The given const char
1575     pointer is converted to Unicode using the fromAscii() function.
1576
1577     You can disable this function by defining \c QT_NO_CAST_FROM_ASCII
1578     when you compile your applications. This can be useful if you want
1579     to ensure that all user-visible strings go through QObject::tr(),
1580     for example.
1581 */
1582
1583 /*!
1584     \overload append()
1585
1586     Appends the character \a ch to this string.
1587 */
1588 QString &QString::append(QChar ch)
1589 {
1590     if (d->ref.isShared() || d->size + 1 > int(d->alloc))
1591         reallocData(d->size + 1, true);
1592     d->data()[d->size++] = ch.unicode();
1593     d->data()[d->size] = '\0';
1594     return *this;
1595 }
1596
1597 /*! \fn QString &QString::prepend(const QString &str)
1598
1599     Prepends the string \a str to the beginning of this string and
1600     returns a reference to this string.
1601
1602     Example:
1603
1604     \snippet doc/src/snippets/qstring/main.cpp 36
1605
1606     \sa append(), insert()
1607 */
1608
1609 /*! \fn QString &QString::prepend(const QLatin1String &str)
1610
1611     \overload prepend()
1612
1613     Prepends the Latin-1 string \a str to this string.
1614 */
1615
1616 /*! \fn QString &QString::prepend(const QByteArray &ba)
1617
1618     \overload prepend()
1619
1620     Prepends the byte array \a ba to this string. The byte array is
1621     converted to Unicode using the fromAscii() function.
1622
1623     You can disable this function by defining \c
1624     QT_NO_CAST_FROM_ASCII when you compile your applications. This
1625     can be useful if you want to ensure that all user-visible strings
1626     go through QObject::tr(), for example.
1627 */
1628
1629 /*! \fn QString &QString::prepend(const char *str)
1630
1631     \overload prepend()
1632
1633     Prepends the string \a str to this string. The const char pointer
1634     is converted to Unicode using the fromAscii() function.
1635
1636     You can disable this function by defining \c
1637     QT_NO_CAST_FROM_ASCII when you compile your applications. This
1638     can be useful if you want to ensure that all user-visible strings
1639     go through QObject::tr(), for example.
1640 */
1641
1642 /*! \fn QString &QString::prepend(QChar ch)
1643
1644     \overload prepend()
1645
1646     Prepends the character \a ch to this string.
1647 */
1648
1649 /*!
1650   \fn QString &QString::remove(int position, int n)
1651
1652   Removes \a n characters from the string, starting at the given \a
1653   position index, and returns a reference to the string.
1654
1655   If the specified \a position index is within the string, but \a
1656   position + \a n is beyond the end of the string, the string is
1657   truncated at the specified \a position.
1658
1659   \snippet doc/src/snippets/qstring/main.cpp 37
1660
1661   \sa insert(), replace()
1662 */
1663 QString &QString::remove(int pos, int len)
1664 {
1665     if (pos < 0)  // count from end of string
1666         pos += d->size;
1667     if (pos < 0 || pos >= d->size) {
1668         // range problems
1669     } else if (len >= d->size - pos) {
1670         resize(pos); // truncate
1671     } else if (len > 0) {
1672         detach();
1673         memmove(d->data() + pos, d->data() + pos + len,
1674                 (d->size - pos - len + 1) * sizeof(ushort));
1675         d->size -= len;
1676     }
1677     return *this;
1678 }
1679
1680 /*!
1681   Removes every occurrence of the given \a str string in this
1682   string, and returns a reference to this string.
1683
1684   If \a cs is Qt::CaseSensitive (default), the search is
1685   case sensitive; otherwise the search is case insensitive.
1686
1687   This is the same as \c replace(str, "", cs).
1688
1689   \sa replace()
1690 */
1691 QString &QString::remove(const QString &str, Qt::CaseSensitivity cs)
1692 {
1693     if (str.d->size) {
1694         int i = 0;
1695         while ((i = indexOf(str, i, cs)) != -1)
1696             remove(i, str.d->size);
1697     }
1698     return *this;
1699 }
1700
1701 /*!
1702   Removes every occurrence of the character \a ch in this string, and
1703   returns a reference to this string.
1704
1705   If \a cs is Qt::CaseSensitive (default), the search is case
1706   sensitive; otherwise the search is case insensitive.
1707
1708   Example:
1709
1710   \snippet doc/src/snippets/qstring/main.cpp 38
1711
1712   This is the same as \c replace(ch, "", cs).
1713
1714   \sa replace()
1715 */
1716 QString &QString::remove(QChar ch, Qt::CaseSensitivity cs)
1717 {
1718     int i = 0;
1719     ushort c = ch.unicode();
1720     if (cs == Qt::CaseSensitive) {
1721         while (i < d->size)
1722             if (d->data()[i] == ch)
1723                 remove(i, 1);
1724             else
1725                 i++;
1726     } else {
1727         c = foldCase(c);
1728         while (i < d->size)
1729             if (foldCase(d->data()[i]) == c)
1730                 remove(i, 1);
1731             else
1732                 i++;
1733     }
1734     return *this;
1735 }
1736
1737 /*!
1738   \fn QString &QString::remove(const QRegExp &rx)
1739
1740   Removes every occurrence of the regular expression \a rx in the
1741   string, and returns a reference to the string. For example:
1742
1743   \snippet doc/src/snippets/qstring/main.cpp 39
1744
1745   \sa indexOf(), lastIndexOf(), replace()
1746 */
1747
1748 /*!
1749   \fn QString &QString::remove(const QRegularExpression &re)
1750   \since 5.0
1751
1752   Removes every occurrence of the regular expression \a re in the
1753   string, and returns a reference to the string. For example:
1754
1755   \snippet doc/src/snippets/qstring/main.cpp 96
1756
1757   \sa indexOf(), lastIndexOf(), replace()
1758 */
1759
1760 /*!
1761   \fn QString &QString::replace(int position, int n, const QString &after)
1762
1763   Replaces \a n characters beginning at index \a position with
1764   the string \a after and returns a reference to this string.
1765
1766   Example:
1767
1768   \snippet doc/src/snippets/qstring/main.cpp 40
1769
1770   \sa insert(), remove()
1771 */
1772 QString &QString::replace(int pos, int len, const QString &after)
1773 {
1774     QString copy = after;
1775     return replace(pos, len, copy.constData(), copy.length());
1776 }
1777
1778 /*!
1779   \fn QString &QString::replace(int position, int n, const QChar *unicode, int size)
1780   \overload replace()
1781   Replaces \a n characters beginning at index \a position with the
1782   first \a size characters of the QChar array \a unicode and returns a
1783   reference to this string.
1784 */
1785 QString &QString::replace(int pos, int len, const QChar *unicode, int size)
1786 {
1787     if (pos < 0 || pos > d->size)
1788         return *this;
1789     if (pos + len > d->size)
1790         len = d->size - pos;
1791
1792     uint index = pos;
1793     replace_helper(&index, 1, len, unicode, size);
1794     return *this;
1795 }
1796
1797 /*!
1798   \fn QString &QString::replace(int position, int n, QChar after)
1799   \overload replace()
1800
1801   Replaces \a n characters beginning at index \a position with the
1802   character \a after and returns a reference to this string.
1803 */
1804 QString &QString::replace(int pos, int len, QChar after)
1805 {
1806     return replace(pos, len, &after, 1);
1807 }
1808
1809 /*!
1810   \overload replace()
1811   Replaces every occurrence of the string \a before with the string \a
1812   after and returns a reference to this string.
1813
1814   If \a cs is Qt::CaseSensitive (default), the search is case
1815   sensitive; otherwise the search is case insensitive.
1816
1817   Example:
1818
1819   \snippet doc/src/snippets/qstring/main.cpp 41
1820
1821   \note The replacement text is not rescanned after it is inserted.
1822
1823   Example:
1824
1825   \snippet doc/src/snippets/qstring/main.cpp 86
1826 */
1827 QString &QString::replace(const QString &before, const QString &after, Qt::CaseSensitivity cs)
1828 {
1829     return replace(before.constData(), before.size(), after.constData(), after.size(), cs);
1830 }
1831
1832 /*!
1833   \internal
1834  */
1835 void QString::replace_helper(uint *indices, int nIndices, int blen, const QChar *after, int alen)
1836 {
1837     // copy *after in case it lies inside our own d->data() area
1838     // (which we could possibly invalidate via a realloc or corrupt via memcpy operations.)
1839     QChar *afterBuffer = const_cast<QChar *>(after);
1840     if (after >= reinterpret_cast<QChar *>(d->data()) && after < reinterpret_cast<QChar *>(d->data()) + d->size) {
1841         afterBuffer = static_cast<QChar *>(::malloc(alen*sizeof(QChar)));
1842         Q_CHECK_PTR(afterBuffer);
1843         ::memcpy(afterBuffer, after, alen*sizeof(QChar));
1844     }
1845
1846     QT_TRY {
1847         if (blen == alen) {
1848             // replace in place
1849             detach();
1850             for (int i = 0; i < nIndices; ++i)
1851                 memcpy(d->data() + indices[i], afterBuffer, alen * sizeof(QChar));
1852         } else if (alen < blen) {
1853             // replace from front
1854             detach();
1855             uint to = indices[0];
1856             if (alen)
1857                 memcpy(d->data()+to, after, alen*sizeof(QChar));
1858             to += alen;
1859             uint movestart = indices[0] + blen;
1860             for (int i = 1; i < nIndices; ++i) {
1861                 int msize = indices[i] - movestart;
1862                 if (msize > 0) {
1863                     memmove(d->data() + to, d->data() + movestart, msize * sizeof(QChar));
1864                     to += msize;
1865                 }
1866                 if (alen) {
1867                     memcpy(d->data() + to, afterBuffer, alen*sizeof(QChar));
1868                     to += alen;
1869                 }
1870                 movestart = indices[i] + blen;
1871             }
1872             int msize = d->size - movestart;
1873             if (msize > 0)
1874                 memmove(d->data() + to, d->data() + movestart, msize * sizeof(QChar));
1875             resize(d->size - nIndices*(blen-alen));
1876         } else {
1877             // replace from back
1878             int adjust = nIndices*(alen-blen);
1879             int newLen = d->size + adjust;
1880             int moveend = d->size;
1881             resize(newLen);
1882
1883             while (nIndices) {
1884                 --nIndices;
1885                 int movestart = indices[nIndices] + blen;
1886                 int insertstart = indices[nIndices] + nIndices*(alen-blen);
1887                 int moveto = insertstart + alen;
1888                 memmove(d->data() + moveto, d->data() + movestart,
1889                         (moveend - movestart)*sizeof(QChar));
1890                 memcpy(d->data() + insertstart, afterBuffer, alen*sizeof(QChar));
1891                 moveend = movestart-blen;
1892             }
1893         }
1894     } QT_CATCH(const std::bad_alloc &) {
1895         if (afterBuffer != after)
1896             ::free(afterBuffer);
1897         QT_RETHROW;
1898     }
1899     if (afterBuffer != after)
1900         ::free(afterBuffer);
1901 }
1902
1903 /*!
1904   \since 4.5
1905   \overload replace()
1906
1907   Replaces each occurrence in this string of the first \a blen
1908   characters of \a before with the first \a alen characters of \a
1909   after and returns a reference to this string.
1910
1911   If \a cs is Qt::CaseSensitive (default), the search is case
1912   sensitive; otherwise the search is case insensitive.
1913 */
1914 QString &QString::replace(const QChar *before, int blen,
1915                           const QChar *after, int alen,
1916                           Qt::CaseSensitivity cs)
1917 {
1918     if (d->size == 0) {
1919         if (blen)
1920             return *this;
1921     } else {
1922         if (cs == Qt::CaseSensitive && before == after && blen == alen)
1923             return *this;
1924     }
1925     if (alen == 0 && blen == 0)
1926         return *this;
1927
1928     QStringMatcher matcher(before, blen, cs);
1929
1930     int index = 0;
1931     while (1) {
1932         uint indices[1024];
1933         uint pos = 0;
1934         while (pos < 1023) {
1935             index = matcher.indexIn(*this, index);
1936             if (index == -1)
1937                 break;
1938             indices[pos++] = index;
1939             index += blen;
1940             // avoid infinite loop
1941             if (!blen)
1942                 index++;
1943         }
1944         if (!pos)
1945             break;
1946
1947         replace_helper(indices, pos, blen, after, alen);
1948
1949         if (index == -1)
1950             break;
1951         // index has to be adjusted in case we get back into the loop above.
1952         index += pos*(alen-blen);
1953     }
1954
1955     return *this;
1956 }
1957
1958 /*!
1959   \overload replace()
1960   Replaces every occurrence of the character \a ch in the string with
1961   \a after and returns a reference to this string.
1962
1963   If \a cs is Qt::CaseSensitive (default), the search is case
1964   sensitive; otherwise the search is case insensitive.
1965 */
1966 QString& QString::replace(QChar ch, const QString &after, Qt::CaseSensitivity cs)
1967 {
1968     if (after.d->size == 0)
1969         return remove(ch, cs);
1970
1971     if (after.d->size == 1)
1972         return replace(ch, after.d->data()[0], cs);
1973
1974     if (d->size == 0)
1975         return *this;
1976
1977     ushort cc = (cs == Qt::CaseSensitive ? ch.unicode() : ch.toCaseFolded().unicode());
1978
1979     int index = 0;
1980     while (1) {
1981         uint indices[1024];
1982         uint pos = 0;
1983         if (cs == Qt::CaseSensitive) {
1984             while (pos < 1023 && index < d->size) {
1985                 if (d->data()[index] == cc)
1986                     indices[pos++] = index;
1987                 index++;
1988             }
1989         } else {
1990             while (pos < 1023 && index < d->size) {
1991                 if (QChar::toCaseFolded(d->data()[index]) == cc)
1992                     indices[pos++] = index;
1993                 index++;
1994             }
1995         }
1996         if (!pos)
1997             break;
1998
1999         replace_helper(indices, pos, 1, after.constData(), after.d->size);
2000
2001         if (index == -1)
2002             break;
2003         // index has to be adjusted in case we get back into the loop above.
2004         index += pos*(after.d->size - 1);
2005     }
2006     return *this;
2007 }
2008
2009 /*!
2010   \overload replace()
2011   Replaces every occurrence of the character \a before with the
2012   character \a after and returns a reference to this string.
2013
2014   If \a cs is Qt::CaseSensitive (default), the search is case
2015   sensitive; otherwise the search is case insensitive.
2016 */
2017 QString& QString::replace(QChar before, QChar after, Qt::CaseSensitivity cs)
2018 {
2019     ushort a = after.unicode();
2020     ushort b = before.unicode();
2021     if (d->size) {
2022         detach();
2023         ushort *i = d->data();
2024         const ushort *e = i + d->size;
2025         if (cs == Qt::CaseSensitive) {
2026             for (; i != e; ++i)
2027                 if (*i == b)
2028                     *i = a;
2029         } else {
2030             b = foldCase(b);
2031             for (; i != e; ++i)
2032                 if (foldCase(*i) == b)
2033                     *i = a;
2034         }
2035     }
2036     return *this;
2037 }
2038
2039 /*!
2040   \since 4.5
2041   \overload replace()
2042
2043   Replaces every occurrence of the string \a before with the string \a
2044   after and returns a reference to this string.
2045
2046   If \a cs is Qt::CaseSensitive (default), the search is case
2047   sensitive; otherwise the search is case insensitive.
2048
2049   \note The text is not rescanned after a replacement.
2050 */
2051 QString &QString::replace(const QLatin1String &before,
2052                           const QLatin1String &after,
2053                           Qt::CaseSensitivity cs)
2054 {
2055     int alen = after.size();
2056     QVarLengthArray<ushort> a(alen);
2057     for (int i = 0; i < alen; ++i)
2058         a[i] = (uchar)after.latin1()[i];
2059     int blen = before.size();
2060     QVarLengthArray<ushort> b(blen);
2061     for (int i = 0; i < blen; ++i)
2062         b[i] = (uchar)before.latin1()[i];
2063     return replace((const QChar *)b.data(), blen, (const QChar *)a.data(), alen, cs);
2064 }
2065
2066 /*!
2067   \since 4.5
2068   \overload replace()
2069
2070   Replaces every occurrence of the string \a before with the string \a
2071   after and returns a reference to this string.
2072
2073   If \a cs is Qt::CaseSensitive (default), the search is case
2074   sensitive; otherwise the search is case insensitive.
2075
2076   \note The text is not rescanned after a replacement.
2077 */
2078 QString &QString::replace(const QLatin1String &before,
2079                           const QString &after,
2080                           Qt::CaseSensitivity cs)
2081 {
2082     int blen = before.size();
2083     QVarLengthArray<ushort> b(blen);
2084     for (int i = 0; i < blen; ++i)
2085         b[i] = (uchar)before.latin1()[i];
2086     return replace((const QChar *)b.data(), blen, after.constData(), after.d->size, cs);
2087 }
2088
2089 /*!
2090   \since 4.5
2091   \overload replace()
2092
2093   Replaces every occurrence of the string \a before with the string \a
2094   after and returns a reference to this string.
2095
2096   If \a cs is Qt::CaseSensitive (default), the search is case
2097   sensitive; otherwise the search is case insensitive.
2098
2099   \note The text is not rescanned after a replacement.
2100 */
2101 QString &QString::replace(const QString &before,
2102                           const QLatin1String &after,
2103                           Qt::CaseSensitivity cs)
2104 {
2105     int alen = after.size();
2106     QVarLengthArray<ushort> a(alen);
2107     for (int i = 0; i < alen; ++i)
2108         a[i] = (uchar)after.latin1()[i];
2109     return replace(before.constData(), before.d->size, (const QChar *)a.data(), alen, cs);
2110 }
2111
2112 /*!
2113   \since 4.5
2114   \overload replace()
2115
2116   Replaces every occurrence of the character \a c with the string \a
2117   after and returns a reference to this string.
2118
2119   If \a cs is Qt::CaseSensitive (default), the search is case
2120   sensitive; otherwise the search is case insensitive.
2121
2122   \note The text is not rescanned after a replacement.
2123 */
2124 QString &QString::replace(QChar c, const QLatin1String &after, Qt::CaseSensitivity cs)
2125 {
2126     int alen = after.size();
2127     QVarLengthArray<ushort> a(alen);
2128     for (int i = 0; i < alen; ++i)
2129         a[i] = (uchar)after.latin1()[i];
2130     return replace(&c, 1, (const QChar *)a.data(), alen, cs);
2131 }
2132
2133
2134 /*!
2135   \relates QString
2136   Returns true if string \a s1 is equal to string \a s2; otherwise
2137   returns false.
2138
2139   The comparison is based exclusively on the numeric Unicode values of
2140   the characters and is very fast, but is not what a human would
2141   expect. Consider sorting user-interface strings with
2142   localeAwareCompare().
2143 */
2144 bool operator==(const QString &s1, const QString &s2)
2145 {
2146     if (s1.d->size != s2.d->size)
2147         return false;
2148
2149     return qMemEquals(s1.d->data(), s2.d->data(), s1.d->size);
2150 }
2151
2152 /*!
2153     \overload operator==()
2154 */
2155 bool QString::operator==(const QLatin1String &other) const
2156 {
2157     if (d->size != other.size())
2158         return false;
2159
2160     if (!other.size())
2161         return isEmpty();
2162
2163     const ushort *uc = d->data();
2164     const ushort *e = uc + d->size;
2165     const uchar *c = (uchar *)other.latin1();
2166
2167     while (uc < e) {
2168         if (*uc != *c)
2169             return false;
2170         ++uc;
2171         ++c;
2172     }
2173     return true;
2174 }
2175
2176 /*! \fn bool QString::operator==(const QByteArray &other) const
2177
2178     \overload operator==()
2179
2180     The \a other byte array is converted to a QString using the
2181     fromAscii() function. This function stops conversion at the
2182     first NUL character found, or the end of the byte array.
2183
2184     You can disable this operator by defining \c
2185     QT_NO_CAST_FROM_ASCII when you compile your applications. This
2186     can be useful if you want to ensure that all user-visible strings
2187     go through QObject::tr(), for example.
2188 */
2189
2190 /*! \fn bool QString::operator==(const char *other) const
2191
2192     \overload operator==()
2193
2194     The \a other const char pointer is converted to a QString using
2195     the fromAscii() function.
2196
2197     You can disable this operator by defining \c
2198     QT_NO_CAST_FROM_ASCII when you compile your applications. This
2199     can be useful if you want to ensure that all user-visible strings
2200     go through QObject::tr(), for example.
2201 */
2202
2203 /*!
2204    \relates QString
2205     Returns true if string \a s1 is lexically less than string
2206     \a s2; otherwise returns false.
2207
2208     The comparison is based exclusively on the numeric Unicode values
2209     of the characters and is very fast, but is not what a human would
2210     expect. Consider sorting user-interface strings using the
2211     QString::localeAwareCompare() function.
2212 */
2213 bool operator<(const QString &s1, const QString &s2)
2214 {
2215     return ucstrcmp(s1.constData(), s1.length(), s2.constData(), s2.length()) < 0;
2216 }
2217
2218 /*!
2219     \overload operator<()
2220 */
2221 bool QString::operator<(const QLatin1String &other) const
2222 {
2223     const uchar *c = (uchar *) other.latin1();
2224     if (!c || *c == 0)
2225         return false;
2226
2227     const ushort *uc = d->data();
2228     const ushort *e = uc + qMin(d->size, other.size());
2229
2230     while (uc < e) {
2231         if (*uc != *c)
2232             break;
2233         ++uc;
2234         ++c;
2235     }
2236     return (uc == e ? d->size < other.size() : *uc < *c);
2237 }
2238
2239 /*! \fn bool QString::operator<(const QByteArray &other) const
2240
2241     \overload operator<()
2242
2243     The \a other byte array is converted to a QString using the
2244     fromAscii() function. If any NUL characters ('\0') are embedded
2245     in the byte array, they will be included in the transformation.
2246
2247     You can disable this operator by defining \c
2248     QT_NO_CAST_FROM_ASCII when you compile your applications. This
2249     can be useful if you want to ensure that all user-visible strings
2250     go through QObject::tr(), for example.
2251 */
2252
2253 /*! \fn bool QString::operator<(const char *other) const
2254
2255     \overload operator<()
2256
2257     The \a other const char pointer is converted to a QString using
2258     the fromAscii() function.
2259
2260     You can disable this operator by defining \c
2261     QT_NO_CAST_FROM_ASCII when you compile your applications. This
2262     can be useful if you want to ensure that all user-visible strings
2263     go through QObject::tr(), for example.
2264 */
2265
2266 /*! \fn bool operator<=(const QString &s1, const QString &s2)
2267     \relates QString
2268
2269     Returns true if string \a s1 is lexically less than or equal to
2270     string \a s2; otherwise returns false.
2271
2272     The comparison is based exclusively on the numeric Unicode values
2273     of the characters and is very fast, but is not what a human would
2274     expect. Consider sorting user-interface strings with
2275     localeAwareCompare().
2276 */
2277
2278 /*! \fn bool QString::operator<=(const QLatin1String &other) const
2279
2280     \overload operator<=()
2281 */
2282
2283 /*! \fn bool QString::operator<=(const QByteArray &other) const
2284
2285     \overload operator<=()
2286
2287     The \a other byte array is converted to a QString using the
2288     fromAscii() function. If any NUL characters ('\0') are embedded
2289     in the byte array, they will be included in the transformation.
2290
2291     You can disable this operator by defining \c
2292     QT_NO_CAST_FROM_ASCII when you compile your applications. This
2293     can be useful if you want to ensure that all user-visible strings
2294     go through QObject::tr(), for example.
2295 */
2296
2297 /*! \fn bool QString::operator<=(const char *other) const
2298
2299     \overload operator<=()
2300
2301     The \a other const char pointer is converted to a QString using
2302     the fromAscii() function.
2303
2304     You can disable this operator by defining \c
2305     QT_NO_CAST_FROM_ASCII when you compile your applications. This
2306     can be useful if you want to ensure that all user-visible strings
2307     go through QObject::tr(), for example.
2308 */
2309
2310 /*! \fn bool operator>(const QString &s1, const QString &s2)
2311     \relates QString
2312
2313     Returns true if string \a s1 is lexically greater than string \a
2314     s2; otherwise returns false.
2315
2316     The comparison is based exclusively on the numeric Unicode values
2317     of the characters and is very fast, but is not what a human would
2318     expect. Consider sorting user-interface strings with
2319     localeAwareCompare().
2320 */
2321
2322 /*!
2323     \overload operator>()
2324 */
2325 bool QString::operator>(const QLatin1String &other) const
2326 {
2327     const uchar *c = (uchar *) other.latin1();
2328     if (!c || *c == '\0')
2329         return !isEmpty();
2330
2331     const ushort *uc = d->data();
2332     const ushort *e = uc + qMin(d->size, other.size());
2333
2334     while (uc < e) {
2335         if (*uc != *c)
2336             break;
2337         ++uc;
2338         ++c;
2339     }
2340     return (uc == e) ? d->size > other.size() : *uc > *c;
2341 }
2342
2343 /*! \fn bool QString::operator>(const QByteArray &other) const
2344
2345     \overload operator>()
2346
2347     The \a other byte array is converted to a QString using the
2348     fromAscii() function. If any NUL characters ('\0') are embedded
2349     in the byte array, they will be included in the transformation.
2350
2351     You can disable this operator by defining \c
2352     QT_NO_CAST_FROM_ASCII when you compile your applications. This
2353     can be useful if you want to ensure that all user-visible strings
2354     go through QObject::tr(), for example.
2355 */
2356
2357 /*! \fn bool QString::operator>(const char *other) const
2358
2359     \overload operator>()
2360
2361     The \a other const char pointer is converted to a QString using
2362     the fromAscii() function.
2363
2364     You can disable this operator by defining \c QT_NO_CAST_FROM_ASCII
2365     when you compile your applications. This can be useful if you want
2366     to ensure that all user-visible strings go through QObject::tr(),
2367     for example.
2368 */
2369
2370 /*! \fn bool operator>=(const QString &s1, const QString &s2)
2371     \relates QString
2372
2373     Returns true if string \a s1 is lexically greater than or equal to
2374     string \a s2; otherwise returns false.
2375
2376     The comparison is based exclusively on the numeric Unicode values
2377     of the characters and is very fast, but is not what a human would
2378     expect. Consider sorting user-interface strings with
2379     localeAwareCompare().
2380 */
2381
2382 /*! \fn bool QString::operator>=(const QLatin1String &other) const
2383
2384     \overload operator>=()
2385 */
2386
2387 /*! \fn bool QString::operator>=(const QByteArray &other) const
2388
2389     \overload operator>=()
2390
2391     The \a other byte array is converted to a QString using the
2392     fromAscii() function. If any NUL characters ('\0') are embedded in
2393     the byte array, they will be included in the transformation.
2394
2395     You can disable this operator by defining \c QT_NO_CAST_FROM_ASCII
2396     when you compile your applications. This can be useful if you want
2397     to ensure that all user-visible strings go through QObject::tr(),
2398     for example.
2399 */
2400
2401 /*! \fn bool QString::operator>=(const char *other) const
2402
2403     \overload operator>=()
2404
2405     The \a other const char pointer is converted to a QString using
2406     the fromAscii() function.
2407
2408     You can disable this operator by defining \c QT_NO_CAST_FROM_ASCII
2409     when you compile your applications. This can be useful if you want
2410     to ensure that all user-visible strings go through QObject::tr(),
2411     for example.
2412 */
2413
2414 /*! \fn bool operator!=(const QString &s1, const QString &s2)
2415     \relates QString
2416
2417     Returns true if string \a s1 is not equal to string \a s2;
2418     otherwise returns false.
2419
2420     The comparison is based exclusively on the numeric Unicode values
2421     of the characters and is very fast, but is not what a human would
2422     expect. Consider sorting user-interface strings with
2423     localeAwareCompare().
2424 */
2425
2426 /*! \fn bool QString::operator!=(const QLatin1String &other) const
2427
2428     \overload operator!=()
2429 */
2430
2431 /*! \fn bool QString::operator!=(const QByteArray &other) const
2432
2433     \overload operator!=()
2434
2435     The \a other byte array is converted to a QString using the
2436     fromAscii() function. If any NUL characters ('\0') are embedded
2437     in the byte array, they will be included in the transformation.
2438
2439     You can disable this operator by defining \c QT_NO_CAST_FROM_ASCII
2440     when you compile your applications. This can be useful if you want
2441     to ensure that all user-visible strings go through QObject::tr(),
2442     for example.
2443 */
2444
2445 /*! \fn bool QString::operator!=(const char *other) const
2446
2447     \overload operator!=()
2448
2449     The \a other const char pointer is converted to a QString using
2450     the fromAscii() function.
2451
2452     You can disable this operator by defining \c
2453     QT_NO_CAST_FROM_ASCII when you compile your applications. This
2454     can be useful if you want to ensure that all user-visible strings
2455     go through QObject::tr(), for example.
2456 */
2457
2458 /*!
2459   Returns the index position of the first occurrence of the string \a
2460   str in this string, searching forward from index position \a
2461   from. Returns -1 if \a str is not found.
2462
2463   If \a cs is Qt::CaseSensitive (default), the search is case
2464   sensitive; otherwise the search is case insensitive.
2465
2466   Example:
2467
2468   \snippet doc/src/snippets/qstring/main.cpp 24
2469
2470   If \a from is -1, the search starts at the last character; if it is
2471   -2, at the next to last character and so on.
2472
2473   \sa lastIndexOf(), contains(), count()
2474 */
2475 int QString::indexOf(const QString &str, int from, Qt::CaseSensitivity cs) const
2476 {
2477     return qFindString(unicode(), length(), from, str.unicode(), str.length(), cs);
2478 }
2479
2480 /*!
2481   \since 4.5
2482   Returns the index position of the first occurrence of the string \a
2483   str in this string, searching forward from index position \a
2484   from. Returns -1 if \a str is not found.
2485
2486   If \a cs is Qt::CaseSensitive (default), the search is case
2487   sensitive; otherwise the search is case insensitive.
2488
2489   Example:
2490
2491   \snippet doc/src/snippets/qstring/main.cpp 24
2492
2493   If \a from is -1, the search starts at the last character; if it is
2494   -2, at the next to last character and so on.
2495
2496   \sa lastIndexOf(), contains(), count()
2497 */
2498
2499 int QString::indexOf(const QLatin1String &str, int from, Qt::CaseSensitivity cs) const
2500 {
2501     return qt_find_latin1_string(unicode(), size(), str, from, cs);
2502 }
2503
2504 int qFindString(
2505     const QChar *haystack0, int haystackLen, int from,
2506     const QChar *needle0, int needleLen, Qt::CaseSensitivity cs)
2507 {
2508     const int l = haystackLen;
2509     const int sl = needleLen;
2510     if (from < 0)
2511         from += l;
2512     if (uint(sl + from) > (uint)l)
2513         return -1;
2514     if (!sl)
2515         return from;
2516     if (!l)
2517         return -1;
2518
2519     if (sl == 1)
2520         return findChar(haystack0, haystackLen, needle0[0], from, cs);
2521
2522     /*
2523         We use the Boyer-Moore algorithm in cases where the overhead
2524         for the skip table should pay off, otherwise we use a simple
2525         hash function.
2526     */
2527     if (l > 500 && sl > 5)
2528         return qFindStringBoyerMoore(haystack0, haystackLen, from,
2529             needle0, needleLen, cs);
2530
2531     /*
2532         We use some hashing for efficiency's sake. Instead of
2533         comparing strings, we compare the hash value of str with that
2534         of a part of this QString. Only if that matches, we call
2535         ucstrncmp() or ucstrnicmp().
2536     */
2537     const ushort *needle = (const ushort *)needle0;
2538     const ushort *haystack = (const ushort *)haystack0 + from;
2539     const ushort *end = (const ushort *)haystack0 + (l-sl);
2540     const int sl_minus_1 = sl-1;
2541     int hashNeedle = 0, hashHaystack = 0, idx;
2542
2543     if (cs == Qt::CaseSensitive) {
2544         for (idx = 0; idx < sl; ++idx) {
2545             hashNeedle = ((hashNeedle<<1) + needle[idx]);
2546             hashHaystack = ((hashHaystack<<1) + haystack[idx]);
2547         }
2548         hashHaystack -= haystack[sl_minus_1];
2549
2550         while (haystack <= end) {
2551             hashHaystack += haystack[sl_minus_1];
2552             if (hashHaystack == hashNeedle
2553                  && ucstrncmp((const QChar *)needle, (const QChar *)haystack, sl) == 0)
2554                 return haystack - (const ushort *)haystack0;
2555
2556             REHASH(*haystack);
2557             ++haystack;
2558         }
2559     } else {
2560         const ushort *haystack_start = (const ushort *)haystack0;
2561         for (idx = 0; idx < sl; ++idx) {
2562             hashNeedle = (hashNeedle<<1) + foldCase(needle + idx, needle);
2563             hashHaystack = (hashHaystack<<1) + foldCase(haystack + idx, haystack_start);
2564         }
2565         hashHaystack -= foldCase(haystack + sl_minus_1, haystack_start);
2566
2567         while (haystack <= end) {
2568             hashHaystack += foldCase(haystack + sl_minus_1, haystack_start);
2569             if (hashHaystack == hashNeedle && ucstrnicmp(needle, haystack, sl) == 0)
2570                 return haystack - (const ushort *)haystack0;
2571
2572             REHASH(foldCase(haystack, haystack_start));
2573             ++haystack;
2574         }
2575     }
2576     return -1;
2577 }
2578
2579 /*!
2580     \overload indexOf()
2581
2582     Returns the index position of the first occurrence of the
2583     character \a ch in the string, searching forward from index
2584     position \a from. Returns -1 if \a ch could not be found.
2585 */
2586 int QString::indexOf(QChar ch, int from, Qt::CaseSensitivity cs) const
2587 {
2588     return findChar(unicode(), length(), ch, from, cs);
2589 }
2590
2591 /*!
2592     \since 4.8
2593
2594     \overload indexOf()
2595
2596     Returns the index position of the first occurrence of the string
2597     reference \a str in this string, searching forward from index
2598     position \a from. Returns -1 if \a str is not found.
2599
2600     If \a cs is Qt::CaseSensitive (default), the search is case
2601     sensitive; otherwise the search is case insensitive.
2602 */
2603 int QString::indexOf(const QStringRef &str, int from, Qt::CaseSensitivity cs) const
2604 {
2605     return qFindString(unicode(), length(), from, str.unicode(), str.length(), cs);
2606 }
2607
2608 static int lastIndexOfHelper(const ushort *haystack, int from, const ushort *needle, int sl, Qt::CaseSensitivity cs)
2609 {
2610     /*
2611         See indexOf() for explanations.
2612     */
2613
2614     const ushort *end = haystack;
2615     haystack += from;
2616     const int sl_minus_1 = sl-1;
2617     const ushort *n = needle+sl_minus_1;
2618     const ushort *h = haystack+sl_minus_1;
2619     int hashNeedle = 0, hashHaystack = 0, idx;
2620
2621     if (cs == Qt::CaseSensitive) {
2622         for (idx = 0; idx < sl; ++idx) {
2623             hashNeedle = ((hashNeedle<<1) + *(n-idx));
2624             hashHaystack = ((hashHaystack<<1) + *(h-idx));
2625         }
2626         hashHaystack -= *haystack;
2627
2628         while (haystack >= end) {
2629             hashHaystack += *haystack;
2630             if (hashHaystack == hashNeedle
2631                  && ucstrncmp((const QChar *)needle, (const QChar *)haystack, sl) == 0)
2632                 return haystack - end;
2633             --haystack;
2634             REHASH(haystack[sl]);
2635         }
2636     } else {
2637         for (idx = 0; idx < sl; ++idx) {
2638             hashNeedle = ((hashNeedle<<1) + foldCase(n-idx, needle));
2639             hashHaystack = ((hashHaystack<<1) + foldCase(h-idx, end));
2640         }
2641         hashHaystack -= foldCase(haystack, end);
2642
2643         while (haystack >= end) {
2644             hashHaystack += foldCase(haystack, end);
2645             if (hashHaystack == hashNeedle && ucstrnicmp(needle, haystack, sl) == 0)
2646                 return haystack - end;
2647             --haystack;
2648             REHASH(foldCase(haystack + sl, end));
2649         }
2650     }
2651     return -1;
2652 }
2653
2654 /*!
2655   Returns the index position of the last occurrence of the string \a
2656   str in this string, searching backward from index position \a
2657   from. If \a from is -1 (default), the search starts at the last
2658   character; if \a from is -2, at the next to last character and so
2659   on. Returns -1 if \a str is not found.
2660
2661   If \a cs is Qt::CaseSensitive (default), the search is case
2662   sensitive; otherwise the search is case insensitive.
2663
2664   Example:
2665
2666   \snippet doc/src/snippets/qstring/main.cpp 29
2667
2668   \sa indexOf(), contains(), count()
2669 */
2670 int QString::lastIndexOf(const QString &str, int from, Qt::CaseSensitivity cs) const
2671 {
2672     const int sl = str.d->size;
2673     if (sl == 1)
2674         return lastIndexOf(QChar(str.d->data()[0]), from, cs);
2675
2676     const int l = d->size;
2677     if (from < 0)
2678         from += l;
2679     int delta = l-sl;
2680     if (from == l && sl == 0)
2681         return from;
2682     if (from < 0 || from >= l || delta < 0)
2683         return -1;
2684     if (from > delta)
2685         from = delta;
2686
2687     return lastIndexOfHelper(d->data(), from, str.d->data(), str.d->size, cs);
2688 }
2689
2690 /*!
2691   \since 4.5
2692   \overload lastIndexOf()
2693
2694   Returns the index position of the last occurrence of the string \a
2695   str in this string, searching backward from index position \a
2696   from. If \a from is -1 (default), the search starts at the last
2697   character; if \a from is -2, at the next to last character and so
2698   on. Returns -1 if \a str is not found.
2699
2700   If \a cs is Qt::CaseSensitive (default), the search is case
2701   sensitive; otherwise the search is case insensitive.
2702
2703   Example:
2704
2705   \snippet doc/src/snippets/qstring/main.cpp 29
2706
2707   \sa indexOf(), contains(), count()
2708 */
2709 int QString::lastIndexOf(const QLatin1String &str, int from, Qt::CaseSensitivity cs) const
2710 {
2711     const int sl = str.size();
2712     if (sl == 1)
2713         return lastIndexOf(QLatin1Char(str.latin1()[0]), from, cs);
2714
2715     const int l = d->size;
2716     if (from < 0)
2717         from += l;
2718     int delta = l-sl;
2719     if (from == l && sl == 0)
2720         return from;
2721     if (from < 0 || from >= l || delta < 0)
2722         return -1;
2723     if (from > delta)
2724         from = delta;
2725
2726     QVarLengthArray<ushort> s(sl);
2727     for (int i = 0; i < sl; ++i)
2728         s[i] = str.latin1()[i];
2729
2730     return lastIndexOfHelper(d->data(), from, s.data(), sl, cs);
2731 }
2732
2733 /*!
2734   \overload lastIndexOf()
2735
2736   Returns the index position of the last occurrence of the character
2737   \a ch, searching backward from position \a from.
2738 */
2739 int QString::lastIndexOf(QChar ch, int from, Qt::CaseSensitivity cs) const
2740 {
2741     return qt_last_index_of(unicode(), size(), ch, from, cs);
2742 }
2743
2744 /*!
2745   \since 4.8
2746   \overload lastIndexOf()
2747
2748   Returns the index position of the last occurrence of the string
2749   reference \a str in this string, searching backward from index
2750   position \a from. If \a from is -1 (default), the search starts at
2751   the last character; if \a from is -2, at the next to last character
2752   and so on. Returns -1 if \a str is not found.
2753
2754   If \a cs is Qt::CaseSensitive (default), the search is case
2755   sensitive; otherwise the search is case insensitive.
2756
2757   \sa indexOf(), contains(), count()
2758 */
2759 int QString::lastIndexOf(const QStringRef &str, int from, Qt::CaseSensitivity cs) const
2760 {
2761     const int sl = str.size();
2762     if (sl == 1)
2763         return lastIndexOf(str.at(0), from, cs);
2764
2765     const int l = d->size;
2766     if (from < 0)
2767         from += l;
2768     int delta = l - sl;
2769     if (from == l && sl == 0)
2770         return from;
2771     if (from < 0 || from >= l || delta < 0)
2772     return -1;
2773     if (from > delta)
2774         from = delta;
2775
2776     return lastIndexOfHelper(d->data(), from, reinterpret_cast<const ushort*>(str.unicode()),
2777                              str.size(), cs);
2778 }
2779
2780 #ifndef QT_NO_REGEXP
2781 struct QStringCapture
2782 {
2783     int pos;
2784     int len;
2785     int no;
2786 };
2787
2788 /*!
2789   \overload replace()
2790
2791   Replaces every occurrence of the regular expression \a rx in the
2792   string with \a after. Returns a reference to the string. For
2793   example:
2794
2795   \snippet doc/src/snippets/qstring/main.cpp 42
2796
2797   For regular expressions containing \l{capturing parentheses},
2798   occurrences of \b{\\1}, \b{\\2}, ..., in \a after are replaced
2799   with \a{rx}.cap(1), cap(2), ...
2800
2801   \snippet doc/src/snippets/qstring/main.cpp 43
2802
2803   \sa indexOf(), lastIndexOf(), remove(), QRegExp::cap()
2804 */
2805 QString& QString::replace(const QRegExp &rx, const QString &after)
2806 {
2807     QRegExp rx2(rx);
2808
2809     if (isEmpty() && rx2.indexIn(*this) == -1)
2810         return *this;
2811
2812     reallocData(d->size);
2813
2814     int index = 0;
2815     int numCaptures = rx2.captureCount();
2816     int al = after.length();
2817     QRegExp::CaretMode caretMode = QRegExp::CaretAtZero;
2818
2819     if (numCaptures > 0) {
2820         const QChar *uc = after.unicode();
2821         int numBackRefs = 0;
2822
2823         for (int i = 0; i < al - 1; i++) {
2824             if (uc[i] == QLatin1Char('\\')) {
2825                 int no = uc[i + 1].digitValue();
2826                 if (no > 0 && no <= numCaptures)
2827                     numBackRefs++;
2828             }
2829         }
2830
2831         /*
2832             This is the harder case where we have back-references.
2833         */
2834         if (numBackRefs > 0) {
2835             QVarLengthArray<QStringCapture, 16> captures(numBackRefs);
2836             int j = 0;
2837
2838             for (int i = 0; i < al - 1; i++) {
2839                 if (uc[i] == QLatin1Char('\\')) {
2840                     int no = uc[i + 1].digitValue();
2841                     if (no > 0 && no <= numCaptures) {
2842                         QStringCapture capture;
2843                         capture.pos = i;
2844                         capture.len = 2;
2845
2846                         if (i < al - 2) {
2847                             int secondDigit = uc[i + 2].digitValue();
2848                             if (secondDigit != -1 && ((no * 10) + secondDigit) <= numCaptures) {
2849                                 no = (no * 10) + secondDigit;
2850                                 ++capture.len;
2851                             }
2852                         }
2853
2854                         capture.no = no;
2855                         captures[j++] = capture;
2856                     }
2857                 }
2858             }
2859
2860             while (index <= length()) {
2861                 index = rx2.indexIn(*this, index, caretMode);
2862                 if (index == -1)
2863                     break;
2864
2865                 QString after2(after);
2866                 for (j = numBackRefs - 1; j >= 0; j--) {
2867                     const QStringCapture &capture = captures[j];
2868                     after2.replace(capture.pos, capture.len, rx2.cap(capture.no));
2869                 }
2870
2871                 replace(index, rx2.matchedLength(), after2);
2872                 index += after2.length();
2873
2874                 // avoid infinite loop on 0-length matches (e.g., QRegExp("[a-z]*"))
2875                 if (rx2.matchedLength() == 0)
2876                     ++index;
2877
2878                 caretMode = QRegExp::CaretWontMatch;
2879             }
2880             return *this;
2881         }
2882     }
2883
2884     /*
2885         This is the simple and optimized case where we don't have
2886         back-references.
2887     */
2888     while (index != -1) {
2889         struct {
2890             int pos;
2891             int length;
2892         } replacements[2048];
2893
2894         int pos = 0;
2895         int adjust = 0;
2896         while (pos < 2047) {
2897             index = rx2.indexIn(*this, index, caretMode);
2898             if (index == -1)
2899                 break;
2900             int ml = rx2.matchedLength();
2901             replacements[pos].pos = index;
2902             replacements[pos++].length = ml;
2903             index += ml;
2904             adjust += al - ml;
2905             // avoid infinite loop
2906             if (!ml)
2907                 index++;
2908         }
2909         if (!pos)
2910             break;
2911         replacements[pos].pos = d->size;
2912         int newlen = d->size + adjust;
2913
2914         // to continue searching at the right position after we did
2915         // the first round of replacements
2916         if (index != -1)
2917             index += adjust;
2918         QString newstring;
2919         newstring.reserve(newlen + 1);
2920         QChar *newuc = newstring.data();
2921         QChar *uc = newuc;
2922         int copystart = 0;
2923         int i = 0;
2924         while (i < pos) {
2925             int copyend = replacements[i].pos;
2926             int size = copyend - copystart;
2927             memcpy(uc, d->data() + copystart, size * sizeof(QChar));
2928             uc += size;
2929             memcpy(uc, after.d->data(), al * sizeof(QChar));
2930             uc += al;
2931             copystart = copyend + replacements[i].length;
2932             i++;
2933         }
2934         memcpy(uc, d->data() + copystart, (d->size - copystart) * sizeof(QChar));
2935         newstring.resize(newlen);
2936         *this = newstring;
2937         caretMode = QRegExp::CaretWontMatch;
2938     }
2939     return *this;
2940 }
2941 #endif
2942
2943 #ifndef QT_NO_REGEXP
2944 #ifndef QT_BOOTSTRAPPED
2945 /*!
2946   \overload replace()
2947   \since 5.0
2948
2949   Replaces every occurrence of the regular expression \a re in the
2950   string with \a after. Returns a reference to the string. For
2951   example:
2952
2953   \snippet doc/src/snippets/qstring/main.cpp 87
2954
2955   For regular expressions containing capturing groups,
2956   occurrences of \bold{\\1}, \bold{\\2}, ..., in \a after are replaced
2957   with the string captured by the corresponding capturing group.
2958
2959   \snippet doc/src/snippets/qstring/main.cpp 88
2960
2961   \sa indexOf(), lastIndexOf(), remove(), QRegularExpression, QRegularExpressionMatch
2962 */
2963 QString &QString::replace(const QRegularExpression &re, const QString &after)
2964 {
2965     if (!re.isValid()) {
2966         qWarning("QString::replace: invalid QRegularExpresssion object");
2967         return *this;
2968     }
2969
2970     const QString copy(*this);
2971     QRegularExpressionMatchIterator iterator = re.globalMatch(copy);
2972     if (!iterator.hasNext()) // no matches at all
2973         return *this;
2974
2975     reallocData(d->size);
2976
2977     int numCaptures = re.captureCount();
2978
2979     // 1. build the backreferences vector, holding where the backreferences
2980     // are in the replacement string
2981     QVector<QStringCapture> backReferences;
2982     const int al = after.length();
2983     const QChar *ac = after.unicode();
2984
2985     for (int i = 0; i < al - 1; i++) {
2986         if (ac[i] == QLatin1Char('\\')) {
2987             int no = ac[i + 1].digitValue();
2988             if (no > 0 && no <= numCaptures) {
2989                 QStringCapture backReference;
2990                 backReference.pos = i;
2991                 backReference.len = 2;
2992
2993                 if (i < al - 2) {
2994                     int secondDigit = ac[i + 2].digitValue();
2995                     if (secondDigit != -1 && ((no * 10) + secondDigit) <= numCaptures) {
2996                         no = (no * 10) + secondDigit;
2997                         ++backReference.len;
2998                     }
2999                 }
3000
3001                 backReference.no = no;
3002                 backReferences.append(backReference);
3003             }
3004         }
3005     }
3006
3007     // 2. iterate on the matches. For every match, copy in chunks
3008     // - the part before the match
3009     // - the after string, with the proper replacements for the backreferences
3010
3011     int newLength = 0; // length of the new string, with all the replacements
3012     int lastEnd = 0;
3013     QVector<QStringRef> chunks;
3014     while (iterator.hasNext()) {
3015         QRegularExpressionMatch match = iterator.next();
3016         int len;
3017         // add the part before the match
3018         len = match.capturedStart() - lastEnd;
3019         if (len > 0) {
3020             chunks << copy.midRef(lastEnd, len);
3021             newLength += len;
3022         }
3023
3024         lastEnd = 0;
3025         // add the after string, with replacements for the backreferences
3026         foreach (const QStringCapture &backReference, backReferences) {
3027             // part of "after" before the backreference
3028             len = backReference.pos - lastEnd;
3029             if (len > 0) {
3030                 chunks << after.midRef(lastEnd, len);
3031                 newLength += len;
3032             }
3033
3034             // backreference itself
3035             len = match.capturedLength(backReference.no);
3036             if (len > 0) {
3037                 chunks << copy.midRef(match.capturedStart(backReference.no), len);
3038                 newLength += len;
3039             }
3040
3041             lastEnd = backReference.pos + backReference.len;
3042         }
3043
3044         // add the last part of the after string
3045         len = after.length() - lastEnd;
3046         if (len > 0) {
3047             chunks << after.midRef(lastEnd, len);
3048             newLength += len;
3049         }
3050
3051         lastEnd = match.capturedEnd();
3052     }
3053
3054     // 3. trailing string after the last match
3055     if (copy.length() > lastEnd) {
3056         chunks << copy.midRef(lastEnd);
3057         newLength += copy.length() - lastEnd;
3058     }
3059
3060     // 4. assemble the chunks together
3061     resize(newLength);
3062     int i = 0;
3063     QChar *uc = data();
3064     foreach (const QStringRef &chunk, chunks) {
3065         int len = chunk.length();
3066         memcpy(uc + i, chunk.unicode(), len * sizeof(QChar));
3067         i += len;
3068     }
3069
3070     return *this;
3071 }
3072 #endif // QT_BOOTSTRAPPED
3073 #endif // QT_NO_REGEXP
3074
3075 /*!
3076     Returns the number of (potentially overlapping) occurrences of
3077     the string \a str in this string.
3078
3079     If \a cs is Qt::CaseSensitive (default), the search is
3080     case sensitive; otherwise the search is case insensitive.
3081
3082     \sa contains(), indexOf()
3083 */
3084
3085 int QString::count(const QString &str, Qt::CaseSensitivity cs) const
3086 {
3087     return qt_string_count(unicode(), size(), str.unicode(), str.size(), cs);
3088 }
3089
3090 /*!
3091   \overload count()
3092
3093   Returns the number of occurrences of character \a ch in the string.
3094 */
3095
3096 int QString::count(QChar ch, Qt::CaseSensitivity cs) const
3097 {
3098     return qt_string_count(unicode(), size(), ch, cs);
3099     }
3100
3101 /*!
3102     \since 4.8
3103     \overload count()
3104     Returns the number of (potentially overlapping) occurrences of the
3105     string reference \a str in this string.
3106
3107     If \a cs is Qt::CaseSensitive (default), the search is
3108     case sensitive; otherwise the search is case insensitive.
3109
3110     \sa contains(), indexOf()
3111 */
3112 int QString::count(const QStringRef &str, Qt::CaseSensitivity cs) const
3113 {
3114     return qt_string_count(unicode(), size(), str.unicode(), str.size(), cs);
3115 }
3116
3117
3118 /*! \fn bool QString::contains(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
3119
3120     Returns true if this string contains an occurrence of the string
3121     \a str; otherwise returns false.
3122
3123     If \a cs is Qt::CaseSensitive (default), the search is
3124     case sensitive; otherwise the search is case insensitive.
3125
3126     Example:
3127     \snippet doc/src/snippets/qstring/main.cpp 17
3128
3129     \sa indexOf(), count()
3130 */
3131
3132 /*! \fn bool QString::contains(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
3133
3134     \overload contains()
3135
3136     Returns true if this string contains an occurrence of the
3137     character \a ch; otherwise returns false.
3138 */
3139
3140 /*! \fn bool QString::contains(const QStringRef &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
3141     \since 4.8
3142
3143     Returns true if this string contains an occurrence of the string
3144     reference \a str; otherwise returns false.
3145
3146     If \a cs is Qt::CaseSensitive (default), the search is
3147     case sensitive; otherwise the search is case insensitive.
3148
3149     \sa indexOf(), count()
3150 */
3151
3152 /*! \fn bool QString::contains(const QRegExp &rx) const
3153
3154     \overload contains()
3155
3156     Returns true if the regular expression \a rx matches somewhere in
3157     this string; otherwise returns false.
3158 */
3159
3160 /*! \fn bool QString::contains(QRegExp &rx) const
3161     \overload contains()
3162     \since 4.5
3163
3164     Returns true if the regular expression \a rx matches somewhere in
3165     this string; otherwise returns false.
3166
3167     If there is a match, the \a rx regular expression will contain the
3168     matched captures (see QRegExp::matchedLength, QRegExp::cap).
3169 */
3170
3171 #ifndef QT_NO_REGEXP
3172 /*!
3173     \overload indexOf()
3174
3175     Returns the index position of the first match of the regular
3176     expression \a rx in the string, searching forward from index
3177     position \a from. Returns -1 if \a rx didn't match anywhere.
3178
3179     Example:
3180
3181     \snippet doc/src/snippets/qstring/main.cpp 25
3182 */
3183 int QString::indexOf(const QRegExp& rx, int from) const
3184 {
3185     QRegExp rx2(rx);
3186     return rx2.indexIn(*this, from);
3187 }
3188
3189 /*!
3190     \overload indexOf()
3191     \since 4.5
3192
3193     Returns the index position of the first match of the regular
3194     expression \a rx in the string, searching forward from index
3195     position \a from. Returns -1 if \a rx didn't match anywhere.
3196
3197     If there is a match, the \a rx regular expression will contain the
3198     matched captures (see QRegExp::matchedLength, QRegExp::cap).
3199
3200     Example:
3201
3202     \snippet doc/src/snippets/qstring/main.cpp 25
3203 */
3204 int QString::indexOf(QRegExp& rx, int from) const
3205 {
3206     return rx.indexIn(*this, from);
3207 }
3208
3209 /*!
3210     \overload lastIndexOf()
3211
3212     Returns the index position of the last match of the regular
3213     expression \a rx in the string, searching backward from index
3214     position \a from. Returns -1 if \a rx didn't match anywhere.
3215
3216     Example:
3217
3218     \snippet doc/src/snippets/qstring/main.cpp 30
3219 */
3220 int QString::lastIndexOf(const QRegExp& rx, int from) const
3221 {
3222     QRegExp rx2(rx);
3223     return rx2.lastIndexIn(*this, from);
3224 }
3225
3226 /*!
3227     \overload lastIndexOf()
3228     \since 4.5
3229
3230     Returns the index position of the last match of the regular
3231     expression \a rx in the string, searching backward from index
3232     position \a from. Returns -1 if \a rx didn't match anywhere.
3233
3234     If there is a match, the \a rx regular expression will contain the
3235     matched captures (see QRegExp::matchedLength, QRegExp::cap).
3236
3237     Example:
3238
3239     \snippet doc/src/snippets/qstring/main.cpp 30
3240 */
3241 int QString::lastIndexOf(QRegExp& rx, int from) const
3242 {
3243     return rx.lastIndexIn(*this, from);
3244 }
3245
3246 /*!
3247     \overload count()
3248
3249     Returns the number of times the regular expression \a rx matches
3250     in the string.
3251
3252     This function counts overlapping matches, so in the example
3253     below, there are four instances of "ana" or "ama":
3254
3255     \snippet doc/src/snippets/qstring/main.cpp 18
3256
3257 */
3258 int QString::count(const QRegExp& rx) const
3259 {
3260     QRegExp rx2(rx);
3261     int count = 0;
3262     int index = -1;
3263     int len = length();
3264     while (index < len - 1) {                 // count overlapping matches
3265         index = rx2.indexIn(*this, index + 1);
3266         if (index == -1)
3267             break;
3268         count++;
3269     }
3270     return count;
3271 }
3272 #endif // QT_NO_REGEXP
3273
3274 #ifndef QT_NO_REGEXP
3275 #ifndef QT_BOOTSTRAPPED
3276 /*!
3277     \overload indexOf()
3278     \since 5.0
3279
3280     Returns the index position of the first match of the regular
3281     expression \a re in the string, searching forward from index
3282     position \a from. Returns -1 if \a re didn't match anywhere.
3283
3284     Example:
3285
3286     \snippet doc/src/snippets/qstring/main.cpp 93
3287 */
3288 int QString::indexOf(const QRegularExpression& re, int from) const
3289 {
3290     if (!re.isValid()) {
3291         qWarning("QString::indexOf: invalid QRegularExpresssion object");
3292         return -1;
3293     }
3294
3295     QRegularExpressionMatch match = re.match(*this, from);
3296     if (match.hasMatch())
3297         return match.capturedStart();
3298
3299     return -1;
3300 }
3301
3302 /*!
3303     \overload lastIndexOf()
3304     \since 5.0
3305
3306     Returns the index position of the last match of the regular
3307     expression \a re in the string, which starts before the index
3308     position \a from. Returns -1 if \a re didn't match anywhere.
3309
3310     Example:
3311
3312     \snippet doc/src/snippets/qstring/main.cpp 94
3313 */
3314 int QString::lastIndexOf(const QRegularExpression &re, int from) const
3315 {
3316     if (!re.isValid()) {
3317         qWarning("QString::lastIndexOf: invalid QRegularExpresssion object");
3318         return -1;
3319     }
3320
3321     int endpos = (from < 0) ? (size() + from + 1) : (from + 1);
3322
3323     QRegularExpressionMatchIterator iterator = re.globalMatch(*this);
3324     int lastIndex = -1;
3325     while (iterator.hasNext()) {
3326         QRegularExpressionMatch match = iterator.next();
3327         int start = match.capturedStart();
3328         if (start < endpos)
3329             lastIndex = start;
3330         else
3331             break;
3332     }
3333
3334     return lastIndex;
3335 }
3336
3337 /*! \overload contains()
3338     \since 5.0
3339
3340     Returns true if the regular expression \a re matches somewhere in
3341     this string; otherwise returns false.
3342 */
3343 bool QString::contains(const QRegularExpression &re) const
3344 {
3345     if (!re.isValid()) {
3346         qWarning("QString::contains: invalid QRegularExpresssion object");
3347         return false;
3348     }
3349     QRegularExpressionMatch match = re.match(*this);
3350     return match.hasMatch();
3351 }
3352
3353 /*!
3354     \overload count()
3355     \since 5.0
3356
3357     Returns the number of times the regular expression \a re matches
3358     in the string.
3359
3360     This function counts overlapping matches, so in the example
3361     below, there are four instances of "ana" or "ama":
3362
3363     \snippet doc/src/snippets/qstring/main.cpp 95
3364 */
3365 int QString::count(const QRegularExpression &re) const
3366 {
3367     if (!re.isValid()) {
3368         qWarning("QString::count: invalid QRegularExpresssion object");
3369         return 0;
3370     }
3371     int count = 0;
3372     int index = -1;
3373     int len = length();
3374     while (index < len - 1) {
3375         QRegularExpressionMatch match = re.match(*this, index + 1);
3376         if (!match.hasMatch())
3377             break;
3378         index = match.capturedStart();
3379         count++;
3380     }
3381     return count;
3382 }
3383 #endif // QT_BOOTSTRAPPED
3384 #endif // QT_NO_REGEXP
3385
3386 /*! \fn int QString::count() const
3387
3388     \overload count()
3389
3390     Same as size().
3391 */
3392
3393
3394 /*!
3395     \enum QString::SectionFlag
3396
3397     This enum specifies flags that can be used to affect various
3398     aspects of the section() function's behavior with respect to
3399     separators and empty fields.
3400
3401     \value SectionDefault Empty fields are counted, leading and
3402     trailing separators are not included, and the separator is
3403     compared case sensitively.
3404
3405     \value SectionSkipEmpty Treat empty fields as if they don't exist,
3406     i.e. they are not considered as far as \e start and \e end are
3407     concerned.
3408
3409     \value SectionIncludeLeadingSep Include the leading separator (if
3410     any) in the result string.
3411
3412     \value SectionIncludeTrailingSep Include the trailing separator
3413     (if any) in the result string.
3414
3415     \value SectionCaseInsensitiveSeps Compare the separator
3416     case-insensitively.
3417
3418     \sa section()
3419 */
3420
3421 /*!
3422     \fn QString QString::section(QChar sep, int start, int end = -1, SectionFlags flags) const
3423
3424     This function returns a section of the string.
3425
3426     This string is treated as a sequence of fields separated by the
3427     character, \a sep. The returned string consists of the fields from
3428     position \a start to position \a end inclusive. If \a end is not
3429     specified, all fields from position \a start to the end of the
3430     string are included. Fields are numbered 0, 1, 2, etc., counting
3431     from the left, and -1, -2, etc., counting from right to left.
3432
3433     The \a flags argument can be used to affect some aspects of the
3434     function's behavior, e.g. whether to be case sensitive, whether
3435     to skip empty fields and how to deal with leading and trailing
3436     separators; see \l{SectionFlags}.
3437
3438     \snippet doc/src/snippets/qstring/main.cpp 52
3439
3440     If \a start or \a end is negative, we count fields from the right
3441     of the string, the right-most field being -1, the one from
3442     right-most field being -2, and so on.
3443
3444     \snippet doc/src/snippets/qstring/main.cpp 53
3445
3446     \sa split()
3447 */
3448
3449 /*!
3450     \overload section()
3451
3452     \snippet doc/src/snippets/qstring/main.cpp 51
3453     \snippet doc/src/snippets/qstring/main.cpp 54
3454
3455     \sa split()
3456 */
3457
3458 QString QString::section(const QString &sep, int start, int end, SectionFlags flags) const
3459 {
3460     QStringList sections = split(sep, KeepEmptyParts,
3461                                  (flags & SectionCaseInsensitiveSeps) ? Qt::CaseInsensitive : Qt::CaseSensitive);
3462     if (sections.isEmpty())
3463         return QString();
3464     if (!(flags & SectionSkipEmpty)) {
3465         if (start < 0)
3466             start += sections.count();
3467         if (end < 0)
3468             end += sections.count();
3469     } else {
3470         int skip = 0;
3471         for (int k=0; k<sections.size(); ++k) {
3472             if (sections.at(k).isEmpty())
3473                 skip++;
3474         }
3475         if (start < 0)
3476             start += sections.count() - skip;
3477         if (end < 0)
3478             end += sections.count() - skip;
3479     }
3480     int x = 0;
3481     QString ret;
3482     int first_i = start, last_i = end;
3483     for (int i = 0; x <= end && i < sections.size(); ++i) {
3484         QString section = sections.at(i);
3485         const bool empty = section.isEmpty();
3486         if (x >= start) {
3487             if(x == start)
3488                 first_i = i;
3489             if(x == end)
3490                 last_i = i;
3491             if(x > start)
3492                 ret += sep;
3493             ret += section;
3494         }
3495         if (!empty || !(flags & SectionSkipEmpty))
3496             x++;
3497     }
3498     if((flags & SectionIncludeLeadingSep) && first_i)
3499         ret.prepend(sep);
3500     if((flags & SectionIncludeTrailingSep) && last_i < sections.size()-1)
3501         ret += sep;
3502     return ret;
3503 }
3504
3505 #ifndef QT_NO_REGEXP
3506 class qt_section_chunk {
3507 public:
3508     qt_section_chunk(int l, QString s) { length = l; string = s; }
3509     int length;
3510     QString string;
3511 };
3512
3513 static QString extractSections(const QList<qt_section_chunk> &sections,
3514                                int start,
3515                                int end,
3516                                QString::SectionFlags flags)
3517 {
3518     if (start < 0)
3519         start += sections.count();
3520     if (end < 0)
3521         end += sections.count();
3522
3523     QString ret;
3524     int x = 0;
3525     int first_i = start, last_i = end;
3526     for (int i = 0; x <= end && i < sections.size(); ++i) {
3527         const qt_section_chunk &section = sections.at(i);
3528         const bool empty = (section.length == section.string.length());
3529         if (x >= start) {
3530             if (x == start)
3531                 first_i = i;
3532             if (x == end)
3533                 last_i = i;
3534             if (x != start)
3535                 ret += section.string;
3536             else
3537                 ret += section.string.mid(section.length);
3538         }
3539         if (!empty || !(flags & QString::SectionSkipEmpty))
3540             x++;
3541     }
3542
3543     if ((flags & QString::SectionIncludeLeadingSep) && first_i < sections.size()) {
3544         const qt_section_chunk &section = sections.at(first_i);
3545         ret.prepend(section.string.left(section.length));
3546     }
3547
3548     if ((flags & QString::SectionIncludeTrailingSep) && last_i+1 <= sections.size()-1) {
3549         const qt_section_chunk &section = sections.at(last_i+1);
3550         ret += section.string.left(section.length);
3551     }
3552
3553     return ret;
3554 }
3555
3556 /*!
3557     \overload section()
3558
3559     This string is treated as a sequence of fields separated by the
3560     regular expression, \a reg.
3561
3562     \snippet doc/src/snippets/qstring/main.cpp 55
3563
3564     \warning Using this QRegExp version is much more expensive than
3565     the overloaded string and character versions.
3566
3567     \sa split() simplified()
3568 */
3569 QString QString::section(const QRegExp &reg, int start, int end, SectionFlags flags) const
3570 {
3571     const QChar *uc = unicode();
3572     if(!uc)
3573         return QString();
3574
3575     QRegExp sep(reg);
3576     sep.setCaseSensitivity((flags & SectionCaseInsensitiveSeps) ? Qt::CaseInsensitive
3577                                                                 : Qt::CaseSensitive);
3578
3579     QList<qt_section_chunk> sections;
3580     int n = length(), m = 0, last_m = 0, last_len = 0;
3581     while ((m = sep.indexIn(*this, m)) != -1) {
3582         sections.append(qt_section_chunk(last_len, QString(uc + last_m, m - last_m)));
3583         last_m = m;
3584         last_len = sep.matchedLength();
3585         m += qMax(sep.matchedLength(), 1);
3586     }
3587     sections.append(qt_section_chunk(last_len, QString(uc + last_m, n - last_m)));
3588
3589     return extractSections(sections, start, end, flags);
3590 }
3591 #endif
3592
3593 #ifndef QT_NO_REGEXP
3594 #ifndef QT_BOOTSTRAPPED
3595 /*!
3596     \overload section()
3597     \since 5.0
3598
3599     This string is treated as a sequence of fields separated by the
3600     regular expression, \a re.
3601
3602     \snippet doc/src/snippets/qstring/main.cpp 89
3603
3604     \warning Using this QRegularExpression version is much more expensive than
3605     the overloaded string and character versions.
3606
3607     \sa split() simplified()
3608 */
3609 QString QString::section(const QRegularExpression &re, int start, int end, SectionFlags flags) const
3610 {
3611     if (!re.isValid()) {
3612         qWarning("QString::section: invalid QRegularExpression object");
3613         return QString();
3614     }
3615
3616     const QChar *uc = unicode();
3617     if (!uc)
3618         return QString();
3619
3620     QRegularExpression sep(re);
3621     if (flags & SectionCaseInsensitiveSeps)
3622         sep.setPatternOptions(sep.patternOptions() | QRegularExpression::CaseInsensitiveOption);
3623
3624     QList<qt_section_chunk> sections;
3625     int n = length(), m = 0, last_m = 0, last_len = 0;
3626     QRegularExpressionMatchIterator iterator = sep.globalMatch(*this);
3627     while (iterator.hasNext()) {
3628         QRegularExpressionMatch match = iterator.next();
3629         m = match.capturedStart();
3630         sections.append(qt_section_chunk(last_len, QString(uc + last_m, m - last_m)));
3631         last_m = m;
3632         last_len = match.capturedLength();
3633     }
3634     sections.append(qt_section_chunk(last_len, QString(uc + last_m, n - last_m)));
3635
3636     return extractSections(sections, start, end, flags);
3637 }
3638 #endif // QT_BOOTSTRAPPED
3639 #endif // QT_NO_REGEXP
3640
3641 /*!
3642     Returns a substring that contains the \a n leftmost characters
3643     of the string.
3644
3645     The entire string is returned if \a n is greater than size() or
3646     less than zero.
3647
3648     \snippet doc/src/snippets/qstring/main.cpp 31
3649
3650     \sa right(), mid(), startsWith()
3651 */
3652 QString QString::left(int n)  const
3653 {
3654     if (n >= d->size || n < 0)
3655         return *this;
3656     return QString((const QChar*) d->data(), n);
3657 }
3658
3659 /*!
3660     Returns a substring that contains the \a n rightmost characters
3661     of the string.
3662
3663     The entire string is returned if \a n is greater than size() or
3664     less than zero.
3665
3666     \snippet doc/src/snippets/qstring/main.cpp 48
3667
3668     \sa left(), mid(), endsWith()
3669 */
3670 QString QString::right(int n) const
3671 {
3672     if (n >= d->size || n < 0)
3673         return *this;
3674     return QString((const QChar*) d->data() + d->size - n, n);
3675 }
3676
3677 /*!
3678     Returns a string that contains \a n characters of this string,
3679     starting at the specified \a position index.
3680
3681     Returns a null string if the \a position index exceeds the
3682     length of the string. If there are less than \a n characters
3683     available in the string starting at the given \a position, or if
3684     \a n is -1 (default), the function returns all characters that
3685     are available from the specified \a position.
3686
3687     Example:
3688
3689     \snippet doc/src/snippets/qstring/main.cpp 34
3690
3691     \sa left(), right()
3692 */
3693
3694 QString QString::mid(int position, int n) const
3695 {
3696     if (position > d->size)
3697         return QString();
3698     if (position < 0) {
3699         if (n < 0 || n + position >= d->size)
3700             return *this;
3701         if (n + position <= 0)
3702             return QString();
3703
3704         n += position;
3705         position = 0;
3706     } else if (n < 0 || n > d->size - position)
3707         n = d->size - position;
3708     if (position == 0 && n == d->size)
3709         return *this;
3710     return QString((const QChar*) d->data() + position, n);
3711 }
3712
3713 /*!
3714     Returns true if the string starts with \a s; otherwise returns
3715     false.
3716
3717     If \a cs is Qt::CaseSensitive (default), the search is
3718     case sensitive; otherwise the search is case insensitive.
3719
3720     \snippet doc/src/snippets/qstring/main.cpp 65
3721
3722     \sa endsWith()
3723 */
3724 bool QString::startsWith(const QString& s, Qt::CaseSensitivity cs) const
3725 {
3726     return qt_starts_with(isNull() ? 0 : unicode(), size(),
3727                           s.isNull() ? 0 : s.unicode(), s.size(), cs);
3728 }
3729
3730 /*!
3731   \overload startsWith()
3732  */
3733 bool QString::startsWith(const QLatin1String& s, Qt::CaseSensitivity cs) const
3734 {
3735     return qt_starts_with(isNull() ? 0 : unicode(), size(), s, cs);
3736 }
3737
3738 /*!
3739   \overload startsWith()
3740
3741   Returns true if the string starts with \a c; otherwise returns
3742   false.
3743 */
3744 bool QString::startsWith(QChar c, Qt::CaseSensitivity cs) const
3745 {
3746     return d->size
3747            && (cs == Qt::CaseSensitive
3748                ? d->data()[0] == c
3749                : foldCase(d->data()[0]) == foldCase(c.unicode()));
3750 }
3751
3752 /*!
3753     \since 4.8
3754     \overload
3755     Returns true if the string starts with the string reference \a s;
3756     otherwise returns false.
3757
3758     If \a cs is Qt::CaseSensitive (default), the search is case
3759     sensitive; otherwise the search is case insensitive.
3760
3761     \sa endsWith()
3762 */
3763 bool QString::startsWith(const QStringRef &s, Qt::CaseSensitivity cs) const
3764 {
3765     return qt_starts_with(isNull() ? 0 : unicode(), size(),
3766                           s.isNull() ? 0 : s.unicode(), s.size(), cs);
3767 }
3768
3769 /*!
3770     Returns true if the string ends with \a s; otherwise returns
3771     false.
3772
3773     If \a cs is Qt::CaseSensitive (default), the search is case
3774     sensitive; otherwise the search is case insensitive.
3775
3776     \snippet doc/src/snippets/qstring/main.cpp 20
3777
3778     \sa startsWith()
3779 */
3780 bool QString::endsWith(const QString& s, Qt::CaseSensitivity cs) const
3781 {
3782     return qt_ends_with(isNull() ? 0 : unicode(), size(),
3783                         s.isNull() ? 0 : s.unicode(), s.size(), cs);
3784     }
3785
3786 /*!
3787     \since 4.8
3788     \overload endsWith()
3789     Returns true if the string ends with the string reference \a s;
3790     otherwise returns false.
3791
3792     If \a cs is Qt::CaseSensitive (default), the search is case
3793     sensitive; otherwise the search is case insensitive.
3794
3795     \sa startsWith()
3796 */
3797 bool QString::endsWith(const QStringRef &s, Qt::CaseSensitivity cs) const
3798 {
3799     return qt_ends_with(isNull() ? 0 : unicode(), size(),
3800                         s.isNull() ? 0 : s.unicode(), s.size(), cs);
3801 }
3802
3803
3804 /*!
3805     \overload endsWith()
3806 */
3807 bool QString::endsWith(const QLatin1String& s, Qt::CaseSensitivity cs) const
3808 {
3809     return qt_ends_with(isNull() ? 0 : unicode(), size(), s, cs);
3810 }
3811
3812 /*!
3813   Returns true if the string ends with \a c; otherwise returns
3814   false.
3815
3816   \overload endsWith()
3817  */
3818 bool QString::endsWith(QChar c, Qt::CaseSensitivity cs) const
3819 {
3820     return d->size
3821            && (cs == Qt::CaseSensitive
3822                ? d->data()[d->size - 1] == c
3823                : foldCase(d->data()[d->size - 1]) == foldCase(c.unicode()));
3824 }
3825
3826
3827 #if defined(QT_ALWAYS_HAVE_SSE2)
3828 static inline __m128i mergeQuestionMarks(__m128i chunk)
3829 {
3830     const __m128i questionMark = _mm_set1_epi16('?');
3831
3832 # ifdef __SSE4_2__
3833     // compare the unsigned shorts for the range 0x0100-0xFFFF
3834     // note on the use of _mm_cmpestrm:
3835     //  The MSDN documentation online (http://technet.microsoft.com/en-us/library/bb514080.aspx)
3836     //  says for range search the following:
3837     //    For each character c in a, determine whether b0 <= c <= b1 or b2 <= c <= b3
3838     //
3839     //  However, all examples on the Internet, including from Intel
3840     //  (see http://software.intel.com/en-us/articles/xml-parsing-accelerator-with-intel-streaming-simd-extensions-4-intel-sse4/)
3841     //  put the range to be searched first
3842     //
3843     //  Disassembly and instruction-level debugging with GCC and ICC show
3844     //  that they are doing the right thing. Inverting the arguments in the
3845     //  instruction does cause a bunch of test failures.
3846
3847     const int mode = _SIDD_UWORD_OPS | _SIDD_CMP_RANGES | _SIDD_UNIT_MASK;
3848     const __m128i rangeMatch = _mm_cvtsi32_si128(0xffff0100);
3849     const __m128i offLimitMask = _mm_cmpestrm(rangeMatch, 2, chunk, 8, mode);
3850
3851     // replace the non-Latin 1 characters in the chunk with question marks
3852     chunk = _mm_blendv_epi8(chunk, questionMark, offLimitMask);
3853 # else
3854     // SSE has no compare instruction for unsigned comparison.
3855     // The variables must be shiffted + 0x8000 to be compared
3856     const __m128i signedBitOffset = _mm_set1_epi16(0x8000);
3857     const __m128i thresholdMask = _mm_set1_epi16(0xff + 0x8000);
3858
3859     const __m128i signedChunk = _mm_add_epi16(chunk, signedBitOffset);
3860     const __m128i offLimitMask = _mm_cmpgt_epi16(signedChunk, thresholdMask);
3861
3862 #  ifdef __SSE4_1__
3863     // replace the non-Latin 1 characters in the chunk with question marks
3864     chunk = _mm_blendv_epi8(chunk, questionMark, offLimitMask);
3865 #  else
3866     // offLimitQuestionMark contains '?' for each 16 bits that was off-limit
3867     // the 16 bits that were correct contains zeros
3868     const __m128i offLimitQuestionMark = _mm_and_si128(offLimitMask, questionMark);
3869
3870     // correctBytes contains the bytes that were in limit
3871     // the 16 bits that were off limits contains zeros
3872     const __m128i correctBytes = _mm_andnot_si128(offLimitMask, chunk);
3873
3874     // merge offLimitQuestionMark and correctBytes to have the result
3875     chunk = _mm_or_si128(correctBytes, offLimitQuestionMark);
3876 #  endif
3877 # endif
3878     return chunk;
3879 }
3880 #endif
3881
3882 static QByteArray toLatin1_helper(const QChar *data, int length)
3883 {
3884     QByteArray ba;
3885     if (length) {
3886         ba.resize(length);
3887         const ushort *src = reinterpret_cast<const ushort *>(data);
3888         uchar *dst = (uchar*) ba.data();
3889 #if defined(QT_ALWAYS_HAVE_SSE2)
3890         if (length >= 16) {
3891             const int chunkCount = length >> 4; // divided by 16
3892
3893             for (int i = 0; i < chunkCount; ++i) {
3894                 __m128i chunk1 = _mm_loadu_si128((__m128i*)src); // load
3895                 chunk1 = mergeQuestionMarks(chunk1);
3896                 src += 8;
3897
3898                 __m128i chunk2 = _mm_loadu_si128((__m128i*)src); // load
3899                 chunk2 = mergeQuestionMarks(chunk2);
3900                 src += 8;
3901
3902                 // pack the two vector to 16 x 8bits elements
3903                 const __m128i result = _mm_packus_epi16(chunk1, chunk2);
3904
3905                 _mm_storeu_si128((__m128i*)dst, result); // store
3906                 dst += 16;
3907             }
3908             length = length % 16;
3909         }
3910 #elif defined(QT_ALWAYS_HAVE_NEON)
3911         // Refer to the documentation of the SSE2 implementation
3912         // this use eactly the same method as for SSE except:
3913         // 1) neon has unsigned comparison
3914         // 2) packing is done to 64 bits (8 x 8bits component).
3915         if (length >= 16) {
3916             const int chunkCount = length >> 3; // divided by 8
3917             const uint16x8_t questionMark = vdupq_n_u16('?'); // set
3918             const uint16x8_t thresholdMask = vdupq_n_u16(0xff); // set
3919             for (int i = 0; i < chunkCount; ++i) {
3920                 uint16x8_t chunk = vld1q_u16((uint16_t *)src); // load
3921                 src += 8;
3922
3923                 const uint16x8_t offLimitMask = vcgtq_u16(chunk, thresholdMask); // chunk > thresholdMask
3924                 const uint16x8_t offLimitQuestionMark = vandq_u16(offLimitMask, questionMark); // offLimitMask & questionMark
3925                 const uint16x8_t correctBytes = vbicq_u16(chunk, offLimitMask); // !offLimitMask & chunk
3926                 chunk = vorrq_u16(correctBytes, offLimitQuestionMark); // correctBytes | offLimitQuestionMark
3927                 const uint8x8_t result = vmovn_u16(chunk); // narrowing move->packing
3928                 vst1_u8(dst, result); // store
3929                 dst += 8;
3930             }
3931             length = length % 8;
3932         }
3933 #endif
3934         while (length--) {
3935             *dst++ = (*src>0xff) ? '?' : (uchar) *src;
3936             ++src;
3937         }
3938     }
3939     return ba;
3940 }
3941
3942 /*!
3943     Returns a Latin-1 representation of the string as a QByteArray.
3944
3945     The returned byte array is undefined if the string contains non-Latin1
3946     characters. Those characters may be suppressed or replaced with a
3947     question mark.
3948
3949     \sa fromLatin1(), toAscii(), toUtf8(), toLocal8Bit(), QTextCodec
3950 */
3951 QByteArray QString::toLatin1() const
3952 {
3953     return toLatin1_helper(unicode(), length());
3954 }
3955
3956 /*!
3957     Returns an 8-bit representation of the string as a QByteArray.
3958
3959     This function does the same as toLatin1().
3960
3961     Note that, despite the name, this function does not necessarily return an US-ASCII
3962     (ANSI X3.4-1986) string and its result may not be US-ASCII compatible.
3963
3964     \sa fromAscii(), toLatin1(), toUtf8(), toLocal8Bit(), QTextCodec
3965 */
3966 QByteArray QString::toAscii() const
3967 {
3968     return toLatin1();
3969 }
3970
3971 #if !defined(Q_OS_MAC) && defined(Q_OS_UNIX)
3972 static QByteArray toLocal8Bit_helper(const QChar *data, int length)
3973 {
3974 #ifndef QT_NO_TEXTCODEC
3975     if (QTextCodec::codecForLocale())
3976         return QTextCodec::codecForLocale()->fromUnicode(data, length);
3977 #endif // QT_NO_TEXTCODEC
3978     return toLatin1_helper(data, length);
3979 }
3980 #endif
3981
3982 /*!
3983     Returns the local 8-bit representation of the string as a
3984     QByteArray. The returned byte array is undefined if the string
3985     contains characters not supported by the local 8-bit encoding.
3986
3987     QTextCodec::codecForLocale() is used to perform the conversion from
3988     Unicode. If the locale encoding could not be determined, this function
3989     does the same as toLatin1().
3990
3991     If this string contains any characters that cannot be encoded in the
3992     locale, the returned byte array is undefined. Those characters may be
3993     suppressed or replaced by another.
3994
3995     \sa fromLocal8Bit(), toAscii(), toLatin1(), toUtf8(), QTextCodec
3996 */
3997 QByteArray QString::toLocal8Bit() const
3998 {
3999 #ifndef QT_NO_TEXTCODEC
4000     if (QTextCodec::codecForLocale())
4001         return QTextCodec::codecForLocale()->fromUnicode(*this);
4002 #endif // QT_NO_TEXTCODEC
4003     return toLatin1();
4004 }
4005
4006 /*!
4007     Returns a UTF-8 representation of the string as a QByteArray.
4008
4009     UTF-8 is a Unicode codec and can represent all characters in a Unicode
4010     string like QString.
4011
4012     However, in the Unicode range, there are certain codepoints that are not
4013     considered characters. The Unicode standard reserves the last two
4014     codepoints in each Unicode Plane (U+FFFE, U+FFFF, U+1FFFE, U+1FFFF,
4015     U+2FFFE, etc.), as well as 16 codepoints in the range U+FDD0..U+FDDF,
4016     inclusive, as non-characters. If any of those appear in the string, they
4017     may be discarded and will not appear in the UTF-8 representation, or they
4018     may be replaced by one or more replacement characters.
4019
4020     \sa fromUtf8(), toAscii(), toLatin1(), toLocal8Bit(), QTextCodec
4021 */
4022 QByteArray QString::toUtf8() const
4023 {
4024     if (isNull())
4025         return QByteArray();
4026
4027     return QUtf8::convertFromUnicode(constData(), length(), 0);
4028 }
4029
4030 /*!
4031     \since 4.2
4032
4033     Returns a UCS-4/UTF-32 representation of the string as a QVector<uint>.
4034
4035     UCS-4 is a Unicode codec and is lossless. All characters from this string
4036     can be encoded in UCS-4. The vector is not null terminated.
4037
4038     \sa fromUtf8(), toAscii(), toLatin1(), toLocal8Bit(), QTextCodec, fromUcs4(), toWCharArray()
4039 */
4040 QVector<uint> QString::toUcs4() const
4041 {
4042     QVector<uint> v(length());
4043     uint *a = v.data();
4044     int len = toUcs4_helper(d->data(), length(), a);
4045     v.resize(len);
4046     return v;
4047 }
4048
4049 QString::Data *QString::fromLatin1_helper(const char *str, int size)
4050 {
4051     Data *d;
4052     if (!str) {
4053         d = shared_null.data_ptr();
4054     } else if (size == 0 || (!*str && size < 0)) {
4055         d = shared_empty.data_ptr();
4056     } else {
4057         if (size < 0)
4058             size = qstrlen(str);
4059         d = static_cast<Data *>(::malloc(sizeof(Data) + (size+1) * sizeof(QChar)));
4060         Q_CHECK_PTR(d);
4061         d->ref.initializeOwned();
4062         d->size = size;
4063         d->alloc = (uint) size;
4064         d->capacityReserved = false;
4065         d->offset = sizeof(QStringData);
4066         d->data()[size] = '\0';
4067         ushort *dst = d->data();
4068         /* SIMD:
4069          * Unpacking with SSE has been shown to improve performance on recent CPUs
4070          * The same method gives no improvement with NEON.
4071          */
4072 #if defined(QT_ALWAYS_HAVE_SSE2)
4073         if (size >= 16) {
4074             int chunkCount = size >> 4; // divided by 16
4075             const __m128i nullMask = _mm_set1_epi32(0);
4076             for (int i = 0; i < chunkCount; ++i) {
4077                 const __m128i chunk = _mm_loadu_si128((__m128i*)str); // load
4078                 str += 16;
4079
4080                 // unpack the first 8 bytes, padding with zeros
4081                 const __m128i firstHalf = _mm_unpacklo_epi8(chunk, nullMask);
4082                 _mm_storeu_si128((__m128i*)dst, firstHalf); // store
4083                 dst += 8;
4084
4085                 // unpack the last 8 bytes, padding with zeros
4086                 const __m128i secondHalf = _mm_unpackhi_epi8 (chunk, nullMask);
4087                 _mm_storeu_si128((__m128i*)dst, secondHalf); // store
4088                 dst += 8;
4089             }
4090             size = size % 16;
4091         }
4092 #endif
4093         while (size--)
4094             *dst++ = (uchar)*str++;
4095     }
4096     return d;
4097 }
4098
4099 QString::Data *QString::fromAscii_helper(const char *str, int size)
4100 {
4101     return fromLatin1_helper(str, size);
4102 }
4103
4104 /*! \fn QString QString::fromLatin1(const char *str, int size)
4105     Returns a QString initialized with the first \a size characters
4106     of the Latin-1 string \a str.
4107
4108     If \a size is -1 (default), it is taken to be strlen(\a
4109     str).
4110
4111     \sa toLatin1(), fromAscii(), fromUtf8(), fromLocal8Bit()
4112 */
4113
4114
4115 /*! \fn QString QString::fromLocal8Bit(const char *str, int size)
4116     Returns a QString initialized with the first \a size characters
4117     of the 8-bit string \a str.
4118
4119     If \a size is -1 (default), it is taken to be strlen(\a
4120     str).
4121
4122     QTextCodec::codecForLocale() is used to perform the conversion.
4123
4124     \sa toLocal8Bit(), fromAscii(), fromLatin1(), fromUtf8()
4125 */
4126 QString QString::fromLocal8Bit_helper(const char *str, int size)
4127 {
4128     if (!str)
4129         return QString();
4130     if (size == 0 || (!*str && size < 0)) {
4131         QStringDataPtr empty = { shared_empty.data_ptr() };
4132         return QString(empty);
4133     }
4134 #if !defined(QT_NO_TEXTCODEC)
4135     if (size < 0)
4136         size = qstrlen(str);
4137     QTextCodec *codec = QTextCodec::codecForLocale();
4138     if (codec)
4139         return codec->toUnicode(str, size);
4140 #endif // !QT_NO_TEXTCODEC
4141     return fromLatin1(str, size);
4142 }
4143
4144 /*! \fn QString QString::fromAscii(const char *, int size);
4145     Returns a QString initialized with the first \a size characters
4146     from the string \a str.
4147
4148     If \a size is -1 (default), it is taken to be strlen(\a
4149     str).
4150
4151     This function does the same as fromLatin1().
4152
4153     \sa toAscii(), fromLatin1(), fromUtf8(), fromLocal8Bit()
4154 */
4155
4156 /*! \fn QString QString::fromUtf8(const char *str, int size)
4157     Returns a QString initialized with the first \a size bytes
4158     of the UTF-8 string \a str.
4159
4160     If \a size is -1 (default), it is taken to be strlen(\a
4161     str).
4162
4163     UTF-8 is a Unicode codec and can represent all characters in a Unicode
4164     string like QString. However, invalid sequences are possible with UTF-8
4165     and, if any such are found, they will be replaced with one or more
4166     "replacement characters", or suppressed. These include non-Unicode
4167     sequences, non-characters, overlong sequences or surrogate codepoints
4168     encoded into UTF-8.
4169
4170     Non-characters are codepoints that the Unicode standard reserves and must
4171     not be used in text interchange. They are the last two codepoints in each
4172     Unicode Plane (U+FFFE, U+FFFF, U+1FFFE, U+1FFFF, U+2FFFE, etc.), as well
4173     as 16 codepoints in the range U+FDD0..U+FDDF, inclusive.
4174
4175     \sa toUtf8(), fromAscii(), fromLatin1(), fromLocal8Bit()
4176 */
4177 QString QString::fromUtf8_helper(const char *str, int size)
4178 {
4179     if (!str)
4180         return QString();
4181
4182     Q_ASSERT(size != -1);
4183     return QUtf8::convertToUnicode(str, size, 0);
4184 }
4185
4186 /*!
4187     Returns a QString initialized with the first \a size characters
4188     of the Unicode string \a unicode (ISO-10646-UTF-16 encoded).
4189
4190     If \a size is -1 (default), \a unicode must be terminated
4191     with a 0.
4192
4193     This function checks for a Byte Order Mark (BOM). If it is missing,
4194     host byte order is assumed.
4195
4196     This function is slow compared to the other Unicode conversions.
4197     Use QString(const QChar *, int) or QString(const QChar *) if possible.
4198
4199     QString makes a deep copy of the Unicode data.
4200
4201     \sa utf16(), setUtf16()
4202 */
4203 QString QString::fromUtf16(const ushort *unicode, int size)
4204 {
4205     if (!unicode)
4206         return QString();
4207     if (size < 0) {
4208         size = 0;
4209         while (unicode[size] != 0)
4210             ++size;
4211     }
4212     return QUtf16::convertToUnicode((const char *)unicode, size*2, 0);
4213 }
4214
4215
4216 /*!
4217     \since 4.2
4218
4219     Returns a QString initialized with the first \a size characters
4220     of the Unicode string \a unicode (ISO-10646-UCS-4 encoded).
4221
4222     If \a size is -1 (default), \a unicode must be terminated
4223     with a 0.
4224
4225     \sa toUcs4(), fromUtf16(), utf16(), setUtf16(), fromWCharArray()
4226 */
4227 QString QString::fromUcs4(const uint *unicode, int size)
4228 {
4229     if (!unicode)
4230         return QString();
4231     if (size < 0) {
4232         size = 0;
4233         while (unicode[size] != 0)
4234             ++size;
4235     }
4236     return QUtf32::convertToUnicode((const char *)unicode, size*4, 0);
4237 }
4238
4239 /*!
4240     Resizes the string to \a size characters and copies \a unicode
4241     into the string.
4242
4243     If \a unicode is 0, nothing is copied, but the string is still
4244     resized to \a size.
4245
4246     \sa unicode(), setUtf16()
4247 */
4248 QString& QString::setUnicode(const QChar *unicode, int size)
4249 {
4250      resize(size);
4251      if (unicode && size)
4252          memcpy(d->data(), unicode, size * sizeof(QChar));
4253      return *this;
4254 }
4255
4256 /*!
4257     \fn QString &QString::setUtf16(const ushort *unicode, int size)
4258
4259     Resizes the string to \a size characters and copies \a unicode
4260     into the string.
4261
4262     If \a unicode is 0, nothing is copied, but the string is still
4263     resized to \a size.
4264
4265     Note that unlike fromUtf16(), this function does not consider BOMs and
4266     possibly differing byte ordering.
4267
4268     \sa utf16(), setUnicode()
4269 */
4270
4271 /*!
4272     Returns a string that has whitespace removed from the start
4273     and the end, and that has each sequence of internal whitespace
4274     replaced with a single space.
4275
4276     Whitespace means any character for which QChar::isSpace() returns
4277     true. This includes the ASCII characters '\\t', '\\n', '\\v',
4278     '\\f', '\\r', and ' '.
4279
4280     Example:
4281
4282     \snippet doc/src/snippets/qstring/main.cpp 57
4283
4284     \sa trimmed()
4285 */
4286 QString QString::simplified() const
4287 {
4288     if (d->size == 0)
4289         return *this;
4290
4291     const QChar * const start = reinterpret_cast<QChar *>(d->data());
4292     const QChar *from = start;
4293     const QChar *fromEnd = start + d->size;
4294     forever {
4295         QChar ch = *from;
4296         if (!ch.isSpace())
4297             break;
4298         if (++from == fromEnd) {
4299             // All-whitespace string
4300             QStringDataPtr empty = { shared_empty.data_ptr() };
4301             return QString(empty);
4302         }
4303     }
4304     // This loop needs no underflow check, as we already determined that
4305     // the string contains non-whitespace. If the string has exactly one
4306     // non-whitespace, it will be checked twice - we can live with that.
4307     while (fromEnd[-1].isSpace())
4308         fromEnd--;
4309     // The rest of the function depends on the fact that we already know
4310     // that the last character in the source is no whitespace.
4311     const QChar *copyFrom = from;
4312     int copyCount;
4313     forever {
4314         if (++from == fromEnd) {
4315             // Only leading and/or trailing whitespace, if any at all
4316             return mid(copyFrom - start, from - copyFrom);
4317         }
4318         QChar ch = *from;
4319         if (!ch.isSpace())
4320             continue;
4321         if (ch != QLatin1Char(' ')) {
4322             copyCount = from - copyFrom;
4323             break;
4324         }
4325         ch = *++from;
4326         if (ch.isSpace()) {
4327             copyCount = from - copyFrom - 1;
4328             break;
4329         }
4330     }
4331     // 'from' now points at the non-trailing whitespace which made the
4332     // string not simplified in the first place. 'copyCount' is the number
4333     // of already simplified characters - at least one, obviously -
4334     // without a trailing space.
4335     QString result((fromEnd - from) + copyCount, Qt::Uninitialized);
4336     QChar *to = reinterpret_cast<QChar *>(result.d->data());
4337     ::memcpy(to, copyFrom, copyCount * 2);
4338     to += copyCount;
4339     fromEnd--;
4340     QChar ch;
4341     forever {
4342         *to++ = QLatin1Char(' ');
4343         do {
4344             ch = *++from;
4345         } while (ch.isSpace());
4346         if (from == fromEnd)
4347             break;
4348         do {
4349             *to++ = ch;
4350             ch = *++from;
4351             if (from == fromEnd)
4352                 goto done;
4353         } while (!ch.isSpace());
4354
4355     }
4356   done:
4357     *to++ = ch;
4358     result.truncate(to - reinterpret_cast<QChar *>(result.d->data()));
4359     return result;
4360 }
4361
4362 /*!
4363     Returns a string that has whitespace removed from the start and
4364     the end.
4365
4366     Whitespace means any character for which QChar::isSpace() returns
4367     true. This includes the ASCII characters '\\t', '\\n', '\\v',
4368     '\\f', '\\r', and ' '.
4369
4370     Example:
4371
4372     \snippet doc/src/snippets/qstring/main.cpp 82
4373
4374     Unlike simplified(), trimmed() leaves internal whitespace alone.
4375
4376     \sa simplified()
4377 */
4378 QString QString::trimmed() const
4379 {
4380     if (d->size == 0)
4381         return *this;
4382     const QChar *s = (const QChar*)d->data();
4383     if (!s->isSpace() && !s[d->size-1].isSpace())
4384         return *this;
4385     int start = 0;
4386     int end = d->size - 1;
4387     while (start<=end && s[start].isSpace())  // skip white space from start
4388         start++;
4389     if (start <= end) {                          // only white space
4390         while (end && s[end].isSpace())           // skip white space from end
4391             end--;
4392     }
4393     int l = end - start + 1;
4394     if (l <= 0) {
4395         QStringDataPtr empty = { shared_empty.data_ptr() };
4396         return QString(empty);
4397     }
4398     return QString(s + start, l);
4399 }
4400
4401 /*! \fn const QChar QString::at(int position) const
4402
4403     Returns the character at the given index \a position in the
4404     string.
4405
4406     The \a position must be a valid index position in the string
4407     (i.e., 0 <= \a position < size()).
4408
4409     \sa operator[]()
4410 */
4411
4412 /*!
4413     \fn QCharRef QString::operator[](int position)
4414
4415     Returns the character at the specified \a position in the string as a
4416     modifiable reference.
4417
4418     Example:
4419
4420     \snippet doc/src/snippets/qstring/main.cpp 85
4421
4422     The return value is of type QCharRef, a helper class for QString.
4423     When you get an object of type QCharRef, you can use it as if it
4424     were a QChar &. If you assign to it, the assignment will apply to
4425     the character in the QString from which you got the reference.
4426
4427     \sa at()
4428 */
4429
4430 /*!
4431     \fn const QChar QString::operator[](int position) const
4432
4433     \overload operator[]()
4434 */
4435
4436 /*! \fn QCharRef QString::operator[](uint position)
4437
4438 \overload operator[]()
4439
4440 Returns the character at the specified \a position in the string as a
4441 modifiable reference. Equivalent to \c at(position).
4442 */
4443
4444 /*! \fn const QChar QString::operator[](uint position) const
4445
4446 \overload operator[]()
4447 */
4448
4449 /*!
4450     \fn void QString::truncate(int position)
4451
4452     Truncates the string at the given \a position index.
4453
4454     If the specified \a position index is beyond the end of the
4455     string, nothing happens.
4456
4457     Example:
4458
4459     \snippet doc/src/snippets/qstring/main.cpp 83
4460
4461     If \a position is negative, it is equivalent to passing zero.
4462
4463     \sa chop(), resize(), left()
4464 */
4465
4466 void QString::truncate(int pos)
4467 {
4468     if (pos < d->size)
4469         resize(pos);
4470 }
4471
4472
4473 /*!
4474     Removes \a n characters from the end of the string.
4475
4476     If \a n is greater than size(), the result is an empty string.
4477
4478     Example:
4479     \snippet doc/src/snippets/qstring/main.cpp 15
4480
4481     If you want to remove characters from the \e beginning of the
4482     string, use remove() instead.
4483
4484     \sa truncate(), resize(), remove()
4485 */
4486 void QString::chop(int n)
4487 {
4488     if (n > 0)
4489         resize(d->size - n);
4490 }
4491
4492 /*!
4493     Sets every character in the string to character \a ch. If \a size
4494     is different from -1 (default), the string is resized to \a
4495     size beforehand.
4496
4497     Example:
4498
4499     \snippet doc/src/snippets/qstring/main.cpp 21
4500
4501     \sa resize()
4502 */
4503
4504 QString& QString::fill(QChar ch, int size)
4505 {
4506     resize(size < 0 ? d->size : size);
4507     if (d->size) {
4508         QChar *i = (QChar*)d->data() + d->size;
4509         QChar *b = (QChar*)d->data();
4510         while (i != b)
4511            *--i = ch;
4512     }
4513     return *this;
4514 }
4515
4516 /*!
4517     \fn int QString::length() const
4518
4519     Returns the number of characters in this string.  Equivalent to
4520     size().
4521
4522     \sa resize()
4523 */
4524
4525 /*!
4526     \fn int QString::size() const
4527
4528     Returns the number of characters in this string.
4529
4530     The last character in the string is at position size() - 1. In
4531     addition, QString ensures that the character at position size()
4532     is always '\\0', so that you can use the return value of data()
4533     and constData() as arguments to functions that expect
4534     '\\0'-terminated strings.
4535
4536     Example:
4537
4538     \snippet doc/src/snippets/qstring/main.cpp 58
4539
4540     \sa isEmpty(), resize()
4541 */
4542
4543 /*! \fn bool QString::isNull() const
4544
4545     Returns true if this string is null; otherwise returns false.
4546
4547     Example:
4548
4549     \snippet doc/src/snippets/qstring/main.cpp 28
4550
4551     Qt makes a distinction between null strings and empty strings for
4552     historical reasons. For most applications, what matters is
4553     whether or not a string contains any data, and this can be
4554     determined using the isEmpty() function.
4555
4556     \sa isEmpty()
4557 */
4558
4559 /*! \fn bool QString::isEmpty() const
4560
4561     Returns true if the string has no characters; otherwise returns
4562     false.
4563
4564     Example:
4565
4566     \snippet doc/src/snippets/qstring/main.cpp 27
4567
4568     \sa size()
4569 */
4570
4571 /*! \fn QString &QString::operator+=(const QString &other)
4572
4573     Appends the string \a other onto the end of this string and
4574     returns a reference to this string.
4575
4576     Example:
4577
4578     \snippet doc/src/snippets/qstring/main.cpp 84
4579
4580     This operation is typically very fast (\l{constant time}),
4581     because QString preallocates extra space at the end of the string
4582     data so it can grow without reallocating the entire string each
4583     time.
4584
4585     \sa append(), prepend()
4586 */
4587
4588 /*! \fn QString &QString::operator+=(const QLatin1String &str)
4589
4590     \overload operator+=()
4591
4592     Appends the Latin-1 string \a str to this string.
4593 */
4594
4595 /*! \fn QString &QString::operator+=(const QByteArray &ba)
4596
4597     \overload operator+=()
4598
4599     Appends the byte array \a ba to this string. The byte array is converted
4600     to Unicode using the fromAscii() function. If any NUL characters ('\0')
4601     are embedded in the \a ba byte array, they will be included in the
4602     transformation.
4603
4604     You can disable this function by defining \c
4605     QT_NO_CAST_FROM_ASCII when you compile your applications. This
4606     can be useful if you want to ensure that all user-visible strings
4607     go through QObject::tr(), for example.
4608 */
4609
4610 /*! \fn QString &QString::operator+=(const char *str)
4611
4612     \overload operator+=()
4613
4614     Appends the string \a str to this string. The const char pointer
4615     is converted to Unicode using the fromAscii() function.
4616
4617     You can disable this function by defining \c QT_NO_CAST_FROM_ASCII
4618     when you compile your applications. This can be useful if you want
4619     to ensure that all user-visible strings go through QObject::tr(),
4620     for example.
4621 */
4622
4623 /*! \fn QString &QString::operator+=(const QStringRef &str)
4624
4625     \overload operator+=()
4626
4627     Appends the string section referenced by \a str to this string.
4628 */
4629
4630 /*! \fn QString &QString::operator+=(char ch)
4631
4632     \overload operator+=()
4633
4634     Appends the character \a ch to this string. The character is
4635     converted to Unicode using the fromAscii() function.
4636
4637     You can disable this function by defining \c QT_NO_CAST_FROM_ASCII
4638     when you compile your applications. This can be useful if you want
4639     to ensure that all user-visible strings go through QObject::tr(),
4640     for example.
4641 */
4642
4643 /*! \fn QString &QString::operator+=(QChar ch)
4644
4645     \overload operator+=()
4646
4647     Appends the character \a ch to the string.
4648 */
4649
4650 /*! \fn QString &QString::operator+=(QChar::SpecialCharacter c)
4651
4652     \overload operator+=()
4653
4654     \internal
4655 */
4656
4657 /*!
4658     \fn bool operator==(const char *s1, const QString &s2)
4659
4660     \overload  operator==()
4661     \relates QString
4662
4663     Returns true if \a s1 is equal to \a s2; otherwise returns false.
4664     Note that no string is equal to \a s1 being 0.
4665
4666     Equivalent to \c {s1 != 0 && compare(s1, s2) == 0}.
4667
4668     \sa QString::compare()
4669 */
4670
4671 /*!
4672     \fn bool operator!=(const char *s1, const QString &s2)
4673     \relates QString
4674
4675     Returns true if \a s1 is not equal to \a s2; otherwise returns
4676     false.
4677
4678     For \a s1 != 0, this is equivalent to \c {compare(} \a s1, \a s2
4679     \c {) != 0}. Note that no string is equal to \a s1 being 0.
4680
4681     \sa QString::compare()
4682 */
4683
4684 /*!
4685     \fn bool operator<(const char *s1, const QString &s2)
4686     \relates QString
4687
4688     Returns true if \a s1 is lexically less than \a s2; otherwise
4689     returns false.  For \a s1 != 0, this is equivalent to \c
4690     {compare(s1, s2) < 0}.
4691
4692     The comparison is based exclusively on the numeric Unicode values
4693     of the characters and is very fast, but is not what a human would
4694     expect. Consider sorting user-interface strings using the
4695     QString::localeAwareCompare() function.
4696
4697     \sa QString::compare()
4698 */
4699
4700 /*!
4701     \fn bool operator<=(const char *s1, const QString &s2)
4702     \relates QString
4703
4704     Returns true if \a s1 is lexically less than or equal to \a s2;
4705     otherwise returns false.  For \a s1 != 0, this is equivalent to \c
4706     {compare(s1, s2) <= 0}.
4707
4708     The comparison is based exclusively on the numeric Unicode values
4709     of the characters and is very fast, but is not what a human would
4710     expect. Consider sorting user-interface strings with
4711     QString::localeAwareCompare().
4712
4713     \sa QString::compare()
4714 */
4715
4716 /*!
4717     \fn bool operator>(const char *s1, const QString &s2)
4718     \relates QString
4719
4720     Returns true if \a s1 is lexically greater than \a s2; otherwise
4721     returns false.  Equivalent to \c {compare(s1, s2) > 0}.
4722
4723     The comparison is based exclusively on the numeric Unicode values
4724     of the characters and is very fast, but is not what a human would
4725     expect. Consider sorting user-interface strings using the
4726     QString::localeAwareCompare() function.
4727
4728     \sa QString::compare()
4729 */
4730
4731 /*!
4732     \fn bool operator>=(const char *s1, const QString &s2)
4733     \relates QString
4734
4735     Returns true if \a s1 is lexically greater than or equal to \a s2;
4736     otherwise returns false.  For \a s1 != 0, this is equivalent to \c
4737     {compare(s1, s2) >= 0}.
4738
4739     The comparison is based exclusively on the numeric Unicode values
4740     of the characters and is very fast, but is not what a human would
4741     expect. Consider sorting user-interface strings using the
4742     QString::localeAwareCompare() function.
4743 */
4744
4745 /*!
4746     \fn const QString operator+(const QString &s1, const QString &s2)
4747     \relates QString
4748
4749     Returns a string which is the result of concatenating \a s1 and \a
4750     s2.
4751 */
4752
4753 /*!
4754     \fn const QString operator+(const QString &s1, const char *s2)
4755     \relates QString
4756
4757     Returns a string which is the result of concatenating \a s1 and \a
4758     s2 (\a s2 is converted to Unicode using the QString::fromAscii()
4759     function).
4760
4761     \sa QString::fromAscii()
4762 */
4763
4764 /*!
4765     \fn const QString operator+(const char *s1, const QString &s2)
4766     \relates QString
4767
4768     Returns a string which is the result of concatenating \a s1 and \a
4769     s2 (\a s1 is converted to Unicode using the QString::fromAscii()
4770     function).
4771
4772     \sa QString::fromAscii()
4773 */
4774
4775 /*!
4776     \fn const QString operator+(const QString &s, char ch)
4777     \relates QString
4778
4779     Returns a string which is the result of concatenating the string
4780     \a s and the character \a ch.
4781 */
4782
4783 /*!
4784     \fn const QString operator+(char ch, const QString &s)
4785     \relates QString
4786
4787     Returns a string which is the result of concatenating the
4788     character \a ch and the string \a s.
4789 */
4790
4791 /*!
4792     \fn int QString::compare(const QString &s1, const QString &s2, Qt::CaseSensitivity cs)
4793     \since 4.2
4794
4795     Compares \a s1 with \a s2 and returns an integer less than, equal
4796     to, or greater than zero if \a s1 is less than, equal to, or
4797     greater than \a s2.
4798
4799     If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
4800     otherwise the comparison is case insensitive.
4801
4802     Case sensitive comparison is based exclusively on the numeric
4803     Unicode values of the characters and is very fast, but is not what
4804     a human would expect.  Consider sorting user-visible strings with
4805     localeAwareCompare().
4806
4807     \snippet doc/src/snippets/qstring/main.cpp 16
4808
4809     \sa operator==(), operator<(), operator>()
4810 */
4811
4812 /*!
4813     \fn int QString::compare(const QString &s1, const QLatin1String &s2, Qt::CaseSensitivity cs)
4814     \since 4.2
4815     \overload compare()
4816
4817     Performs a comparison of \a s1 and \a s2, using the case
4818     sensitivity setting \a cs.
4819 */
4820
4821 /*!
4822     \fn int QString::compare(const QLatin1String &s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
4823
4824     \since 4.2
4825     \overload compare()
4826
4827     Performs a comparison of \a s1 and \a s2, using the case
4828     sensitivity setting \a cs.
4829 */
4830
4831
4832 /*!
4833     \overload compare()
4834     \since 4.2
4835
4836     Lexically compares this string with the \a other string and
4837     returns an integer less than, equal to, or greater than zero if
4838     this string is less than, equal to, or greater than the other
4839     string.
4840
4841     Same as compare(*this, \a other, \a cs).
4842 */
4843 int QString::compare(const QString &other, Qt::CaseSensitivity cs) const
4844 {
4845     if (cs == Qt::CaseSensitive)
4846         return ucstrcmp(constData(), length(), other.constData(), other.length());
4847     return ucstricmp(d->data(), d->data() + d->size, other.d->data(), other.d->data() + other.d->size);
4848 }
4849
4850 /*!
4851     \internal
4852     \since 4.5
4853 */
4854 int QString::compare_helper(const QChar *data1, int length1, const QChar *data2, int length2,
4855                             Qt::CaseSensitivity cs)
4856 {
4857     if (cs == Qt::CaseSensitive)
4858         return ucstrcmp(data1, length1, data2, length2);
4859     register const ushort *s1 = reinterpret_cast<const ushort *>(data1);
4860     register const ushort *s2 = reinterpret_cast<const ushort *>(data2);
4861     return ucstricmp(s1, s1 + length1, s2, s2 + length2);
4862 }
4863
4864 /*!
4865     \overload compare()
4866     \since 4.2
4867
4868     Same as compare(*this, \a other, \a cs).
4869 */
4870 int QString::compare(const QLatin1String &other, Qt::CaseSensitivity cs) const
4871 {
4872     return compare_helper(unicode(), length(), other, cs);
4873 }
4874
4875 /*!
4876   \fn int QString::compare(const QStringRef &ref, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
4877   \overload compare()
4878
4879   Compares the string reference, \a ref, with the string and returns
4880   an integer less than, equal to, or greater than zero if the string
4881   is less than, equal to, or greater than \a ref.
4882 */
4883
4884 /*!
4885   \fn int QString::compare(const QString &s1, const QStringRef &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
4886   \overload compare()
4887 */
4888
4889 /*!
4890     \internal
4891     \since 4.5
4892 */
4893 int QString::compare_helper(const QChar *data1, int length1, QLatin1String s2,
4894                             Qt::CaseSensitivity cs)
4895 {
4896     const ushort *uc = reinterpret_cast<const ushort *>(data1);
4897     const ushort *uce = uc + length1;
4898     const uchar *c = (uchar *)s2.latin1();
4899
4900     if (!c)
4901         return length1;
4902
4903     if (cs == Qt::CaseSensitive) {
4904         const ushort *e = uc + length1;
4905         if (s2.size() < length1)
4906             e = uc + s2.size();
4907         while (uc < e) {
4908             int diff = *uc - *c;
4909             if (diff)
4910                 return diff;
4911             uc++, c++;
4912         }
4913
4914         if (uc == uce) {
4915             if (c == (const uchar *)s2.latin1() + s2.size())
4916                 return 0;
4917             return -1;
4918         }
4919         return 1;
4920     } else {
4921         return ucstricmp(uc, uce, c, c + s2.size());
4922     }
4923 }
4924
4925 /*!
4926     \fn int QString::localeAwareCompare(const QString & s1, const QString & s2)
4927
4928     Compares \a s1 with \a s2 and returns an integer less than, equal
4929     to, or greater than zero if \a s1 is less than, equal to, or
4930     greater than \a s2.
4931
4932     The comparison is performed in a locale- and also
4933     platform-dependent manner. Use this function to present sorted
4934     lists of strings to the user.
4935
4936     On Mac OS X since Qt 4.3, this function compares according the
4937     "Order for sorted lists" setting in the International prefereces panel.
4938
4939     \sa compare(), QTextCodec::locale()
4940 */
4941
4942 /*!
4943     \fn int QString::localeAwareCompare(const QStringRef &other) const
4944     \since 4.5
4945     \overload localeAwareCompare()
4946
4947     Compares this string with the \a other string and returns an
4948     integer less than, equal to, or greater than zero if this string
4949     is less than, equal to, or greater than the \a other string.
4950
4951     The comparison is performed in a locale- and also
4952     platform-dependent manner. Use this function to present sorted
4953     lists of strings to the user.
4954
4955     Same as \c {localeAwareCompare(*this, other)}.
4956 */
4957
4958 /*!
4959     \fn int QString::localeAwareCompare(const QString &s1, const QStringRef &s2)
4960     \since 4.5
4961     \overload localeAwareCompare()
4962
4963     Compares \a s1 with \a s2 and returns an integer less than, equal
4964     to, or greater than zero if \a s1 is less than, equal to, or
4965     greater than \a s2.
4966
4967     The comparison is performed in a locale- and also
4968     platform-dependent manner. Use this function to present sorted
4969     lists of strings to the user.
4970 */
4971
4972
4973 #if !defined(CSTR_LESS_THAN)
4974 #define CSTR_LESS_THAN    1
4975 #define CSTR_EQUAL        2
4976 #define CSTR_GREATER_THAN 3
4977 #endif
4978
4979 /*!
4980     \overload localeAwareCompare()
4981
4982     Compares this string with the \a other string and returns an
4983     integer less than, equal to, or greater than zero if this string
4984     is less than, equal to, or greater than the \a other string.
4985
4986     The comparison is performed in a locale- and also
4987     platform-dependent manner. Use this function to present sorted
4988     lists of strings to the user.
4989
4990     Same as \c {localeAwareCompare(*this, other)}.
4991 */
4992 int QString::localeAwareCompare(const QString &other) const
4993 {
4994     return localeAwareCompare_helper(constData(), length(), other.constData(), other.length());
4995 }
4996
4997 /*!
4998     \internal
4999     \since 4.5
5000 */
5001 int QString::localeAwareCompare_helper(const QChar *data1, int length1,
5002                                        const QChar *data2, int length2)
5003 {
5004     // do the right thing for null and empty
5005     if (length1 == 0 || length2 == 0)
5006         return ucstrcmp(data1, length1, data2, length2);
5007
5008 #if defined(Q_OS_WIN32) || defined(Q_OS_WINCE)
5009     int res = CompareString(GetUserDefaultLCID(), 0, (wchar_t*)data1, length1, (wchar_t*)data2, length2);
5010
5011     switch (res) {
5012     case CSTR_LESS_THAN:
5013         return -1;
5014     case CSTR_GREATER_THAN:
5015         return 1;
5016     default:
5017         return 0;
5018     }
5019 #elif defined (Q_OS_MAC)
5020     // Use CFStringCompare for comparing strings on Mac. This makes Qt order
5021     // strings the same way as native applications do, and also respects
5022     // the "Order for sorted lists" setting in the International preferences
5023     // panel.
5024     const CFStringRef thisString =
5025         CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault,
5026             reinterpret_cast<const UniChar *>(data1), length1, kCFAllocatorNull);
5027     const CFStringRef otherString =
5028         CFStringCreateWithCharactersNoCopy(kCFAllocatorDefault,
5029             reinterpret_cast<const UniChar *>(data2), length2, kCFAllocatorNull);
5030
5031     const int result = CFStringCompare(thisString, otherString, kCFCompareLocalized);
5032     CFRelease(thisString);
5033     CFRelease(otherString);
5034     return result;
5035 #elif defined(Q_OS_UNIX)
5036 #  if defined(QT_USE_ICU)
5037     int res;
5038     if (qt_ucol_strcoll(data1, length1, data2, length2, &res)) {
5039         if (res == 0)
5040             res = ucstrcmp(data1, length1, data2, length2);
5041         return res;
5042     } // else fall through
5043 #  endif
5044     // declared in <string.h>
5045     int delta = strcoll(toLocal8Bit_helper(data1, length1).constData(), toLocal8Bit_helper(data2, length2).constData());
5046     if (delta == 0)
5047         delta = ucstrcmp(data1, length1, data2, length2);
5048     return delta;
5049 #else
5050     return ucstrcmp(data1, length1, data2, length2);
5051 #endif
5052 }
5053
5054
5055 /*!
5056     \fn const QChar *QString::unicode() const
5057
5058     Returns a '\\0'-terminated Unicode representation of the string.
5059     The result remains valid until the string is modified.
5060
5061     \sa utf16()
5062 */
5063
5064 /*!
5065     \fn const ushort *QString::utf16() const
5066
5067     Returns the QString as a '\\0\'-terminated array of unsigned
5068     shorts. The result remains valid until the string is modified.
5069
5070     The returned string is in host byte order.
5071
5072     \sa unicode()
5073 */
5074
5075 const ushort *QString::utf16() const
5076 {
5077     if (IS_RAW_DATA(d)) {
5078         // ensure '\0'-termination for ::fromRawData strings
5079         const_cast<QString*>(this)->reallocData(d->size);
5080     }
5081     return d->data();
5082 }
5083
5084 /*!
5085     Returns a string of size \a width that contains this string
5086     padded by the \a fill character.
5087
5088     If \a truncate is false and the size() of the string is more than
5089     \a width, then the returned string is a copy of the string.
5090
5091     \snippet doc/src/snippets/qstring/main.cpp 32
5092
5093     If \a truncate is true and the size() of the string is more than
5094     \a width, then any characters in a copy of the string after
5095     position \a width are removed, and the copy is returned.
5096
5097     \snippet doc/src/snippets/qstring/main.cpp 33
5098
5099     \sa rightJustified()
5100 */
5101
5102 QString QString::leftJustified(int width, QChar fill, bool truncate) const
5103 {
5104     QString result;
5105     int len = length();
5106     int padlen = width - len;
5107     if (padlen > 0) {
5108         result.resize(len+padlen);
5109         if (len)
5110             memcpy(result.d->data(), d->data(), sizeof(QChar)*len);
5111         QChar *uc = (QChar*)result.d->data() + len;
5112         while (padlen--)
5113            * uc++ = fill;
5114     } else {
5115         if (truncate)
5116             result = left(width);
5117         else
5118             result = *this;
5119     }
5120     return result;
5121 }
5122
5123 /*!
5124     Returns a string of size() \a width that contains the \a fill
5125     character followed by the string. For example:
5126
5127     \snippet doc/src/snippets/qstring/main.cpp 49
5128
5129     If \a truncate is false and the size() of the string is more than
5130     \a width, then the returned string is a copy of the string.
5131
5132     If \a truncate is true and the size() of the string is more than
5133     \a width, then the resulting string is truncated at position \a
5134     width.
5135
5136     \snippet doc/src/snippets/qstring/main.cpp 50
5137
5138     \sa leftJustified()
5139 */
5140
5141 QString QString::rightJustified(int width, QChar fill, bool truncate) const
5142 {
5143     QString result;
5144     int len = length();
5145     int padlen = width - len;
5146     if (padlen > 0) {
5147         result.resize(len+padlen);
5148         QChar *uc = (QChar*)result.d->data();
5149         while (padlen--)
5150            * uc++ = fill;
5151         if (len)
5152             memcpy(uc, d->data(), sizeof(QChar)*len);
5153     } else {
5154         if (truncate)
5155             result = left(width);
5156         else
5157             result = *this;
5158     }
5159     return result;
5160 }
5161
5162 /*!
5163     Returns a lowercase copy of the string.
5164
5165     \snippet doc/src/snippets/qstring/main.cpp 75
5166
5167     The case conversion will always happen in the 'C' locale. For locale dependent
5168     case folding use QLocale::toLower()
5169
5170     \sa toUpper(), QLocale::toLower()
5171 */
5172
5173 QString QString::toLower() const
5174 {
5175     const ushort *p = d->data();
5176     if (!p)
5177         return *this;
5178
5179     const ushort *e = p + d->size;
5180     // this avoids out of bounds check in the loop
5181     while (e != p && QChar::isHighSurrogate(*(e - 1)))
5182         --e;
5183
5184     const QUnicodeTables::Properties *prop;
5185     while (p != e) {
5186         if (QChar::isHighSurrogate(*p) && QChar::isLowSurrogate(p[1])) {
5187             ushort high = *p++;
5188             prop = qGetProp(QChar::surrogateToUcs4(high, *p));
5189         } else {
5190             prop = qGetProp(*p);
5191         }
5192         if (prop->lowerCaseDiff) {
5193             if (QChar::isLowSurrogate(*p))
5194                 --p; // safe; diff is 0 for surrogates
5195             QString s(d->size, Qt::Uninitialized);
5196             memcpy(s.d->data(), d->data(), (p - d->data())*sizeof(ushort));
5197             ushort *pp = s.d->data() + (p - d->data());
5198             while (p != e) {
5199                 if (QChar::isHighSurrogate(*p) && QChar::isLowSurrogate(p[1])) {
5200                     *pp = *p++;
5201                     prop = qGetProp(QChar::surrogateToUcs4(*pp++, *p));
5202                 } else {
5203                     prop = qGetProp(*p);
5204                 }
5205                 if (prop->lowerCaseSpecial) {
5206                     const ushort *specialCase = specialCaseMap + prop->lowerCaseDiff;
5207                     ushort length = *specialCase++;
5208                     int pos = pp - s.d->data();
5209                     s.resize(s.d->size + length - 1);
5210                     pp = s.d->data() + pos;
5211                     while (length--)
5212                         *pp++ = *specialCase++;
5213                 } else {
5214                     *pp++ = *p + prop->lowerCaseDiff;
5215                 }
5216                 ++p;
5217             }
5218
5219             // this restores high surrogate parts eaten above, if any
5220             while (e != d->data() + d->size)
5221                 *pp++ = *e++;
5222
5223             return s;
5224         }
5225         ++p;
5226     }
5227     return *this;
5228 }
5229
5230 /*!
5231     Returns the case folded equivalent of the string. For most Unicode
5232     characters this is the same as toLower().
5233 */
5234 QString QString::toCaseFolded() const
5235 {
5236     const ushort *p = d->data();
5237     if (!p)
5238         return *this;
5239
5240     const ushort *e = p + d->size;
5241     // this avoids out of bounds check in the loop
5242     while (e != p && QChar::isHighSurrogate(*(e - 1)))
5243         --e;
5244
5245     const QUnicodeTables::Properties *prop;
5246     while (p != e) {
5247         if (QChar::isHighSurrogate(*p) && QChar::isLowSurrogate(p[1])) {
5248             ushort high = *p++;
5249             prop = qGetProp(QChar::surrogateToUcs4(high, *p));
5250         } else {
5251             prop = qGetProp(*p);
5252         }
5253         if (prop->caseFoldDiff) {
5254             if (QChar::isLowSurrogate(*p))
5255                 --p; // safe; diff is 0 for surrogates
5256             QString s(d->size, Qt::Uninitialized);
5257             memcpy(s.d->data(), d->data(), (p - d->data())*sizeof(ushort));
5258             ushort *pp = s.d->data() + (p - d->data());
5259             while (p != e) {
5260                 if (QChar::isHighSurrogate(*p) && QChar::isLowSurrogate(p[1])) {
5261                     *pp = *p++;
5262                     prop = qGetProp(QChar::surrogateToUcs4(*pp++, *p));
5263                 } else {
5264                     prop = qGetProp(*p);
5265                 }
5266                 if (prop->caseFoldSpecial) {
5267                     //### we currently don't support full case foldings
5268                 } else {
5269                     *pp++ = *p + prop->caseFoldDiff;
5270                 }
5271                 ++p;
5272             }
5273
5274             // this restores high surrogate parts eaten above, if any
5275             while (e != d->data() + d->size)
5276                 *pp++ = *e++;
5277
5278             return s;
5279         }
5280         ++p;
5281     }
5282     return *this;
5283 }
5284
5285 /*!
5286     Returns an uppercase copy of the string.
5287
5288     \snippet doc/src/snippets/qstring/main.cpp 81
5289
5290     The case conversion will always happen in the 'C' locale. For locale dependent
5291     case folding use QLocale::toUpper()
5292
5293     \sa toLower(), QLocale::toLower()
5294 */
5295 QString QString::toUpper() const
5296 {
5297     const ushort *p = d->data();
5298     if (!p)
5299         return *this;
5300
5301     const ushort *e = p + d->size;
5302     // this avoids out of bounds check in the loop
5303     while (e != p && QChar::isHighSurrogate(*(e - 1)))
5304         --e;
5305
5306     const QUnicodeTables::Properties *prop;
5307     while (p != e) {
5308         if (QChar::isHighSurrogate(*p) && QChar::isLowSurrogate(p[1])) {
5309             ushort high = *p++;
5310             prop = qGetProp(QChar::surrogateToUcs4(high, *p));
5311         } else {
5312             prop = qGetProp(*p);
5313         }
5314         if (prop->upperCaseDiff) {
5315             if (QChar::isLowSurrogate(*p))
5316                 --p; // safe; diff is 0 for surrogates
5317             QString s(d->size, Qt::Uninitialized);
5318             memcpy(s.d->data(), d->data(), (p - d->data())*sizeof(ushort));
5319             ushort *pp = s.d->data() + (p - d->data());
5320             while (p != e) {
5321                 if (QChar::isHighSurrogate(*p) && QChar::isLowSurrogate(p[1])) {
5322                     *pp = *p++;
5323                     prop = qGetProp(QChar::surrogateToUcs4(*pp++, *p));
5324                 } else {
5325                     prop = qGetProp(*p);
5326                 }
5327                 if (prop->upperCaseSpecial) {
5328                     const ushort *specialCase = specialCaseMap + prop->upperCaseDiff;
5329                     ushort length = *specialCase++;
5330                     int pos = pp - s.d->data();
5331                     s.resize(s.d->size + length - 1);
5332                     pp = s.d->data() + pos;
5333                     while (length--)
5334                         *pp++ = *specialCase++;
5335                 } else {
5336                     *pp++ = *p + prop->upperCaseDiff;
5337                 }
5338                 ++p;
5339             }
5340
5341             // this restores high surrogate parts eaten above, if any
5342             while (e != d->data() + d->size)
5343                 *pp++ = *e++;
5344
5345             return s;
5346         }
5347         ++p;
5348     }
5349     return *this;
5350 }
5351
5352 // ### Qt 6: Consider whether this function shouldn't be removed See task 202871.
5353 /*!
5354     Safely builds a formatted string from the format string \a cformat
5355     and an arbitrary list of arguments.
5356
5357     The %lc escape sequence expects a unicode character of type ushort
5358     (as returned by QChar::unicode()). The %ls escape sequence expects
5359     a pointer to a zero-terminated array of unicode characters of type
5360     ushort (as returned by QString::utf16()).
5361
5362     \note This function expects a UTF-8 string for %s and Latin-1 for
5363     the format string.
5364
5365     The format string supports most of the conversion specifiers
5366     provided by printf() in the standard C++ library. It doesn't
5367     honor the length modifiers (e.g. \c h for \c short, \c ll for
5368     \c{long long}). If you need those, use the standard snprintf()
5369     function instead:
5370
5371     \snippet doc/src/snippets/qstring/main.cpp 63
5372
5373     \warning We do not recommend using QString::sprintf() in new Qt
5374     code. Instead, consider using QTextStream or arg(), both of
5375     which support Unicode strings seamlessly and are type-safe.
5376     Here's an example that uses QTextStream:
5377
5378     \snippet doc/src/snippets/qstring/main.cpp 64
5379
5380     For \l {QObject::tr()}{translations}, especially if the strings
5381     contains more than one escape sequence, you should consider using
5382     the arg() function instead. This allows the order of the
5383     replacements to be controlled by the translator.
5384
5385     \sa arg()
5386 */
5387
5388 QString &QString::sprintf(const char *cformat, ...)
5389 {
5390     va_list ap;
5391     va_start(ap, cformat);
5392     QString &s = vsprintf(cformat, ap);
5393     va_end(ap);
5394     return s;
5395 }
5396
5397 /*!
5398     Equivalent method to sprintf(), but takes a va_list \a ap
5399     instead a list of variable arguments. See the sprintf()
5400     documentation for an explanation of \a cformat.
5401
5402     This method does not call the va_end macro, the caller
5403     is responsible to call va_end on \a ap.
5404
5405     \sa sprintf()
5406 */
5407
5408 QString &QString::vsprintf(const char* cformat, va_list ap)
5409 {
5410     QLocale locale(QLocale::C);
5411
5412     if (!cformat || !*cformat) {
5413         // Qt 1.x compat
5414         *this = fromLatin1("");
5415         return *this;
5416     }
5417
5418     // Parse cformat
5419
5420     QString result;
5421     const char *c = cformat;
5422     for (;;) {
5423         // Copy non-escape chars to result
5424         while (*c != '\0' && *c != '%')
5425             result.append(QLatin1Char(*c++));
5426
5427         if (*c == '\0')
5428             break;
5429
5430         // Found '%'
5431         const char *escape_start = c;
5432         ++c;
5433
5434         if (*c == '\0') {
5435             result.append(QLatin1Char('%')); // a % at the end of the string - treat as non-escape text
5436             break;
5437         }
5438         if (*c == '%') {
5439             result.append(QLatin1Char('%')); // %%
5440             ++c;
5441             continue;
5442         }
5443
5444         // Parse flag characters
5445         uint flags = 0;
5446         bool no_more_flags = false;
5447         do {
5448             switch (*c) {
5449                 case '#': flags |= QLocalePrivate::Alternate; break;
5450                 case '0': flags |= QLocalePrivate::ZeroPadded; break;
5451                 case '-': flags |= QLocalePrivate::LeftAdjusted; break;
5452                 case ' ': flags |= QLocalePrivate::BlankBeforePositive; break;
5453                 case '+': flags |= QLocalePrivate::AlwaysShowSign; break;
5454                 case '\'': flags |= QLocalePrivate::ThousandsGroup; break;
5455                 default: no_more_flags = true; break;
5456             }
5457
5458             if (!no_more_flags)
5459                 ++c;
5460         } while (!no_more_flags);
5461
5462         if (*c == '\0') {
5463             result.append(QLatin1String(escape_start)); // incomplete escape, treat as non-escape text
5464             break;
5465         }
5466
5467         // Parse field width
5468         int width = -1; // -1 means unspecified
5469         if (qIsDigit(*c)) {
5470             QString width_str;
5471             while (*c != '\0' && qIsDigit(*c))
5472                 width_str.append(QLatin1Char(*c++));
5473
5474             // can't be negative - started with a digit
5475             // contains at least one digit
5476             width = width_str.toInt();
5477         }
5478         else if (*c == '*') {
5479             width = va_arg(ap, int);
5480             if (width < 0)
5481                 width = -1; // treat all negative numbers as unspecified
5482             ++c;
5483         }
5484
5485         if (*c == '\0') {
5486             result.append(QLatin1String(escape_start)); // incomplete escape, treat as non-escape text
5487             break;
5488         }
5489
5490         // Parse precision
5491         int precision = -1; // -1 means unspecified
5492         if (*c == '.') {
5493             ++c;
5494             if (qIsDigit(*c)) {
5495                 QString precision_str;
5496                 while (*c != '\0' && qIsDigit(*c))
5497                     precision_str.append(QLatin1Char(*c++));
5498
5499                 // can't be negative - started with a digit
5500                 // contains at least one digit
5501                 precision = precision_str.toInt();
5502             }
5503             else if (*c == '*') {
5504                 precision = va_arg(ap, int);
5505                 if (precision < 0)
5506                     precision = -1; // treat all negative numbers as unspecified
5507                 ++c;
5508             }
5509         }
5510
5511         if (*c == '\0') {
5512             result.append(QLatin1String(escape_start)); // incomplete escape, treat as non-escape text
5513             break;
5514         }
5515
5516         // Parse the length modifier
5517         enum LengthMod { lm_none, lm_hh, lm_h, lm_l, lm_ll, lm_L, lm_j, lm_z, lm_t };
5518         LengthMod length_mod = lm_none;
5519         switch (*c) {
5520             case 'h':
5521                 ++c;
5522                 if (*c == 'h') {
5523                     length_mod = lm_hh;
5524                     ++c;
5525                 }
5526                 else
5527                     length_mod = lm_h;
5528                 break;
5529
5530             case 'l':
5531                 ++c;
5532                 if (*c == 'l') {
5533                     length_mod = lm_ll;
5534                     ++c;
5535                 }
5536                 else
5537                     length_mod = lm_l;
5538                 break;
5539
5540             case 'L':
5541                 ++c;
5542                 length_mod = lm_L;
5543                 break;
5544
5545             case 'j':
5546                 ++c;
5547                 length_mod = lm_j;
5548                 break;
5549
5550             case 'z':
5551             case 'Z':
5552                 ++c;
5553                 length_mod = lm_z;
5554                 break;
5555
5556             case 't':
5557                 ++c;
5558                 length_mod = lm_t;
5559                 break;
5560
5561             default: break;
5562         }
5563
5564         if (*c == '\0') {
5565             result.append(QLatin1String(escape_start)); // incomplete escape, treat as non-escape text
5566             break;
5567         }
5568
5569         // Parse the conversion specifier and do the conversion
5570         QString subst;
5571         switch (*c) {
5572             case 'd':
5573             case 'i': {
5574                 qint64 i;
5575                 switch (length_mod) {
5576                     case lm_none: i = va_arg(ap, int); break;
5577                     case lm_hh: i = va_arg(ap, int); break;
5578                     case lm_h: i = va_arg(ap, int); break;
5579                     case lm_l: i = va_arg(ap, long int); break;
5580                     case lm_ll: i = va_arg(ap, qint64); break;
5581                     case lm_j: i = va_arg(ap, long int); break;
5582                     case lm_z: i = va_arg(ap, size_t); break;
5583                     case lm_t: i = va_arg(ap, int); break;
5584                     default: i = 0; break;
5585                 }
5586                 subst = locale.d()->longLongToString(i, precision, 10, width, flags);
5587                 ++c;
5588                 break;
5589             }
5590             case 'o':
5591             case 'u':
5592             case 'x':
5593             case 'X': {
5594                 quint64 u;
5595                 switch (length_mod) {
5596                     case lm_none: u = va_arg(ap, uint); break;
5597                     case lm_hh: u = va_arg(ap, uint); break;
5598                     case lm_h: u = va_arg(ap, uint); break;
5599                     case lm_l: u = va_arg(ap, ulong); break;
5600                     case lm_ll: u = va_arg(ap, quint64); break;
5601                     case lm_z: u = va_arg(ap, size_t); break;
5602                     default: u = 0; break;
5603                 }
5604
5605                 if (qIsUpper(*c))
5606                     flags |= QLocalePrivate::CapitalEorX;
5607
5608                 int base = 10;
5609                 switch (qToLower(*c)) {
5610                     case 'o':
5611                         base = 8; break;
5612                     case 'u':
5613                         base = 10; break;
5614                     case 'x':
5615                         base = 16; break;
5616                     default: break;
5617                 }
5618                 subst = locale.d()->unsLongLongToString(u, precision, base, width, flags);
5619                 ++c;
5620                 break;
5621             }
5622             case 'E':
5623             case 'e':
5624             case 'F':
5625             case 'f':
5626             case 'G':
5627             case 'g':
5628             case 'A':
5629             case 'a': {
5630                 double d;
5631                 if (length_mod == lm_L)
5632                     d = va_arg(ap, long double); // not supported - converted to a double
5633                 else
5634                     d = va_arg(ap, double);
5635
5636                 if (qIsUpper(*c))
5637                     flags |= QLocalePrivate::CapitalEorX;
5638
5639                 QLocalePrivate::DoubleForm form = QLocalePrivate::DFDecimal;
5640                 switch (qToLower(*c)) {
5641                     case 'e': form = QLocalePrivate::DFExponent; break;
5642                     case 'a':                             // not supported - decimal form used instead
5643                     case 'f': form = QLocalePrivate::DFDecimal; break;
5644                     case 'g': form = QLocalePrivate::DFSignificantDigits; break;
5645                     default: break;
5646                 }
5647                 subst = locale.d()->doubleToString(d, precision, form, width, flags);
5648                 ++c;
5649                 break;
5650             }
5651             case 'c': {
5652                 if (length_mod == lm_l)
5653                     subst = QChar((ushort) va_arg(ap, int));
5654                 else
5655                     subst = QLatin1Char((uchar) va_arg(ap, int));
5656                 ++c;
5657                 break;
5658             }
5659             case 's': {
5660                 if (length_mod == lm_l) {
5661                     const ushort *buff = va_arg(ap, const ushort*);
5662                     const ushort *ch = buff;
5663                     while (*ch != 0)
5664                         ++ch;
5665                     subst.setUtf16(buff, ch - buff);
5666                 } else
5667                     subst = QString::fromUtf8(va_arg(ap, const char*));
5668                 if (precision != -1)
5669                     subst.truncate(precision);
5670                 ++c;
5671                 break;
5672             }
5673             case 'p': {
5674                 void *arg = va_arg(ap, void*);
5675 #ifdef Q_OS_WIN64
5676                 quint64 i = reinterpret_cast<quint64>(arg);
5677 #else
5678                 quint64 i = reinterpret_cast<unsigned long>(arg);
5679 #endif
5680                 flags |= QLocalePrivate::Alternate;
5681                 subst = locale.d()->unsLongLongToString(i, precision, 16, width, flags);
5682                 ++c;
5683                 break;
5684             }
5685             case 'n':
5686                 switch (length_mod) {
5687                     case lm_hh: {
5688                         signed char *n = va_arg(ap, signed char*);
5689                         *n = result.length();
5690                         break;
5691                     }
5692                     case lm_h: {
5693                         short int *n = va_arg(ap, short int*);
5694                         *n = result.length();
5695                             break;
5696                     }
5697                     case lm_l: {
5698                         long int *n = va_arg(ap, long int*);
5699                         *n = result.length();
5700                         break;
5701                     }
5702                     case lm_ll: {
5703                         qint64 *n = va_arg(ap, qint64*);
5704                         volatile uint tmp = result.length(); // egcs-2.91.66 gets internal
5705                         *n = tmp;                             // compiler error without volatile
5706                         break;
5707                     }
5708                     default: {
5709                         int *n = va_arg(ap, int*);
5710                         *n = result.length();
5711                         break;
5712                     }
5713                 }
5714                 ++c;
5715                 break;
5716
5717             default: // bad escape, treat as non-escape text
5718                 for (const char *cc = escape_start; cc != c; ++cc)
5719                     result.append(QLatin1Char(*cc));
5720                 continue;
5721         }
5722
5723         if (flags & QLocalePrivate::LeftAdjusted)
5724             result.append(subst.leftJustified(width));
5725         else
5726             result.append(subst.rightJustified(width));
5727     }
5728
5729     *this = result;
5730
5731     return *this;
5732 }
5733
5734 /*!
5735     Returns the string converted to a \c{long long} using base \a
5736     base, which is 10 by default and must be between 2 and 36, or 0.
5737     Returns 0 if the conversion fails.
5738
5739     If a conversion error occurs, *\a{ok} is set to false; otherwise
5740     *\a{ok} is set to true.
5741
5742     If \a base is 0, the C language convention is used: If the string
5743     begins with "0x", base 16 is used; if the string begins with "0",
5744     base 8 is used; otherwise, base 10 is used.
5745
5746     The string conversion will always happen in the 'C' locale. For locale
5747     dependent conversion use QLocale::toLongLong()
5748
5749     Example:
5750
5751     \snippet doc/src/snippets/qstring/main.cpp 74
5752
5753     \sa number(), toULongLong(), toInt(), QLocale::toLongLong()
5754 */
5755
5756 qint64 QString::toLongLong(bool *ok, int base) const
5757 {
5758 #if defined(QT_CHECK_RANGE)
5759     if (base != 0 && (base < 2 || base > 36)) {
5760         qWarning("QString::toLongLong: Invalid base (%d)", base);
5761         base = 10;
5762     }
5763 #endif
5764
5765     QLocale c_locale(QLocale::C);
5766     return c_locale.d()->stringToLongLong(*this, base, ok, QLocalePrivate::FailOnGroupSeparators);
5767 }
5768
5769 /*!
5770     Returns the string converted to an \c{unsigned long long} using base \a
5771     base, which is 10 by default and must be between 2 and 36, or 0.
5772     Returns 0 if the conversion fails.
5773
5774     If a conversion error occurs, *\a{ok} is set to false; otherwise
5775     *\a{ok} is set to true.
5776
5777     If \a base is 0, the C language convention is used: If the string
5778     begins with "0x", base 16 is used; if the string begins with "0",
5779     base 8 is used; otherwise, base 10 is used.
5780
5781     The string conversion will always happen in the 'C' locale. For locale
5782     dependent conversion use QLocale::toULongLong()
5783
5784     Example:
5785
5786     \snippet doc/src/snippets/qstring/main.cpp 79
5787
5788     \sa number(), toLongLong(), QLocale::toULongLong()
5789 */
5790
5791 quint64 QString::toULongLong(bool *ok, int base) const
5792 {
5793 #if defined(QT_CHECK_RANGE)
5794     if (base != 0 && (base < 2 || base > 36)) {
5795         qWarning("QString::toULongLong: Invalid base (%d)", base);
5796         base = 10;
5797     }
5798 #endif
5799
5800     QLocale c_locale(QLocale::C);
5801     return c_locale.d()->stringToUnsLongLong(*this, base, ok, QLocalePrivate::FailOnGroupSeparators);
5802 }
5803
5804 /*!
5805     \fn long QString::toLong(bool *ok, int base) const
5806
5807     Returns the string converted to a \c long using base \a
5808     base, which is 10 by default and must be between 2 and 36, or 0.
5809     Returns 0 if the conversion fails.
5810
5811     If a conversion error occurs, *\a{ok} is set to false; otherwise
5812     *\a{ok} is set to true.
5813
5814     If \a base is 0, the C language convention is used: If the string
5815     begins with "0x", base 16 is used; if the string begins with "0",
5816     base 8 is used; otherwise, base 10 is used.
5817
5818     The string conversion will always happen in the 'C' locale. For locale
5819     dependent conversion use QLocale::toLong()
5820
5821     Example:
5822
5823     \snippet doc/src/snippets/qstring/main.cpp 73
5824
5825     \sa number(), toULong(), toInt(), QLocale::toLong()
5826 */
5827
5828 long QString::toLong(bool *ok, int base) const
5829 {
5830     qint64 v = toLongLong(ok, base);
5831     if (v < LONG_MIN || v > LONG_MAX) {
5832         if (ok)
5833             *ok = false;
5834         v = 0;
5835     }
5836     return (long)v;
5837 }
5838
5839 /*!
5840     \fn ulong QString::toULong(bool *ok, int base) const
5841
5842     Returns the string converted to an \c{unsigned long} using base \a
5843     base, which is 10 by default and must be between 2 and 36, or 0.
5844     Returns 0 if the conversion fails.
5845
5846     If a conversion error occurs, *\a{ok} is set to false; otherwise
5847     *\a{ok} is set to true.
5848
5849     If \a base is 0, the C language convention is used: If the string
5850     begins with "0x", base 16 is used; if the string begins with "0",
5851     base 8 is used; otherwise, base 10 is used.
5852
5853     The string conversion will always happen in the 'C' locale. For locale
5854     dependent conversion use QLocale::toULong()
5855
5856     Example:
5857
5858     \snippet doc/src/snippets/qstring/main.cpp 78
5859
5860     \sa number(), QLocale::toULong()
5861 */
5862
5863 ulong QString::toULong(bool *ok, int base) const
5864 {
5865     quint64 v = toULongLong(ok, base);
5866     if (v > ULONG_MAX) {
5867         if (ok)
5868             *ok = false;
5869         v = 0;
5870     }
5871     return (ulong)v;
5872 }
5873
5874
5875 /*!
5876     Returns the string converted to an \c int using base \a
5877     base, which is 10 by default and must be between 2 and 36, or 0.
5878     Returns 0 if the conversion fails.
5879
5880     If a conversion error occurs, *\a{ok} is set to false; otherwise
5881     *\a{ok} is set to true.
5882
5883     If \a base is 0, the C language convention is used: If the string
5884     begins with "0x", base 16 is used; if the string begins with "0",
5885     base 8 is used; otherwise, base 10 is used.
5886
5887     The string conversion will always happen in the 'C' locale. For locale
5888     dependent conversion use QLocale::toInt()
5889
5890     Example:
5891
5892     \snippet doc/src/snippets/qstring/main.cpp 72
5893
5894     \sa number(), toUInt(), toDouble(), QLocale::toInt()
5895 */
5896
5897 int QString::toInt(bool *ok, int base) const
5898 {
5899     qint64 v = toLongLong(ok, base);
5900     if (v < INT_MIN || v > INT_MAX) {
5901         if (ok)
5902             *ok = false;
5903         v = 0;
5904     }
5905     return v;
5906 }
5907
5908 /*!
5909     Returns the string converted to an \c{unsigned int} using base \a
5910     base, which is 10 by default and must be between 2 and 36, or 0.
5911     Returns 0 if the conversion fails.
5912
5913     If a conversion error occurs, *\a{ok} is set to false; otherwise
5914     *\a{ok} is set to true.
5915
5916     If \a base is 0, the C language convention is used: If the string
5917     begins with "0x", base 16 is used; if the string begins with "0",
5918     base 8 is used; otherwise, base 10 is used.
5919
5920     The string conversion will always happen in the 'C' locale. For locale
5921     dependent conversion use QLocale::toUInt()
5922
5923     Example:
5924
5925     \snippet doc/src/snippets/qstring/main.cpp 77
5926
5927     \sa number(), toInt(), QLocale::toUInt()
5928 */
5929
5930 uint QString::toUInt(bool *ok, int base) const
5931 {
5932     quint64 v = toULongLong(ok, base);
5933     if (v > UINT_MAX) {
5934         if (ok)
5935             *ok = false;
5936         v = 0;
5937     }
5938     return (uint)v;
5939 }
5940
5941 /*!
5942     Returns the string converted to a \c short using base \a
5943     base, which is 10 by default and must be between 2 and 36, or 0.
5944     Returns 0 if the conversion fails.
5945
5946     If a conversion error occurs, *\a{ok} is set to false; otherwise
5947     *\a{ok} is set to true.
5948
5949     If \a base is 0, the C language convention is used: If the string
5950     begins with "0x", base 16 is used; if the string begins with "0",
5951     base 8 is used; otherwise, base 10 is used.
5952
5953     The string conversion will always happen in the 'C' locale. For locale
5954     dependent conversion use QLocale::toShort()
5955
5956     Example:
5957
5958     \snippet doc/src/snippets/qstring/main.cpp 76
5959
5960     \sa number(), toUShort(), toInt(), QLocale::toShort()
5961 */
5962
5963 short QString::toShort(bool *ok, int base) const
5964 {
5965     long v = toLongLong(ok, base);
5966     if (v < SHRT_MIN || v > SHRT_MAX) {
5967         if (ok)
5968             *ok = false;
5969         v = 0;
5970     }
5971     return (short)v;
5972 }
5973
5974 /*!
5975     Returns the string converted to an \c{unsigned short} using base \a
5976     base, which is 10 by default and must be between 2 and 36, or 0.
5977     Returns 0 if the conversion fails.
5978
5979     If a conversion error occurs, *\a{ok} is set to false; otherwise
5980     *\a{ok} is set to true.
5981
5982     If \a base is 0, the C language convention is used: If the string
5983     begins with "0x", base 16 is used; if the string begins with "0",
5984     base 8 is used; otherwise, base 10 is used.
5985
5986     The string conversion will always happen in the 'C' locale. For locale
5987     dependent conversion use QLocale::toUShort()
5988
5989     Example:
5990
5991     \snippet doc/src/snippets/qstring/main.cpp 80
5992
5993     \sa number(), toShort(), QLocale::toUShort()
5994 */
5995
5996 ushort QString::toUShort(bool *ok, int base) const
5997 {
5998     ulong v = toULongLong(ok, base);
5999     if (v > USHRT_MAX) {
6000         if (ok)
6001             *ok = false;
6002         v = 0;
6003     }
6004     return (ushort)v;
6005 }
6006
6007
6008 /*!
6009     Returns the string converted to a \c double value.
6010
6011     Returns 0.0 if the conversion fails.
6012
6013     If a conversion error occurs, \c{*}\a{ok} is set to false;
6014     otherwise \c{*}\a{ok} is set to true.
6015
6016     \snippet doc/src/snippets/qstring/main.cpp 66
6017
6018     Various string formats for floating point numbers can be converted
6019     to double values:
6020
6021     \snippet doc/src/snippets/qstring/main.cpp 67
6022
6023     The string conversion will always happen in the 'C' locale. For locale
6024     dependent conversion use QLocale::toDouble()
6025
6026     \snippet doc/src/snippets/qstring/main.cpp 68
6027
6028     For historic reasons, this function does not handle
6029     thousands group separators. If you need to convert such numbers,
6030     use QLocale::toDouble().
6031
6032     \snippet doc/src/snippets/qstring/main.cpp 69
6033
6034     \sa number() QLocale::setDefault() QLocale::toDouble() trimmed()
6035 */
6036
6037 double QString::toDouble(bool *ok) const
6038 {
6039     QLocale c_locale(QLocale::C);
6040     return c_locale.d()->stringToDouble(*this, ok, QLocalePrivate::FailOnGroupSeparators);
6041 }
6042
6043 /*!
6044     Returns the string converted to a \c float value.
6045
6046     If a conversion error occurs, *\a{ok} is set to false; otherwise
6047     *\a{ok} is set to true. Returns 0.0 if the conversion fails.
6048
6049     The string conversion will always happen in the 'C' locale. For locale
6050     dependent conversion use QLocale::toFloat()
6051
6052     Example:
6053
6054     \snippet doc/src/snippets/qstring/main.cpp 71
6055
6056     \sa number(), toDouble(), toInt(), QLocale::toFloat()
6057 */
6058
6059 #define QT_MAX_FLOAT 3.4028234663852886e+38
6060
6061 float QString::toFloat(bool *ok) const
6062 {
6063     bool myOk;
6064     double d = toDouble(&myOk);
6065     if (!myOk || d > QT_MAX_FLOAT || d < -QT_MAX_FLOAT) {
6066         if (ok != 0)
6067             *ok = false;
6068         return 0.0;
6069     }
6070     if (ok != 0)
6071         *ok = true;
6072     return (float) d;
6073 }
6074
6075 /*! \fn QString &QString::setNum(int n, int base)
6076
6077     Sets the string to the printed value of \a n in the specified \a
6078     base, and returns a reference to the string.
6079
6080     The base is 10 by default and must be between 2 and 36. For bases
6081     other than 10, \a n is treated as an unsigned integer.
6082
6083     \snippet doc/src/snippets/qstring/main.cpp 56
6084
6085    The formatting always uses QLocale::C, i.e., English/UnitedStates.
6086    To get a localized string representation of a number, use
6087    QLocale::toString() with the appropriate locale.
6088 */
6089
6090 /*! \fn QString &QString::setNum(uint n, int base)
6091
6092     \overload
6093 */
6094
6095 /*! \fn QString &QString::setNum(long n, int base)
6096
6097     \overload
6098 */
6099
6100 /*! \fn QString &QString::setNum(ulong n, int base)
6101
6102     \overload
6103 */
6104
6105 /*!
6106     \overload
6107 */
6108 QString &QString::setNum(qlonglong n, int base)
6109 {
6110 #if defined(QT_CHECK_RANGE)
6111     if (base < 2 || base > 36) {
6112         qWarning("QString::setNum: Invalid base (%d)", base);
6113         base = 10;
6114     }
6115 #endif
6116     QLocale locale(QLocale::C);
6117     *this = locale.d()->longLongToString(n, -1, base);
6118     return *this;
6119 }
6120
6121 /*!
6122     \overload
6123 */
6124 QString &QString::setNum(qulonglong n, int base)
6125 {
6126 #if defined(QT_CHECK_RANGE)
6127     if (base < 2 || base > 36) {
6128         qWarning("QString::setNum: Invalid base (%d)", base);
6129         base = 10;
6130     }
6131 #endif
6132     QLocale locale(QLocale::C);
6133     *this = locale.d()->unsLongLongToString(n, -1, base);
6134     return *this;
6135 }
6136
6137 /*! \fn QString &QString::setNum(short n, int base)
6138
6139     \overload
6140 */
6141
6142 /*! \fn QString &QString::setNum(ushort n, int base)
6143
6144     \overload
6145 */
6146
6147 /*!
6148     \fn QString &QString::setNum(double n, char format, int precision)
6149     \overload
6150
6151     Sets the string to the printed value of \a n, formatted according
6152     to the given \a format and \a precision, and returns a reference
6153     to the string.
6154
6155     The \a format can be 'f', 'F', 'e', 'E', 'g' or 'G' (see the
6156     arg() function documentation for an explanation of the formats).
6157
6158     The formatting always uses QLocale::C, i.e., English/UnitedStates.
6159     To get a localized string representation of a number, use
6160     QLocale::toString() with the appropriate locale.
6161 */
6162
6163 QString &QString::setNum(double n, char f, int prec)
6164 {
6165     QLocalePrivate::DoubleForm form = QLocalePrivate::DFDecimal;
6166     uint flags = 0;
6167
6168     if (qIsUpper(f))
6169         flags = QLocalePrivate::CapitalEorX;
6170     f = qToLower(f);
6171
6172     switch (f) {
6173         case 'f':
6174             form = QLocalePrivate::DFDecimal;
6175             break;
6176         case 'e':
6177             form = QLocalePrivate::DFExponent;
6178             break;
6179         case 'g':
6180             form = QLocalePrivate::DFSignificantDigits;
6181             break;
6182         default:
6183 #if defined(QT_CHECK_RANGE)
6184             qWarning("QString::setNum: Invalid format char '%c'", f);
6185 #endif
6186             break;
6187     }
6188
6189     QLocale locale(QLocale::C);
6190     *this = locale.d()->doubleToString(n, prec, form, -1, flags);
6191     return *this;
6192 }
6193
6194 /*!
6195     \fn QString &QString::setNum(float n, char format, int precision)
6196     \overload
6197
6198     Sets the string to the printed value of \a n, formatted according
6199     to the given \a format and \a precision, and returns a reference
6200     to the string.
6201
6202     The formatting always uses QLocale::C, i.e., English/UnitedStates.
6203     To get a localized string representation of a number, use
6204     QLocale::toString() with the appropriate locale.
6205 */
6206
6207
6208 /*!
6209     \fn QString QString::number(long n, int base)
6210
6211     Returns a string equivalent of the number \a n according to the
6212     specified \a base.
6213
6214     The base is 10 by default and must be between 2
6215     and 36. For bases other than 10, \a n is treated as an
6216     unsigned integer.
6217
6218     The formatting always uses QLocale::C, i.e., English/UnitedStates.
6219     To get a localized string representation of a number, use
6220     QLocale::toString() with the appropriate locale.
6221
6222     \snippet doc/src/snippets/qstring/main.cpp 35
6223
6224     \sa setNum()
6225 */
6226
6227 QString QString::number(long n, int base)
6228 {
6229     QString s;
6230     s.setNum(n, base);
6231     return s;
6232 }
6233
6234 /*!
6235   \fn QString QString::number(ulong n, int base)
6236
6237     \overload
6238 */
6239 QString QString::number(ulong n, int base)
6240 {
6241     QString s;
6242     s.setNum(n, base);
6243     return s;
6244 }
6245
6246 /*!
6247     \overload
6248 */
6249 QString QString::number(int n, int base)
6250 {
6251     QString s;
6252     s.setNum(n, base);
6253     return s;
6254 }
6255
6256 /*!
6257     \overload
6258 */
6259 QString QString::number(uint n, int base)
6260 {
6261     QString s;
6262     s.setNum(n, base);
6263     return s;
6264 }
6265
6266 /*!
6267     \overload
6268 */
6269 QString QString::number(qlonglong n, int base)
6270 {
6271     QString s;
6272     s.setNum(n, base);
6273     return s;
6274 }
6275
6276 /*!
6277     \overload
6278 */
6279 QString QString::number(qulonglong n, int base)
6280 {
6281     QString s;
6282     s.setNum(n, base);
6283     return s;
6284 }
6285
6286
6287 /*!
6288     \fn QString QString::number(double n, char format, int precision)
6289
6290     Returns a string equivalent of the number \a n, formatted
6291     according to the specified \a format and \a precision. See
6292     \l{Argument Formats} for details.
6293
6294     Unlike QLocale::toString(), this function does not honor the
6295     user's locale settings.
6296
6297     \sa setNum(), QLocale::toString()
6298 */
6299 QString QString::number(double n, char f, int prec)
6300 {
6301     QString s;
6302     s.setNum(n, f, prec);
6303     return s;
6304 }
6305
6306 /*!
6307     Splits the string into substrings wherever \a sep occurs, and
6308     returns the list of those strings. If \a sep does not match
6309     anywhere in the string, split() returns a single-element list
6310     containing this string.
6311
6312     \a cs specifies whether \a sep should be matched case
6313     sensitively or case insensitively.
6314
6315     If \a behavior is QString::SkipEmptyParts, empty entries don't
6316     appear in the result. By default, empty entries are kept.
6317
6318     Example:
6319
6320     \snippet doc/src/snippets/qstring/main.cpp 62
6321
6322     \sa QStringList::join(), section()
6323 */
6324 QStringList QString::split(const QString &sep, SplitBehavior behavior, Qt::CaseSensitivity cs) const
6325 {
6326     QStringList list;
6327     int start = 0;
6328     int extra = 0;
6329     int end;
6330     while ((end = indexOf(sep, start + extra, cs)) != -1) {
6331         if (start != end || behavior == KeepEmptyParts)
6332             list.append(mid(start, end - start));
6333         start = end + sep.size();
6334         extra = (sep.size() == 0 ? 1 : 0);
6335     }
6336     if (start != size() || behavior == KeepEmptyParts)
6337         list.append(mid(start));
6338     return list;
6339 }
6340
6341 /*!
6342     \overload
6343 */
6344 QStringList QString::split(QChar sep, SplitBehavior behavior, Qt::CaseSensitivity cs) const
6345 {
6346     QStringList list;
6347     int start = 0;
6348     int end;
6349     while ((end = indexOf(sep, start, cs)) != -1) {
6350         if (start != end || behavior == KeepEmptyParts)
6351             list.append(mid(start, end - start));
6352         start = end + 1;
6353     }
6354     if (start != size() || behavior == KeepEmptyParts)
6355         list.append(mid(start));
6356     return list;
6357 }
6358
6359 #ifndef QT_NO_REGEXP
6360 /*!
6361     \overload
6362
6363     Splits the string into substrings wherever the regular expression
6364     \a rx matches, and returns the list of those strings. If \a rx
6365     does not match anywhere in the string, split() returns a
6366     single-element list containing this string.
6367
6368     Here's an example where we extract the words in a sentence
6369     using one or more whitespace characters as the separator:
6370
6371     \snippet doc/src/snippets/qstring/main.cpp 59
6372
6373     Here's a similar example, but this time we use any sequence of
6374     non-word characters as the separator:
6375
6376     \snippet doc/src/snippets/qstring/main.cpp 60
6377
6378     Here's a third example where we use a zero-length assertion,
6379     \b{\\b} (word boundary), to split the string into an
6380     alternating sequence of non-word and word tokens:
6381
6382     \snippet doc/src/snippets/qstring/main.cpp 61
6383
6384     \sa QStringList::join(), section()
6385 */
6386 QStringList QString::split(const QRegExp &rx, SplitBehavior behavior) const
6387 {
6388     QRegExp rx2(rx);
6389     QStringList list;
6390     int start = 0;
6391     int extra = 0;
6392     int end;
6393     while ((end = rx2.indexIn(*this, start + extra)) != -1) {
6394         int matchedLen = rx2.matchedLength();
6395         if (start != end || behavior == KeepEmptyParts)
6396             list.append(mid(start, end - start));
6397         start = end + matchedLen;
6398         extra = (matchedLen == 0) ? 1 : 0;
6399     }
6400     if (start != size() || behavior == KeepEmptyParts)
6401         list.append(mid(start));
6402     return list;
6403 }
6404 #endif
6405
6406 #ifndef QT_NO_REGEXP
6407 #ifndef QT_BOOTSTRAPPED
6408 /*!
6409     \overload
6410     \since 5.0
6411
6412     Splits the string into substrings wherever the regular expression
6413     \a re matches, and returns the list of those strings. If \a re
6414     does not match anywhere in the string, split() returns a
6415     single-element list containing this string.
6416
6417     Here's an example where we extract the words in a sentence
6418     using one or more whitespace characters as the separator:
6419
6420     \snippet doc/src/snippets/qstring/main.cpp 90
6421
6422     Here's a similar example, but this time we use any sequence of
6423     non-word characters as the separator:
6424
6425     \snippet doc/src/snippets/qstring/main.cpp 91
6426
6427     Here's a third example where we use a zero-length assertion,
6428     \bold{\\b} (word boundary), to split the string into an
6429     alternating sequence of non-word and word tokens:
6430
6431     \snippet doc/src/snippets/qstring/main.cpp 92
6432
6433     \sa QStringList::join(), section()
6434 */
6435 QStringList QString::split(const QRegularExpression &re, SplitBehavior behavior) const
6436 {
6437     QStringList list;
6438     if (!re.isValid()) {
6439         qWarning("QString::split: invalid QRegularExpression object");
6440         return list;
6441     }
6442
6443     int start = 0;
6444     int end = 0;
6445     QRegularExpressionMatchIterator iterator = re.globalMatch(*this);
6446     while (iterator.hasNext()) {
6447         QRegularExpressionMatch match = iterator.next();
6448         end = match.capturedStart();
6449         if (start != end || behavior == KeepEmptyParts)
6450             list.append(mid(start, end - start));
6451         start = match.capturedEnd();
6452     }
6453
6454     if (start != size() || behavior == KeepEmptyParts)
6455         list.append(mid(start));
6456
6457     return list;
6458 }
6459 #endif // QT_BOOTSTRAPPED
6460 #endif // QT_NO_REGEXP
6461
6462 /*!
6463     \enum QString::NormalizationForm
6464
6465     This enum describes the various normalized forms of Unicode text.
6466
6467     \value NormalizationForm_D  Canonical Decomposition
6468     \value NormalizationForm_C  Canonical Decomposition followed by Canonical Composition
6469     \value NormalizationForm_KD  Compatibility Decomposition
6470     \value NormalizationForm_KC  Compatibility Decomposition followed by Canonical Composition
6471
6472     \sa normalized(),
6473         {http://www.unicode.org/reports/tr15/}{Unicode Standard Annex #15}
6474 */
6475
6476 /*!
6477     \fn QString QString::normalized(NormalizationForm mode) const
6478     Returns the string in the given Unicode normalization \a mode.
6479 */
6480 QString QString::normalized(QString::NormalizationForm mode) const
6481 {
6482     return normalized(mode, UNICODE_DATA_VERSION);
6483 }
6484
6485 /*!
6486     \since 4.5
6487
6488     Returns a copy of this string repeated the specified number of \a times.
6489
6490     If \a times is less than 1, an empty string is returned.
6491
6492     Example:
6493
6494     \code
6495         QString str("ab");
6496         str.repeated(4);            // returns "abababab"
6497     \endcode
6498 */
6499 QString QString::repeated(int times) const
6500 {
6501     if (d->size == 0)
6502         return *this;
6503
6504     if (times <= 1) {
6505         if (times == 1)
6506             return *this;
6507         return QString();
6508     }
6509
6510     const int resultSize = times * d->size;
6511
6512     QString result;
6513     result.reserve(resultSize);
6514     if (int(result.d->alloc) != resultSize)
6515         return QString(); // not enough memory
6516
6517     memcpy(result.d->data(), d->data(), d->size * sizeof(ushort));
6518
6519     int sizeSoFar = d->size;
6520     ushort *end = result.d->data() + sizeSoFar;
6521
6522     const int halfResultSize = resultSize >> 1;
6523     while (sizeSoFar <= halfResultSize) {
6524         memcpy(end, result.d->data(), sizeSoFar * sizeof(ushort));
6525         end += sizeSoFar;
6526         sizeSoFar <<= 1;
6527     }
6528     memcpy(end, result.d->data(), (resultSize - sizeSoFar) * sizeof(ushort));
6529     result.d->data()[resultSize] = '\0';
6530     result.d->size = resultSize;
6531     return result;
6532 }
6533
6534 void qt_string_normalize(QString *data, QString::NormalizationForm mode, QChar::UnicodeVersion version, int from);
6535 /*!
6536     \overload
6537     \fn QString QString::normalized(NormalizationForm mode, QChar::UnicodeVersion version) const
6538
6539     Returns the string in the given Unicode normalization \a mode,
6540     according to the given \a version of the Unicode standard.
6541 */
6542 QString QString::normalized(QString::NormalizationForm mode, QChar::UnicodeVersion version) const
6543 {
6544     QString copy = *this;
6545     qt_string_normalize(&copy, mode, version, 0);
6546     return copy;
6547 }
6548
6549 void qt_string_normalize(QString *data, QString::NormalizationForm mode, QChar::UnicodeVersion version, int from)
6550 {
6551     bool simple = true;
6552     const QChar *p = data->constData();
6553     int len = data->length();
6554     for (int i = from; i < len; ++i) {
6555         if (p[i].unicode() >= 0x80) {
6556             simple = false;
6557             break;
6558         }
6559     }
6560     if (simple)
6561         return;
6562
6563     if (version == QChar::Unicode_Unassigned) {
6564         version = UNICODE_DATA_VERSION;
6565     } else if (version != UNICODE_DATA_VERSION) {
6566         const QString &s = *data;
6567         QChar *d = 0;
6568         for (int i = 0; i < NumNormalizationCorrections; ++i) {
6569             const NormalizationCorrection &n = uc_normalization_corrections[i];
6570             if (n.version > version) {
6571                 int pos = from;
6572                 if (QChar::requiresSurrogates(n.ucs4)) {
6573                     ushort ucs4High = QChar::highSurrogate(n.ucs4);
6574                     ushort ucs4Low = QChar::lowSurrogate(n.ucs4);
6575                     ushort oldHigh = QChar::highSurrogate(n.old_mapping);
6576                     ushort oldLow = QChar::lowSurrogate(n.old_mapping);
6577                     while (pos < s.length() - 1) {
6578                         if (s.at(pos).unicode() == ucs4High && s.at(pos + 1).unicode() == ucs4Low) {
6579                             if (!d)
6580                                 d = data->data();
6581                             d[pos] = QChar(oldHigh);
6582                             d[++pos] = QChar(oldLow);
6583                         }
6584                         ++pos;
6585                     }
6586                 } else {
6587                     while (pos < s.length()) {
6588                         if (s.at(pos).unicode() == n.ucs4) {
6589                             if (!d)
6590                                 d = data->data();
6591                             d[pos] = QChar(n.old_mapping);
6592                         }
6593                         ++pos;
6594                     }
6595                 }
6596             }
6597         }
6598     }
6599     decomposeHelper(data, mode < QString::NormalizationForm_KD, version, from);
6600
6601     canonicalOrderHelper(data, version, from);
6602
6603     if (mode == QString::NormalizationForm_D || mode == QString::NormalizationForm_KD)
6604         return;
6605
6606     composeHelper(data, version, from);
6607 }
6608
6609
6610 struct ArgEscapeData
6611 {
6612     int min_escape;            // lowest escape sequence number
6613     int occurrences;           // number of occurrences of the lowest escape sequence number
6614     int locale_occurrences;    // number of occurrences of the lowest escape sequence number that
6615                                // contain 'L'
6616     int escape_len;            // total length of escape sequences which will be replaced
6617 };
6618
6619 static ArgEscapeData findArgEscapes(const QString &s)
6620 {
6621     const QChar *uc_begin = s.unicode();
6622     const QChar *uc_end = uc_begin + s.length();
6623
6624     ArgEscapeData d;
6625
6626     d.min_escape = INT_MAX;
6627     d.occurrences = 0;
6628     d.escape_len = 0;
6629     d.locale_occurrences = 0;
6630
6631     const QChar *c = uc_begin;
6632     while (c != uc_end) {
6633         while (c != uc_end && c->unicode() != '%')
6634             ++c;
6635
6636         if (c == uc_end)
6637             break;
6638         const QChar *escape_start = c;
6639         if (++c == uc_end)
6640             break;
6641
6642         bool locale_arg = false;
6643         if (c->unicode() == 'L') {
6644             locale_arg = true;
6645             if (++c == uc_end)
6646                 break;
6647         }
6648
6649         if (c->digitValue() == -1)
6650             continue;
6651
6652         int escape = c->digitValue();
6653         ++c;
6654
6655         if (c != uc_end && c->digitValue() != -1) {
6656             escape = (10 * escape) + c->digitValue();
6657             ++c;
6658         }
6659
6660         if (escape > d.min_escape)
6661             continue;
6662
6663         if (escape < d.min_escape) {
6664             d.min_escape = escape;
6665             d.occurrences = 0;
6666             d.escape_len = 0;
6667             d.locale_occurrences = 0;
6668         }
6669
6670         ++d.occurrences;
6671         if (locale_arg)
6672             ++d.locale_occurrences;
6673         d.escape_len += c - escape_start;
6674     }
6675     return d;
6676 }
6677
6678 static QString replaceArgEscapes(const QString &s, const ArgEscapeData &d, int field_width,
6679                                  const QString &arg, const QString &larg, QChar fillChar = QLatin1Char(' '))
6680 {
6681     const QChar *uc_begin = s.unicode();
6682     const QChar *uc_end = uc_begin + s.length();
6683
6684     int abs_field_width = qAbs(field_width);
6685     int result_len = s.length()
6686                      - d.escape_len
6687                      + (d.occurrences - d.locale_occurrences)
6688                      *qMax(abs_field_width, arg.length())
6689                      + d.locale_occurrences
6690                      *qMax(abs_field_width, larg.length());
6691
6692     QString result(result_len, Qt::Uninitialized);
6693     QChar *result_buff = (QChar*) result.unicode();
6694
6695     QChar *rc = result_buff;
6696     const QChar *c = uc_begin;
6697     int repl_cnt = 0;
6698     while (c != uc_end) {
6699         /* We don't have to check if we run off the end of the string with c,
6700            because as long as d.occurrences > 0 we KNOW there are valid escape
6701            sequences. */
6702
6703         const QChar *text_start = c;
6704
6705         while (c->unicode() != '%')
6706             ++c;
6707
6708         const QChar *escape_start = c++;
6709
6710         bool locale_arg = false;
6711         if (c->unicode() == 'L') {
6712             locale_arg = true;
6713             ++c;
6714         }
6715
6716         int escape = c->digitValue();
6717         if (escape != -1) {
6718             if (c + 1 != uc_end && (c + 1)->digitValue() != -1) {
6719                 escape = (10 * escape) + (c + 1)->digitValue();
6720                 ++c;
6721             }
6722         }
6723
6724         if (escape != d.min_escape) {
6725             memcpy(rc, text_start, (c - text_start)*sizeof(QChar));
6726             rc += c - text_start;
6727         }
6728         else {
6729             ++c;
6730
6731             memcpy(rc, text_start, (escape_start - text_start)*sizeof(QChar));
6732             rc += escape_start - text_start;
6733
6734             uint pad_chars;
6735             if (locale_arg)
6736                 pad_chars = qMax(abs_field_width, larg.length()) - larg.length();
6737             else
6738                 pad_chars = qMax(abs_field_width, arg.length()) - arg.length();
6739
6740             if (field_width > 0) { // left padded
6741                 for (uint i = 0; i < pad_chars; ++i)
6742                     (rc++)->unicode() = fillChar.unicode();
6743             }
6744
6745             if (locale_arg) {
6746                 memcpy(rc, larg.unicode(), larg.length()*sizeof(QChar));
6747                 rc += larg.length();
6748             }
6749             else {
6750                 memcpy(rc, arg.unicode(), arg.length()*sizeof(QChar));
6751                 rc += arg.length();
6752             }
6753
6754             if (field_width < 0) { // right padded
6755                 for (uint i = 0; i < pad_chars; ++i)
6756                     (rc++)->unicode() = fillChar.unicode();
6757             }
6758
6759             if (++repl_cnt == d.occurrences) {
6760                 memcpy(rc, c, (uc_end - c)*sizeof(QChar));
6761                 rc += uc_end - c;
6762                 Q_ASSERT(rc - result_buff == result_len);
6763                 c = uc_end;
6764             }
6765         }
6766     }
6767     Q_ASSERT(rc == result_buff + result_len);
6768
6769     return result;
6770 }
6771
6772 /*!
6773   Returns a copy of this string with the lowest numbered place marker
6774   replaced by string \a a, i.e., \c %1, \c %2, ..., \c %99.
6775
6776   \a fieldWidth specifies the minimum amount of space that argument \a
6777   a shall occupy. If \a a requires less space than \a fieldWidth, it
6778   is padded to \a fieldWidth with character \a fillChar.  A positive
6779   \a fieldWidth produces right-aligned text. A negative \a fieldWidth
6780   produces left-aligned text.
6781
6782   This example shows how we might create a \c status string for
6783   reporting progress while processing a list of files:
6784
6785   \snippet doc/src/snippets/qstring/main.cpp 11
6786
6787   First, \c arg(i) replaces \c %1. Then \c arg(total) replaces \c
6788   %2. Finally, \c arg(fileName) replaces \c %3.
6789
6790   One advantage of using arg() over sprintf() is that the order of the
6791   numbered place markers can change, if the application's strings are
6792   translated into other languages, but each arg() will still replace
6793   the lowest numbered unreplaced place marker, no matter where it
6794   appears. Also, if place marker \c %i appears more than once in the
6795   string, the arg() replaces all of them.
6796
6797   If there is no unreplaced place marker remaining, a warning message
6798   is output and the result is undefined. Place marker numbers must be
6799   in the range 1 to 99.
6800 */
6801 QString QString::arg(const QString &a, int fieldWidth, QChar fillChar) const
6802 {
6803     ArgEscapeData d = findArgEscapes(*this);
6804
6805     if (d.occurrences == 0) {
6806         qWarning("QString::arg: Argument missing: %s, %s", toLocal8Bit().data(),
6807                   a.toLocal8Bit().data());
6808         return *this;
6809     }
6810     return replaceArgEscapes(*this, d, fieldWidth, a, a, fillChar);
6811 }
6812
6813 /*!
6814   \fn QString QString::arg(const QString& a1, const QString& a2) const
6815   \overload arg()
6816
6817   This is the same as \c {str.arg(a1).arg(a2)}, except that the
6818   strings \a a1 and \a a2 are replaced in one pass. This can make a
6819   difference if \a a1 contains e.g. \c{%1}:
6820
6821   \snippet doc/src/snippets/qstring/main.cpp 13
6822 */
6823
6824 /*!
6825   \fn QString QString::arg(const QString& a1, const QString& a2, const QString& a3) const
6826   \overload arg()
6827
6828   This is the same as calling \c str.arg(a1).arg(a2).arg(a3), except
6829   that the strings \a a1, \a a2 and \a a3 are replaced in one pass.
6830 */
6831
6832 /*!
6833   \fn QString QString::arg(const QString& a1, const QString& a2, const QString& a3, const QString& a4) const
6834   \overload arg()
6835
6836   This is the same as calling \c
6837   {str.arg(a1).arg(a2).arg(a3).arg(a4)}, except that the strings \a
6838   a1, \a a2, \a a3 and \a a4 are replaced in one pass.
6839 */
6840
6841 /*!
6842   \fn QString QString::arg(const QString& a1, const QString& a2, const QString& a3, const QString& a4, const QString& a5) const
6843   \overload arg()
6844
6845   This is the same as calling \c
6846   {str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5)}, except that the strings
6847   \a a1, \a a2, \a a3, \a a4, and \a a5 are replaced in one pass.
6848 */
6849
6850 /*!
6851   \fn QString QString::arg(const QString& a1, const QString& a2, const QString& a3, const QString& a4, const QString& a5, const QString& a6) const
6852   \overload arg()
6853
6854   This is the same as calling \c
6855   {str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6))}, except that
6856   the strings \a a1, \a a2, \a a3, \a a4, \a a5, and \a a6 are
6857   replaced in one pass.
6858 */
6859
6860 /*!
6861   \fn QString QString::arg(const QString& a1, const QString& a2, const QString& a3, const QString& a4, const QString& a5, const QString& a6, const QString& a7) const
6862   \overload arg()
6863
6864   This is the same as calling \c
6865   {str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6).arg(a7)},
6866   except that the strings \a a1, \a a2, \a a3, \a a4, \a a5, \a a6,
6867   and \a a7 are replaced in one pass.
6868 */
6869
6870 /*!
6871   \fn QString QString::arg(const QString& a1, const QString& a2, const QString& a3, const QString& a4, const QString& a5, const QString& a6, const QString& a7, const QString& a8) const
6872   \overload arg()
6873
6874   This is the same as calling \c
6875   {str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6).arg(a7).arg(a8)},
6876   except that the strings \a a1, \a a2, \a a3, \a a4, \a a5, \a a6, \a
6877   a7, and \a a8 are replaced in one pass.
6878 */
6879
6880 /*!
6881   \fn QString QString::arg(const QString& a1, const QString& a2, const QString& a3, const QString& a4, const QString& a5, const QString& a6, const QString& a7, const QString& a8, const QString& a9) const
6882   \overload arg()
6883
6884   This is the same as calling \c
6885   {str.arg(a1).arg(a2).arg(a3).arg(a4).arg(a5).arg(a6).arg(a7).arg(a8).arg(a9)},
6886   except that the strings \a a1, \a a2, \a a3, \a a4, \a a5, \a a6, \a
6887   a7, \a a8, and \a a9 are replaced in one pass.
6888 */
6889
6890 /*! \fn QString QString::arg(int a, int fieldWidth, int base, QChar fillChar) const
6891   \overload arg()
6892
6893   The \a a argument is expressed in base \a base, which is 10 by
6894   default and must be between 2 and 36. For bases other than 10, \a a
6895   is treated as an unsigned integer.
6896
6897   \a fieldWidth specifies the minimum amount of space that \a a is
6898   padded to and filled with the character \a fillChar. A positive
6899   value produces right-aligned text; a negative value produces
6900   left-aligned text.
6901
6902   The '%' can be followed by an 'L', in which case the sequence is
6903   replaced with a localized representation of \a a. The conversion
6904   uses the default locale, set by QLocale::setDefault(). If no default
6905   locale was specified, the "C" locale is used. The 'L' flag is
6906   ignored if \a base is not 10.
6907
6908   \snippet doc/src/snippets/qstring/main.cpp 12
6909   \snippet doc/src/snippets/qstring/main.cpp 14
6910
6911   If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6912   used. For negative numbers, zero padding might appear before the
6913   minus sign.
6914 */
6915
6916 /*! \fn QString QString::arg(uint a, int fieldWidth, int base, QChar fillChar) const
6917   \overload arg()
6918
6919   The \a base argument specifies the base to use when converting the
6920   integer \a a into a string. The base must be between 2 and 36.
6921
6922   If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6923   used. For negative numbers, zero padding might appear before the
6924   minus sign.
6925 */
6926
6927 /*! \fn QString QString::arg(long a, int fieldWidth, int base, QChar fillChar) const
6928   \overload arg()
6929
6930   \a fieldWidth specifies the minimum amount of space that \a a is
6931   padded to and filled with the character \a fillChar. A positive
6932   value produces right-aligned text; a negative value produces
6933   left-aligned text.
6934
6935   The \a a argument is expressed in the given \a base, which is 10 by
6936   default and must be between 2 and 36.
6937
6938   The '%' can be followed by an 'L', in which case the sequence is
6939   replaced with a localized representation of \a a. The conversion
6940   uses the default locale. The default locale is determined from the
6941   system's locale settings at application startup. It can be changed
6942   using QLocale::setDefault(). The 'L' flag is ignored if \a base is
6943   not 10.
6944
6945   \snippet doc/src/snippets/qstring/main.cpp 12
6946   \snippet doc/src/snippets/qstring/main.cpp 14
6947
6948   If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6949   used. For negative numbers, zero padding might appear before the
6950   minus sign.
6951 */
6952
6953 /*! \fn QString QString::arg(ulong a, int fieldWidth, int base, QChar fillChar) const
6954   \overload arg()
6955
6956   \a fieldWidth specifies the minimum amount of space that \a a is
6957   padded to and filled with the character \a fillChar. A positive
6958   value produces right-aligned text; a negative value produces
6959   left-aligned text.
6960
6961   The \a base argument specifies the base to use when converting the
6962   integer \a a to a string. The base must be between 2 and 36, with 8
6963   giving octal, 10 decimal, and 16 hexadecimal numbers.
6964
6965   If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6966   used. For negative numbers, zero padding might appear before the
6967   minus sign.
6968 */
6969
6970 /*!
6971   \overload arg()
6972
6973   \a fieldWidth specifies the minimum amount of space that \a a is
6974   padded to and filled with the character \a fillChar. A positive
6975   value produces right-aligned text; a negative value produces
6976   left-aligned text.
6977
6978   The \a base argument specifies the base to use when converting the
6979   integer \a a into a string. The base must be between 2 and 36, with
6980   8 giving octal, 10 decimal, and 16 hexadecimal numbers.
6981
6982   If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
6983   used. For negative numbers, zero padding might appear before the
6984   minus sign.
6985 */
6986 QString QString::arg(qlonglong a, int fieldWidth, int base, QChar fillChar) const
6987 {
6988     ArgEscapeData d = findArgEscapes(*this);
6989
6990     if (d.occurrences == 0) {
6991         qWarning() << "QString::arg: Argument missing:" << *this << ',' << a;
6992         return *this;
6993     }
6994
6995     unsigned flags = QLocalePrivate::NoFlags;
6996     if (fillChar == QLatin1Char('0'))
6997         flags = QLocalePrivate::ZeroPadded;
6998
6999     QString arg;
7000     if (d.occurrences > d.locale_occurrences)
7001         arg = QLocale::c().d()->longLongToString(a, -1, base, fieldWidth, flags);
7002
7003     QString locale_arg;
7004     if (d.locale_occurrences > 0) {
7005         QLocale locale;
7006         if (!locale.numberOptions() & QLocale::OmitGroupSeparator)
7007             flags |= QLocalePrivate::ThousandsGroup;
7008         locale_arg = locale.d()->longLongToString(a, -1, base, fieldWidth, flags);
7009     }
7010
7011     return replaceArgEscapes(*this, d, fieldWidth, arg, locale_arg, fillChar);
7012 }
7013
7014 /*!
7015   \overload arg()
7016
7017   \a fieldWidth specifies the minimum amount of space that \a a is
7018   padded to and filled with the character \a fillChar. A positive
7019   value produces right-aligned text; a negative value produces
7020   left-aligned text.
7021
7022   The \a base argument specifies the base to use when converting the
7023   integer \a a into a string. \a base must be between 2 and 36, with 8
7024   giving octal, 10 decimal, and 16 hexadecimal numbers.
7025
7026   If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
7027   used. For negative numbers, zero padding might appear before the
7028   minus sign.
7029 */
7030 QString QString::arg(qulonglong a, int fieldWidth, int base, QChar fillChar) const
7031 {
7032     ArgEscapeData d = findArgEscapes(*this);
7033
7034     if (d.occurrences == 0) {
7035         qWarning() << "QString::arg: Argument missing:" << *this << ',' << a;
7036         return *this;
7037     }
7038
7039     unsigned flags = QLocalePrivate::NoFlags;
7040     if (fillChar == QLatin1Char('0'))
7041         flags = QLocalePrivate::ZeroPadded;
7042
7043     QString arg;
7044     if (d.occurrences > d.locale_occurrences)
7045         arg = QLocale::c().d()->unsLongLongToString(a, -1, base, fieldWidth, flags);
7046
7047     QString locale_arg;
7048     if (d.locale_occurrences > 0) {
7049         QLocale locale;
7050         if (!locale.numberOptions() & QLocale::OmitGroupSeparator)
7051             flags |= QLocalePrivate::ThousandsGroup;
7052         locale_arg = locale.d()->unsLongLongToString(a, -1, base, fieldWidth, flags);
7053     }
7054
7055     return replaceArgEscapes(*this, d, fieldWidth, arg, locale_arg, fillChar);
7056 }
7057
7058 /*!
7059   \overload arg()
7060
7061   \fn QString QString::arg(short a, int fieldWidth, int base, QChar fillChar) const
7062
7063   \a fieldWidth specifies the minimum amount of space that \a a is
7064   padded to and filled with the character \a fillChar. A positive
7065   value produces right-aligned text; a negative value produces
7066   left-aligned text.
7067
7068   The \a base argument specifies the base to use when converting the
7069   integer \a a into a string. The base must be between 2 and 36, with
7070   8 giving octal, 10 decimal, and 16 hexadecimal numbers.
7071
7072   If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
7073   used. For negative numbers, zero padding might appear before the
7074   minus sign.
7075 */
7076
7077 /*!
7078   \fn QString QString::arg(ushort a, int fieldWidth, int base, QChar fillChar) const
7079   \overload arg()
7080
7081   \a fieldWidth specifies the minimum amount of space that \a a is
7082   padded to and filled with the character \a fillChar. A positive
7083   value produces right-aligned text; a negative value produces
7084   left-aligned text.
7085
7086   The \a base argument specifies the base to use when converting the
7087   integer \a a into a string. The base must be between 2 and 36, with
7088   8 giving octal, 10 decimal, and 16 hexadecimal numbers.
7089
7090   If \a fillChar is '0' (the number 0, ASCII 48), the locale's zero is
7091   used. For negative numbers, zero padding might appear before the
7092   minus sign.
7093 */
7094
7095 /*!
7096     \overload arg()
7097 */
7098 QString QString::arg(QChar a, int fieldWidth, QChar fillChar) const
7099 {
7100     QString c;
7101     c += a;
7102     return arg(c, fieldWidth, fillChar);
7103 }
7104
7105 /*!
7106   \overload arg()
7107
7108   The \a a argument is interpreted as a Latin-1 character.
7109 */
7110 QString QString::arg(char a, int fieldWidth, QChar fillChar) const
7111 {
7112     QString c;
7113     c += QLatin1Char(a);
7114     return arg(c, fieldWidth, fillChar);
7115 }
7116
7117 /*!
7118   \fn QString QString::arg(double a, int fieldWidth, char format, int precision, QChar fillChar) const
7119   \overload arg()
7120
7121   Argument \a a is formatted according to the specified \a format and
7122   \a precision. See \l{Argument Formats} for details.
7123
7124   \a fieldWidth specifies the minimum amount of space that \a a is
7125   padded to and filled with the character \a fillChar.  A positive
7126   value produces right-aligned text; a negative value produces
7127   left-aligned text.
7128
7129   \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 2
7130
7131   The '%' can be followed by an 'L', in which case the sequence is
7132   replaced with a localized representation of \a a. The conversion
7133   uses the default locale, set by QLocale::setDefaultLocale(). If no
7134   default locale was specified, the "C" locale is used.
7135
7136   If \a fillChar is '0' (the number 0, ASCII 48), this function will
7137   use the locale's zero to pad. For negative numbers, the zero padding
7138   will probably appear before the minus sign.
7139
7140   \sa QLocale::toString()
7141 */
7142 QString QString::arg(double a, int fieldWidth, char fmt, int prec, QChar fillChar) const
7143 {
7144     ArgEscapeData d = findArgEscapes(*this);
7145
7146     if (d.occurrences == 0) {
7147         qWarning("QString::arg: Argument missing: %s, %g", toLocal8Bit().data(), a);
7148         return *this;
7149     }
7150
7151     unsigned flags = QLocalePrivate::NoFlags;
7152     if (fillChar == QLatin1Char('0'))
7153         flags = QLocalePrivate::ZeroPadded;
7154
7155     if (qIsUpper(fmt))
7156         flags |= QLocalePrivate::CapitalEorX;
7157     fmt = qToLower(fmt);
7158
7159     QLocalePrivate::DoubleForm form = QLocalePrivate::DFDecimal;
7160     switch (fmt) {
7161     case 'f':
7162         form = QLocalePrivate::DFDecimal;
7163         break;
7164     case 'e':
7165         form = QLocalePrivate::DFExponent;
7166         break;
7167     case 'g':
7168         form = QLocalePrivate::DFSignificantDigits;
7169         break;
7170     default:
7171 #if defined(QT_CHECK_RANGE)
7172         qWarning("QString::arg: Invalid format char '%c'", fmt);
7173 #endif
7174         break;
7175     }
7176
7177     QString arg;
7178     if (d.occurrences > d.locale_occurrences)
7179         arg = QLocale::c().d()->doubleToString(a, prec, form, fieldWidth, flags);
7180
7181     QString locale_arg;
7182     if (d.locale_occurrences > 0) {
7183         QLocale locale;
7184
7185         if (!locale.numberOptions() & QLocale::OmitGroupSeparator)
7186             flags |= QLocalePrivate::ThousandsGroup;
7187         locale_arg = locale.d()->doubleToString(a, prec, form, fieldWidth, flags);
7188     }
7189
7190     return replaceArgEscapes(*this, d, fieldWidth, arg, locale_arg, fillChar);
7191 }
7192
7193 static int getEscape(const QChar *uc, int *pos, int len, int maxNumber = 999)
7194 {
7195     int i = *pos;
7196     ++i;
7197     if (i < len && uc[i] == QLatin1Char('L'))
7198         ++i;
7199     if (i < len) {
7200         int escape = uc[i].unicode() - '0';
7201         if (uint(escape) >= 10U)
7202             return -1;
7203         ++i;
7204         while (i < len) {
7205             int digit = uc[i].unicode() - '0';
7206             if (uint(digit) >= 10U)
7207                 break;
7208             escape = (escape * 10) + digit;
7209             ++i;
7210         }
7211         if (escape <= maxNumber) {
7212             *pos = i;
7213             return escape;
7214         }
7215     }
7216     return -1;
7217 }
7218
7219 QString QString::multiArg(int numArgs, const QString **args) const
7220 {
7221     QString result;
7222     QMap<int, int> numbersUsed;
7223     const QChar *uc = (const QChar *) d->data();
7224     const int len = d->size;
7225     const int end = len - 1;
7226     int lastNumber = -1;
7227     int i = 0;
7228
7229     // populate the numbersUsed map with the %n's that actually occur in the string
7230     while (i < end) {
7231         if (uc[i] == QLatin1Char('%')) {
7232             int number = getEscape(uc, &i, len);
7233             if (number != -1) {
7234                 numbersUsed.insert(number, -1);
7235                 continue;
7236             }
7237         }
7238         ++i;
7239     }
7240
7241     // assign an argument number to each of the %n's
7242     QMap<int, int>::iterator j = numbersUsed.begin();
7243     QMap<int, int>::iterator jend = numbersUsed.end();
7244     int arg = 0;
7245     while (j != jend && arg < numArgs) {
7246         *j = arg++;
7247         lastNumber = j.key();
7248         ++j;
7249     }
7250
7251     // sanity
7252     if (numArgs > arg) {
7253         qWarning("QString::arg: %d argument(s) missing in %s", numArgs - arg, toLocal8Bit().data());
7254         numArgs = arg;
7255     }
7256
7257     i = 0;
7258     while (i < len) {
7259         if (uc[i] == QLatin1Char('%') && i != end) {
7260             int number = getEscape(uc, &i, len, lastNumber);
7261             int arg = numbersUsed[number];
7262             if (number != -1 && arg != -1) {
7263                 result += *args[arg];
7264                 continue;
7265             }
7266         }
7267         result += uc[i++];
7268     }
7269     return result;
7270 }
7271
7272
7273 /*! \fn bool QString::isSimpleText() const
7274
7275     \internal
7276 */
7277 bool QString::isSimpleText() const
7278 {
7279     const ushort *p = d->data();
7280     const ushort * const end = p + d->size;
7281     while (p < end) {
7282         ushort uc = *p;
7283         // sort out regions of complex text formatting
7284         if (uc > 0x058f && (uc < 0x1100 || uc > 0xfb0f)) {
7285             return false;
7286         }
7287         p++;
7288     }
7289
7290     return true;
7291 }
7292
7293 /*! \fn bool QString::isRightToLeft() const
7294
7295     Returns true if the string is read right to left.
7296 */
7297 bool QString::isRightToLeft() const
7298 {
7299     const ushort *p = d->data();
7300     const ushort * const end = p + d->size;
7301     while (p < end) {
7302         switch(QChar::direction(*p))
7303         {
7304         case QChar::DirL:
7305             return false;
7306         case QChar::DirR:
7307         case QChar::DirAL:
7308             return true;
7309         default:
7310             break;
7311         }
7312         ++p;
7313     }
7314     return false;
7315 }
7316
7317 /*! \fn QChar *QString::data()
7318
7319     Returns a pointer to the data stored in the QString. The pointer
7320     can be used to access and modify the characters that compose the
7321     string. For convenience, the data is '\\0'-terminated.
7322
7323     Example:
7324
7325     \snippet doc/src/snippets/qstring/main.cpp 19
7326
7327     Note that the pointer remains valid only as long as the string is
7328     not modified by other means. For read-only access, constData() is
7329     faster because it never causes a \l{deep copy} to occur.
7330
7331     \sa constData(), operator[]()
7332 */
7333
7334 /*! \fn const QChar *QString::data() const
7335
7336     \overload
7337 */
7338
7339 /*! \fn const QChar *QString::constData() const
7340
7341     Returns a pointer to the data stored in the QString. The pointer
7342     can be used to access the characters that compose the string. For
7343     convenience, the data is '\\0'-terminated.
7344
7345     Note that the pointer remains valid only as long as the string is
7346     not modified.
7347
7348     \sa data(), operator[]()
7349 */
7350
7351 /*! \fn void QString::push_front(const QString &other)
7352
7353     This function is provided for STL compatibility, prepending the
7354     given \a other string to the beginning of this string. It is
7355     equivalent to \c prepend(other).
7356
7357     \sa prepend()
7358 */
7359
7360 /*! \fn void QString::push_front(QChar ch)
7361
7362     \overload
7363
7364     Prepends the given \a ch character to the beginning of this string.
7365 */
7366
7367 /*! \fn void QString::push_back(const QString &other)
7368
7369     This function is provided for STL compatibility, appending the
7370     given \a other string onto the end of this string. It is
7371     equivalent to \c append(other).
7372
7373     \sa append()
7374 */
7375
7376 /*! \fn void QString::push_back(QChar ch)
7377
7378     \overload
7379
7380     Appends the given \a ch character onto the end of this string.
7381 */
7382
7383 /*!
7384     \fn std::string QString::toStdString() const
7385
7386     Returns a std::string object with the data contained in this
7387     QString. The Unicode data is converted into 8-bit characters using
7388     the toAscii() function.
7389
7390     This operator is mostly useful to pass a QString to a function
7391     that accepts a std::string object.
7392
7393     If the QString contains non-Latin1 Unicode characters, using this
7394     can lead to loss of information.
7395
7396     \sa toAscii(), toLatin1(), toUtf8(), toLocal8Bit()
7397 */
7398
7399 /*!
7400     Constructs a QString that uses the first \a size Unicode characters
7401     in the array \a unicode. The data in \a unicode is \e not
7402     copied. The caller must be able to guarantee that \a unicode will
7403     not be deleted or modified as long as the QString (or an
7404     unmodified copy of it) exists.
7405
7406     Any attempts to modify the QString or copies of it will cause it
7407     to create a deep copy of the data, ensuring that the raw data
7408     isn't modified.
7409
7410     Here's an example of how we can use a QRegExp on raw data in
7411     memory without requiring to copy the data into a QString:
7412
7413     \snippet doc/src/snippets/qstring/main.cpp 22
7414     \snippet doc/src/snippets/qstring/main.cpp 23
7415
7416     \warning A string created with fromRawData() is \e not
7417     '\\0'-terminated, unless the raw data contains a '\\0' character
7418     at position \a size. This means unicode() will \e not return a
7419     '\\0'-terminated string (although utf16() does, at the cost of
7420     copying the raw data).
7421
7422     \sa fromUtf16(), setRawData()
7423 */
7424 QString QString::fromRawData(const QChar *unicode, int size)
7425 {
7426     Data *x;
7427     if (!unicode) {
7428         x = shared_null.data_ptr();
7429     } else if (!size) {
7430         x = shared_empty.data_ptr();
7431     } else {
7432         x = static_cast<Data *>(::malloc(sizeof(Data)));
7433         Q_CHECK_PTR(x);
7434         x->ref.initializeOwned();
7435         x->size = size;
7436         x->alloc = 0;
7437         x->capacityReserved = false;
7438         x->offset = reinterpret_cast<const char *>(unicode) - reinterpret_cast<char *>(x);
7439     }
7440     QStringDataPtr dataPtr = { x };
7441     return QString(dataPtr);
7442 }
7443
7444 /*!
7445     \since 4.7
7446
7447     Resets the QString to use the first \a size Unicode characters
7448     in the array \a unicode. The data in \a unicode is \e not
7449     copied. The caller must be able to guarantee that \a unicode will
7450     not be deleted or modified as long as the QString (or an
7451     unmodified copy of it) exists.
7452
7453     This function can be used instead of fromRawData() to re-use
7454     existings QString objects to save memory re-allocations.
7455
7456     \sa fromRawData()
7457 */
7458 QString &QString::setRawData(const QChar *unicode, int size)
7459 {
7460     if (d->ref.isShared() || d->alloc) {
7461         *this = fromRawData(unicode, size);
7462     } else {
7463         if (unicode) {
7464             d->size = size;
7465             d->offset = reinterpret_cast<const char *>(unicode) - reinterpret_cast<char *>(d);
7466         } else {
7467             d->offset = sizeof(QStringData);
7468             d->size = 0;
7469         }
7470     }
7471     return *this;
7472 }
7473
7474 /*! \class QLatin1String
7475     \brief The QLatin1String class provides a thin wrapper around an US-ASCII/Latin-1 encoded string literal.
7476
7477     \ingroup string-processing
7478     \reentrant
7479
7480     Many of QString's member functions are overloaded to accept
7481     \c{const char *} instead of QString. This includes the copy
7482     constructor, the assignment operator, the comparison operators,
7483     and various other functions such as \link QString::insert()
7484     insert() \endlink, \link QString::replace() replace()\endlink,
7485     and \link QString::indexOf() indexOf()\endlink. These functions
7486     are usually optimized to avoid constructing a QString object for
7487     the \c{const char *} data. For example, assuming \c str is a
7488     QString,
7489
7490     \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 3
7491
7492     is much faster than
7493
7494     \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 4
7495
7496     because it doesn't construct four temporary QString objects and
7497     make a deep copy of the character data.
7498
7499     Applications that define \c QT_NO_CAST_FROM_ASCII (as explained
7500     in the QString documentation) don't have access to QString's
7501     \c{const char *} API. To provide an efficient way of specifying
7502     constant Latin-1 strings, Qt provides the QLatin1String, which is
7503     just a very thin wrapper around a \c{const char *}. Using
7504     QLatin1String, the example code above becomes
7505
7506     \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 5
7507
7508     This is a bit longer to type, but it provides exactly the same
7509     benefits as the first version of the code, and is faster than
7510     converting the Latin-1 strings using QString::fromLatin1().
7511
7512     Thanks to the QString(const QLatin1String &) constructor,
7513     QLatin1String can be used everywhere a QString is expected. For
7514     example:
7515
7516     \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 6
7517
7518     \sa QString, QLatin1Char, QStringLiteral
7519 */
7520
7521 /*! \fn QLatin1String::QLatin1String(const char *str)
7522
7523     Constructs a QLatin1String object that stores \a str. Note that if
7524     \a str is 0, an empty string is created; this case is handled by
7525     QString.
7526
7527     The string data is \e not copied. The caller must be able to
7528     guarantee that \a str will not be deleted or modified as long as
7529     the QLatin1String object exists.
7530
7531     \sa latin1()
7532 */
7533
7534 /*! \fn QLatin1String::QLatin1String(const char *str, int size)
7535
7536     Constructs a QLatin1String object that stores \a str with \a size.
7537     Note that if \a str is 0, an empty string is created; this case
7538     is handled by QString.
7539
7540     The string data is \e not copied. The caller must be able to
7541     guarantee that \a str will not be deleted or modified as long as
7542     the QLatin1String object exists.
7543
7544     \sa latin1()
7545 */
7546
7547 /*! \fn QLatin1String::QLatin1String(const QByteArray &str)
7548
7549     Constructs a QLatin1String object that stores \a str.
7550
7551     The string data is \e not copied. The caller must be able to
7552     guarantee that \a str will not be deleted or modified as long as
7553     the QLatin1String object exists.
7554
7555     \sa latin1()
7556 */
7557
7558 /*! \fn const char *QLatin1String::latin1() const
7559
7560     Returns the Latin-1 string stored in this object.
7561 */
7562
7563 /*! \fn int QLatin1String::size() const
7564
7565     Returns the size of the Latin-1 string stored in this object.
7566 */
7567
7568 /*! \fn bool QLatin1String::operator==(const QString &other) const
7569
7570     Returns true if this string is equal to string \a other;
7571     otherwise returns false.
7572
7573     The comparison is based exclusively on the numeric Unicode values
7574     of the characters and is very fast, but is not what a human would
7575     expect. Consider sorting user-interface strings with
7576     QString::localeAwareCompare().
7577 */
7578
7579 /*!
7580     \fn bool QLatin1String::operator==(const char *other) const
7581     \since 4.3
7582     \overload
7583
7584     The \a other const char pointer is converted to a QString using
7585     the QString::fromAscii() function.
7586
7587     You can disable this operator by defining \c
7588     QT_NO_CAST_FROM_ASCII when you compile your applications. This
7589     can be useful if you want to ensure that all user-visible strings
7590     go through QObject::tr(), for example.
7591 */
7592
7593 /*! \fn bool QLatin1String::operator!=(const QString &other) const
7594
7595     Returns true if this string is not equal to string \a other;
7596     otherwise returns false.
7597
7598     The comparison is based exclusively on the numeric Unicode values
7599     of the characters and is very fast, but is not what a human would
7600     expect. Consider sorting user-interface strings with
7601     QString::localeAwareCompare().
7602 */
7603
7604 /*!
7605     \fn bool QLatin1String::operator!=(const char *other) const
7606     \since 4.3
7607     \overload operator!=()
7608
7609     The \a other const char pointer is converted to a QString using
7610     the QString::fromAscii() function.
7611
7612     You can disable this operator by defining \c
7613     QT_NO_CAST_FROM_ASCII when you compile your applications. This
7614     can be useful if you want to ensure that all user-visible strings
7615     go through QObject::tr(), for example.
7616 */
7617
7618 /*!
7619     \fn bool QLatin1String::operator>(const QString &other) const
7620
7621     Returns true if this string is lexically greater than string \a
7622     other; otherwise returns false.
7623
7624     The comparison is based exclusively on the numeric Unicode values
7625     of the characters and is very fast, but is not what a human would
7626     expect. Consider sorting user-interface strings with
7627     QString::localeAwareCompare().
7628 */
7629
7630 /*!
7631     \fn bool QLatin1String::operator>(const char *other) const
7632     \since 4.3
7633     \overload
7634
7635     The \a other const char pointer is converted to a QString using
7636     the QString::fromAscii() function.
7637
7638     You can disable this operator by defining \c QT_NO_CAST_FROM_ASCII
7639     when you compile your applications. This can be useful if you want
7640     to ensure that all user-visible strings go through QObject::tr(),
7641     for example.
7642 */
7643
7644 /*!
7645     \fn bool QLatin1String::operator<(const QString &other) const
7646
7647     Returns true if this string is lexically less than the \a other
7648     string; otherwise returns false.
7649
7650     The comparison is based exclusively on the numeric Unicode values
7651     of the characters and is very fast, but is not what a human would
7652     expect. Consider sorting user-interface strings using the
7653     QString::localeAwareCompare() function.
7654 */
7655
7656 /*!
7657     \fn bool QLatin1String::operator<(const char *other) const
7658     \since 4.3
7659     \overload
7660
7661     The \a other const char pointer is converted to a QString using
7662     the QString::fromAscii() function.
7663
7664     You can disable this operator by defining \c
7665     QT_NO_CAST_FROM_ASCII when you compile your applications. This
7666     can be useful if you want to ensure that all user-visible strings
7667     go through QObject::tr(), for example.
7668 */
7669
7670 /*!
7671     \fn bool QLatin1String::operator>=(const QString &other) const
7672
7673     Returns true if this string is lexically greater than or equal
7674     to string \a other; otherwise returns false.
7675
7676     The comparison is based exclusively on the numeric Unicode values
7677     of the characters and is very fast, but is not what a human would
7678     expect. Consider sorting user-interface strings with
7679     QString::localeAwareCompare().
7680 */
7681
7682 /*!
7683     \fn bool QLatin1String::operator>=(const char *other) const
7684     \since 4.3
7685     \overload
7686
7687     The \a other const char pointer is converted to a QString using
7688     the QString::fromAscii() function.
7689
7690     You can disable this operator by defining \c
7691     QT_NO_CAST_FROM_ASCII when you compile your applications. This
7692     can be useful if you want to ensure that all user-visible strings
7693     go through QObject::tr(), for example.
7694 */
7695
7696 /*! \fn bool QLatin1String::operator<=(const QString &other) const
7697
7698     Returns true if this string is lexically less than or equal
7699     to string \a other; otherwise returns false.
7700
7701     The comparison is based exclusively on the numeric Unicode values
7702     of the characters and is very fast, but is not what a human would
7703     expect. Consider sorting user-interface strings with
7704     QString::localeAwareCompare().
7705 */
7706
7707 /*!
7708     \fn bool QLatin1String::operator<=(const char *other) const
7709     \since 4.3
7710     \overload
7711
7712     The \a other const char pointer is converted to a QString using
7713     the QString::fromAscii() function.
7714
7715     You can disable this operator by defining \c
7716     QT_NO_CAST_FROM_ASCII when you compile your applications. This
7717     can be useful if you want to ensure that all user-visible strings
7718     go through QObject::tr(), for example.
7719 */
7720
7721
7722
7723 /*! \fn bool operator==(const QLatin1String &s1, const QLatin1String &s2)
7724    \relates QLatin1String
7725
7726    Returns true if string \a s1 is lexically equal to string \a s2; otherwise
7727    returns false.
7728 */
7729 /*! \fn bool operator!=(const QLatin1String &s1, const QLatin1String &s2)
7730    \relates QLatin1String
7731
7732    Returns true if string \a s1 is lexically unequal to string \a s2; otherwise
7733    returns false.
7734 */
7735 /*! \fn bool operator<(const QLatin1String &s1, const QLatin1String &s2)
7736    \relates QLatin1String
7737
7738    Returns true if string \a s1 is lexically smaller than string \a s2; otherwise
7739    returns false.
7740 */
7741 /*! \fn bool operator<=(const QLatin1String &s1, const QLatin1String &s2)
7742    \relates QLatin1String
7743
7744    Returns true if string \a s1 is lexically smaller than or equal to string \a s2; otherwise
7745    returns false.
7746 */
7747 /*! \fn bool operator>(const QLatin1String &s1, const QLatin1String &s2)
7748    \relates QLatin1String
7749
7750    Returns true if string \a s1 is lexically greater than string \a s2; otherwise
7751    returns false.
7752 */
7753 /*! \fn bool operator>=(const QLatin1String &s1, const QLatin1String &s2)
7754    \relates QLatin1String
7755
7756    Returns true if string \a s1 is lexically greater than or equal to
7757    string \a s2; otherwise returns false.
7758 */
7759
7760
7761 #if !defined(QT_NO_DATASTREAM) || (defined(QT_BOOTSTRAPPED) && !defined(QT_BUILD_QMAKE))
7762 /*!
7763     \fn QDataStream &operator<<(QDataStream &stream, const QString &string)
7764     \relates QString
7765
7766     Writes the given \a string to the specified \a stream.
7767
7768     \sa {Serializing Qt Data Types}
7769 */
7770
7771 QDataStream &operator<<(QDataStream &out, const QString &str)
7772 {
7773     if (out.version() == 1) {
7774         out << str.toLatin1();
7775     } else {
7776         if (!str.isNull() || out.version() < 3) {
7777             if ((out.byteOrder() == QDataStream::BigEndian) == (QSysInfo::ByteOrder == QSysInfo::BigEndian)) {
7778                 out.writeBytes(reinterpret_cast<const char *>(str.unicode()), sizeof(QChar) * str.length());
7779             } else {
7780                 QVarLengthArray<ushort> buffer(str.length());
7781                 const ushort *data = reinterpret_cast<const ushort *>(str.constData());
7782                 for (int i = 0; i < str.length(); i++) {
7783                     buffer[i] = qbswap(*data);
7784                     ++data;
7785                 }
7786                 out.writeBytes(reinterpret_cast<const char *>(buffer.data()), sizeof(ushort) * buffer.size());
7787             }
7788         } else {
7789             // write null marker
7790             out << (quint32)0xffffffff;
7791         }
7792     }
7793     return out;
7794 }
7795
7796 /*!
7797     \fn QDataStream &operator>>(QDataStream &stream, QString &string)
7798     \relates QString
7799
7800     Reads a string from the specified \a stream into the given \a string.
7801
7802     \sa {Serializing Qt Data Types}
7803 */
7804
7805 QDataStream &operator>>(QDataStream &in, QString &str)
7806 {
7807 #ifdef QT_QSTRING_UCS_4
7808 #if defined(Q_CC_GNU)
7809 #warning "operator>> not working properly"
7810 #endif
7811 #endif
7812
7813     if (in.version() == 1) {
7814         QByteArray l;
7815         in >> l;
7816         str = QString::fromLatin1(l);
7817     } else {
7818         quint32 bytes = 0;
7819         in >> bytes;                                  // read size of string
7820         if (bytes == 0xffffffff) {                    // null string
7821             str.clear();
7822         } else if (bytes > 0) {                       // not empty
7823             if (bytes & 0x1) {
7824                 str.clear();
7825                 in.setStatus(QDataStream::ReadCorruptData);
7826                 return in;
7827             }
7828
7829             const quint32 Step = 1024 * 1024;
7830             quint32 len = bytes / 2;
7831             quint32 allocated = 0;
7832
7833             while (allocated < len) {
7834                 int blockSize = qMin(Step, len - allocated);
7835                 str.resize(allocated + blockSize);
7836                 if (in.readRawData(reinterpret_cast<char *>(str.data()) + allocated * 2,
7837                                    blockSize * 2) != blockSize * 2) {
7838                     str.clear();
7839                     in.setStatus(QDataStream::ReadPastEnd);
7840                     return in;
7841                 }
7842                 allocated += blockSize;
7843             }
7844
7845             if ((in.byteOrder() == QDataStream::BigEndian)
7846                     != (QSysInfo::ByteOrder == QSysInfo::BigEndian)) {
7847                 ushort *data = reinterpret_cast<ushort *>(str.data());
7848                 while (len--) {
7849                     *data = qbswap(*data);
7850                     ++data;
7851                 }
7852             }
7853         } else {
7854             str = QString(QLatin1String(""));
7855         }
7856     }
7857     return in;
7858 }
7859 #endif // QT_NO_DATASTREAM
7860
7861
7862
7863
7864 /*!
7865     \class QStringRef
7866     \since 4.3
7867     \brief The QStringRef class provides a thin wrapper around QString substrings.
7868     \reentrant
7869     \ingroup tools
7870     \ingroup string-processing
7871
7872     QStringRef provides a read-only subset of the QString API.
7873
7874     A string reference explicitly references a portion of a string()
7875     with a given size(), starting at a specific position(). Calling
7876     toString() returns a copy of the data as a real QString instance.
7877
7878     This class is designed to improve the performance of substring
7879     handling when manipulating substrings obtained from existing QString
7880     instances. QStringRef avoids the memory allocation and reference
7881     counting overhead of a standard QString by simply referencing a
7882     part of the original string. This can prove to be advantageous in
7883     low level code, such as that used in a parser, at the expense of
7884     potentially more complex code.
7885
7886     For most users, there are no semantic benefits to using QStringRef
7887     instead of QString since QStringRef requires attention to be paid
7888     to memory management issues, potentially making code more complex
7889     to write and maintain.
7890
7891     \warning A QStringRef is only valid as long as the referenced
7892     string exists. If the original string is deleted, the string
7893     reference points to an invalid memory location.
7894
7895     We suggest that you only use this class in stable code where profiling
7896     has clearly identified that performance improvements can be made by
7897     replacing standard string operations with the optimized substring
7898     handling provided by this class.
7899
7900     \sa {Implicitly Shared Classes}
7901 */
7902
7903
7904 /*!
7905  \fn QStringRef::QStringRef()
7906
7907  Constructs an empty string reference.
7908 */
7909
7910 /*! \fn QStringRef::QStringRef(const QString *string, int position, int length)
7911
7912 Constructs a string reference to the range of characters in the given
7913 \a string specified by the starting \a position and \a length in characters.
7914
7915 \warning This function exists to improve performance as much as possible,
7916 and performs no bounds checking. For program correctness, \a position and
7917 \a length must describe a valid substring of \a string.
7918
7919 This means that the starting \a position must be positive or 0 and smaller
7920 than \a string's length, and \a length must be positive or 0 but smaller than
7921 the string's length minus the starting \a position;
7922 i.e, 0 <= position < string->length() and
7923 0 <= length <= string->length() - position must both be satisfied.
7924 */
7925
7926 /*! \fn QStringRef::QStringRef(const QString *string)
7927
7928 Constructs a string reference to the given \a string.
7929 */
7930
7931 /*! \fn QStringRef::QStringRef(const QStringRef &other)
7932
7933 Constructs a copy of the \a other string reference.
7934  */
7935 /*!
7936 \fn QStringRef::~QStringRef()
7937
7938 Destroys the string reference.
7939
7940 Since this class is only used to refer to string data, and does not take
7941 ownership of it, no memory is freed when instances are destroyed.
7942 */
7943
7944
7945 /*!
7946     \fn int QStringRef::position() const
7947
7948     Returns the starting position in the referenced string that is referred to
7949     by the string reference.
7950
7951     \sa size(), string()
7952 */
7953
7954 /*!
7955     \fn int QStringRef::size() const
7956
7957     Returns the number of characters referred to by the string reference.
7958     Equivalent to length() and count().
7959
7960     \sa position(), string()
7961 */
7962 /*!
7963     \fn int QStringRef::count() const
7964     Returns the number of characters referred to by the string reference.
7965     Equivalent to size() and length().
7966
7967     \sa position(), string()
7968 */
7969 /*!
7970     \fn int QStringRef::length() const
7971     Returns the number of characters referred to by the string reference.
7972     Equivalent to size() and count().
7973
7974     \sa position(), string()
7975 */
7976
7977
7978 /*!
7979     \fn bool QStringRef::isEmpty() const
7980
7981     Returns true if the string reference has no characters; otherwise returns
7982     false.
7983
7984     A string reference is empty if its size is zero.
7985
7986     \sa size()
7987 */
7988
7989 /*!
7990     \fn bool QStringRef::isNull() const
7991
7992     Returns true if string() returns a null pointer or a pointer to a
7993     null string; otherwise returns true.
7994
7995     \sa size()
7996 */
7997
7998 /*!
7999     \fn const QString *QStringRef::string() const
8000
8001     Returns a pointer to the string referred to by the string reference, or
8002     0 if it does not reference a string.
8003
8004     \sa unicode()
8005 */
8006
8007
8008 /*!
8009     \fn const QChar *QStringRef::unicode() const
8010
8011     Returns a Unicode representation of the string reference. Since
8012     the data stems directly from the referenced string, it is not
8013     null-terminated unless the string reference includes the string's
8014     null terminator.
8015
8016     \sa string()
8017 */
8018
8019 /*!
8020     \fn const QChar *QStringRef::data() const
8021
8022     Same as unicode().
8023 */
8024
8025 /*!
8026     \fn const QChar *QStringRef::constData() const
8027
8028     Same as unicode().
8029 */
8030
8031 /*!
8032     Returns a copy of the string reference as a QString object.
8033
8034     If the string reference is not a complete reference of the string
8035     (meaning that position() is 0 and size() equals string()->size()),
8036     this function will allocate a new string to return.
8037
8038     \sa string()
8039 */
8040
8041 QString QStringRef::toString() const {
8042     if (!m_string)
8043         return QString();
8044     if (m_size && m_position == 0 && m_size == m_string->size())
8045         return *m_string;
8046     return QString(m_string->unicode() + m_position, m_size);
8047 }
8048
8049
8050 /*! \relates QStringRef
8051
8052    Returns true if string reference \a s1 is lexically equal to string reference \a s2; otherwise
8053    returns false.
8054 */
8055 bool operator==(const QStringRef &s1,const QStringRef &s2)
8056 { return (s1.size() == s2.size() &&
8057           qMemEquals((const ushort *)s1.unicode(), (const ushort *)s2.unicode(), s1.size()));
8058 }
8059
8060 /*! \relates QStringRef
8061
8062    Returns true if string \a s1 is lexically equal to string reference \a s2; otherwise
8063    returns false.
8064 */
8065 bool operator==(const QString &s1,const QStringRef &s2)
8066 { return (s1.size() == s2.size() &&
8067           qMemEquals((const ushort *)s1.unicode(), (const ushort *)s2.unicode(), s1.size()));
8068 }
8069
8070 /*! \relates QStringRef
8071
8072    Returns true if string  \a s1 is lexically equal to string reference \a s2; otherwise
8073    returns false.
8074 */
8075 bool operator==(const QLatin1String &s1, const QStringRef &s2)
8076 {
8077     if (s1.size() != s2.size())
8078         return false;
8079
8080     const ushort *uc = reinterpret_cast<const ushort *>(s2.unicode());
8081     const ushort *e = uc + s2.size();
8082     const uchar *c = reinterpret_cast<const uchar *>(s1.latin1());
8083     if (!c)
8084         return s2.isEmpty();
8085
8086     while (*c) {
8087         if (uc == e || *uc != *c)
8088             return false;
8089         ++uc;
8090         ++c;
8091     }
8092     return (uc == e);
8093 }
8094
8095 /*!
8096    \relates QStringRef
8097
8098     Returns true if string reference \a s1 is lexically less than
8099     string reference \a s2; otherwise returns false.
8100
8101     The comparison is based exclusively on the numeric Unicode values
8102     of the characters and is very fast, but is not what a human would
8103     expect. Consider sorting user-interface strings using the
8104     QString::localeAwareCompare() function.
8105 */
8106 bool operator<(const QStringRef &s1,const QStringRef &s2)
8107 {
8108     return ucstrcmp(s1.constData(), s1.length(), s2.constData(), s2.length()) < 0;
8109 }
8110
8111 /*!\fn bool operator<=(const QStringRef &s1,const QStringRef &s2)
8112
8113    \relates QStringRef
8114
8115     Returns true if string reference \a s1 is lexically less than
8116     or equal to string reference \a s2; otherwise returns false.
8117
8118     The comparison is based exclusively on the numeric Unicode values
8119     of the characters and is very fast, but is not what a human would
8120     expect. Consider sorting user-interface strings using the
8121     QString::localeAwareCompare() function.
8122 */
8123
8124 /*!\fn bool operator>=(const QStringRef &s1,const QStringRef &s2)
8125
8126    \relates QStringRef
8127
8128     Returns true if string reference \a s1 is lexically greater than
8129     or equal to string reference \a s2; otherwise returns false.
8130
8131     The comparison is based exclusively on the numeric Unicode values
8132     of the characters and is very fast, but is not what a human would
8133     expect. Consider sorting user-interface strings using the
8134     QString::localeAwareCompare() function.
8135 */
8136
8137 /*!\fn bool operator>(const QStringRef &s1,const QStringRef &s2)
8138
8139    \relates QStringRef
8140
8141     Returns true if string reference \a s1 is lexically greater than
8142     string reference \a s2; otherwise returns false.
8143
8144     The comparison is based exclusively on the numeric Unicode values
8145     of the characters and is very fast, but is not what a human would
8146     expect. Consider sorting user-interface strings using the
8147     QString::localeAwareCompare() function.
8148 */
8149
8150
8151 /*!
8152     \fn const QChar QStringRef::at(int position) const
8153
8154     Returns the character at the given index \a position in the
8155     string reference.
8156
8157     The \a position must be a valid index position in the string
8158     (i.e., 0 <= \a position < size()).
8159 */
8160
8161 /*!
8162     \fn void QStringRef::clear()
8163
8164     Clears the contents of the string reference by making it null and empty.
8165
8166     \sa isEmpty(), isNull()
8167 */
8168
8169 /*!
8170     \fn QStringRef &QStringRef::operator=(const QStringRef &other)
8171
8172     Assigns the \a other string reference to this string reference, and
8173     returns the result.
8174 */
8175
8176 /*!
8177     \fn QStringRef &QStringRef::operator=(const QString *string)
8178
8179     Constructs a string reference to the given \a string and assigns it to
8180     this string reference, returning the result.
8181 */
8182
8183 /*!
8184     \typedef QString::DataPtr
8185     \internal
8186 */
8187
8188 /*!
8189     \fn DataPtr & QString::data_ptr()
8190     \internal
8191 */
8192
8193
8194
8195 /*!  Appends the string reference to \a string, and returns a new
8196 reference to the combined string data.
8197  */
8198 QStringRef QStringRef::appendTo(QString *string) const
8199 {
8200     if (!string)
8201         return QStringRef();
8202     int pos = string->size();
8203     string->insert(pos, unicode(), size());
8204     return QStringRef(string, pos, size());
8205 }
8206
8207 /*!
8208     \fn int QStringRef::compare(const QStringRef &s1, const QString &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
8209     \since 4.5
8210
8211     Compares the string \a s1 with the string \a s2 and returns an
8212     integer less than, equal to, or greater than zero if \a s1
8213     is less than, equal to, or greater than \a s2.
8214
8215     If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
8216     otherwise the comparison is case insensitive.
8217 */
8218
8219 /*!
8220     \fn int QStringRef::compare(const QStringRef &s1, const QStringRef &s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
8221     \since 4.5
8222     \overload
8223
8224     Compares the string \a s1 with the string \a s2 and returns an
8225     integer less than, equal to, or greater than zero if \a s1
8226     is less than, equal to, or greater than \a s2.
8227
8228     If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
8229     otherwise the comparison is case insensitive.
8230 */
8231
8232 /*!
8233     \fn int QStringRef::compare(const QStringRef &s1, QLatin1String s2, Qt::CaseSensitivity cs = Qt::CaseSensitive)
8234     \since 4.5
8235     \overload
8236
8237     Compares the string \a s1 with the string \a s2 and returns an
8238     integer less than, equal to, or greater than zero if \a s1
8239     is less than, equal to, or greater than \a s2.
8240
8241     If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
8242     otherwise the comparison is case insensitive.
8243 */
8244
8245 /*!
8246     \overload
8247     \fn int QStringRef::compare(const QString &other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
8248     \since 4.5
8249
8250     Compares this string with the \a other string and returns an
8251     integer less than, equal to, or greater than zero if this string
8252     is less than, equal to, or greater than the \a other string.
8253
8254     If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
8255     otherwise the comparison is case insensitive.
8256
8257     Equivalent to \c {compare(*this, other, cs)}.
8258
8259     \sa QString::compare()
8260 */
8261
8262 /*!
8263     \overload
8264     \fn int QStringRef::compare(const QStringRef &other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
8265     \since 4.5
8266
8267     Compares this string with the \a other string and returns an
8268     integer less than, equal to, or greater than zero if this string
8269     is less than, equal to, or greater than the \a other string.
8270
8271     If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
8272     otherwise the comparison is case insensitive.
8273
8274     Equivalent to \c {compare(*this, other, cs)}.
8275
8276     \sa QString::compare()
8277 */
8278
8279 /*!
8280     \overload
8281     \fn int QStringRef::compare(QLatin1String other, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
8282     \since 4.5
8283
8284     Compares this string with the \a other string and returns an
8285     integer less than, equal to, or greater than zero if this string
8286     is less than, equal to, or greater than the \a other string.
8287
8288     If \a cs is Qt::CaseSensitive, the comparison is case sensitive;
8289     otherwise the comparison is case insensitive.
8290
8291     Equivalent to \c {compare(*this, other, cs)}.
8292
8293     \sa QString::compare()
8294 */
8295
8296 /*!
8297     \fn int QStringRef::localeAwareCompare(const QStringRef &s1, const QString & s2)
8298     \since 4.5
8299
8300     Compares \a s1 with \a s2 and returns an integer less than, equal
8301     to, or greater than zero if \a s1 is less than, equal to, or
8302     greater than \a s2.
8303
8304     The comparison is performed in a locale- and also
8305     platform-dependent manner. Use this function to present sorted
8306     lists of strings to the user.
8307
8308     On Mac OS X, this function compares according the
8309     "Order for sorted lists" setting in the International prefereces panel.
8310
8311     \sa compare(), QTextCodec::locale()
8312 */
8313
8314 /*!
8315     \fn int QStringRef::localeAwareCompare(const QStringRef &s1, const QStringRef & s2)
8316     \since 4.5
8317     \overload
8318
8319     Compares \a s1 with \a s2 and returns an integer less than, equal
8320     to, or greater than zero if \a s1 is less than, equal to, or
8321     greater than \a s2.
8322
8323     The comparison is performed in a locale- and also
8324     platform-dependent manner. Use this function to present sorted
8325     lists of strings to the user.
8326
8327 */
8328
8329 /*!
8330     \fn int QStringRef::localeAwareCompare(const QString &other) const
8331     \since 4.5
8332     \overload
8333
8334     Compares this string with the \a other string and returns an
8335     integer less than, equal to, or greater than zero if this string
8336     is less than, equal to, or greater than the \a other string.
8337
8338     The comparison is performed in a locale- and also
8339     platform-dependent manner. Use this function to present sorted
8340     lists of strings to the user.
8341 */
8342
8343 /*!
8344     \fn int QStringRef::localeAwareCompare(const QStringRef &other) const
8345     \since 4.5
8346     \overload
8347
8348     Compares this string with the \a other string and returns an
8349     integer less than, equal to, or greater than zero if this string
8350     is less than, equal to, or greater than the \a other string.
8351
8352     The comparison is performed in a locale- and also
8353     platform-dependent manner. Use this function to present sorted
8354     lists of strings to the user.
8355 */
8356
8357 /*!
8358     \fn QString &QString::append(const QStringRef &reference)
8359     \since 4.4
8360
8361     Appends the given string \a reference to this string and returns the result.
8362  */
8363 QString &QString::append(const QStringRef &str)
8364 {
8365     if (str.string() == this) {
8366         str.appendTo(this);
8367     } else if (str.string()) {
8368         int oldSize = size();
8369         resize(oldSize + str.size());
8370         memcpy(data() + oldSize, str.unicode(), str.size() * sizeof(QChar));
8371     }
8372     return *this;
8373 }
8374
8375 /*!
8376     \since 4.4
8377
8378     Returns a substring reference to the \a n leftmost characters
8379     of the string.
8380
8381     If \a n is greater than size() or less than zero, a reference to the entire
8382     string is returned.
8383
8384     \snippet doc/src/snippets/qstring/main.cpp leftRef
8385
8386     \sa left(), rightRef(), midRef(), startsWith()
8387 */
8388 QStringRef QString::leftRef(int n)  const
8389 {
8390     if (n >= d->size || n < 0)
8391         n = d->size;
8392     return QStringRef(this, 0, n);
8393 }
8394
8395 /*!
8396     \since 4.4
8397
8398     Returns a substring reference to the \a n rightmost characters
8399     of the string.
8400
8401     If \a n is greater than size() or less than zero, a reference to the entire
8402     string is returned.
8403
8404     \snippet doc/src/snippets/qstring/main.cpp rightRef
8405
8406     \sa right(), leftRef(), midRef(), endsWith()
8407 */
8408 QStringRef QString::rightRef(int n) const
8409 {
8410     if (n >= d->size || n < 0)
8411         n = d->size;
8412     return QStringRef(this, d->size - n, n);
8413 }
8414
8415 /*!
8416     \since 4.4
8417
8418     Returns a substring reference to \a n characters of this string,
8419     starting at the specified \a position.
8420
8421     If the \a position exceeds the length of the string, a null
8422     reference is returned.
8423
8424     If there are less than \a n characters available in the string,
8425     starting at the given \a position, or if \a n is -1 (default), the
8426     function returns all characters from the specified \a position
8427     onwards.
8428
8429     Example:
8430
8431     \snippet doc/src/snippets/qstring/main.cpp midRef
8432
8433     \sa mid(), leftRef(), rightRef()
8434 */
8435
8436 QStringRef QString::midRef(int position, int n) const
8437 {
8438     if (position > d->size)
8439         return QStringRef();
8440     if (position < 0) {
8441         if (n < 0 || n + position >= d->size)
8442             return QStringRef(this, 0, d->size);
8443         if (n + position <= 0)
8444             return QStringRef();
8445
8446         n += position;
8447         position = 0;
8448     } else if (n < 0 || n > d->size - position)
8449         n = d->size - position;
8450     return QStringRef(this, position, n);
8451 }
8452
8453 /*!
8454   \since 4.8
8455
8456   Returns the index position of the first occurrence of the string \a
8457   str in this string reference, searching forward from index position
8458   \a from. Returns -1 if \a str is not found.
8459
8460   If \a cs is Qt::CaseSensitive (default), the search is case
8461   sensitive; otherwise the search is case insensitive.
8462
8463   If \a from is -1, the search starts at the last character; if it is
8464   -2, at the next to last character and so on.
8465
8466   \sa QString::indexOf(), lastIndexOf(), contains(), count()
8467 */
8468 int QStringRef::indexOf(const QString &str, int from, Qt::CaseSensitivity cs) const
8469 {
8470     return qFindString(unicode(), length(), from, str.unicode(), str.length(), cs);
8471 }
8472
8473 /*!
8474     \since 4.8
8475     \overload indexOf()
8476
8477     Returns the index position of the first occurrence of the
8478     character \a ch in the string reference, searching forward from
8479     index position \a from. Returns -1 if \a ch could not be found.
8480
8481     \sa QString::indexOf(), lastIndexOf(), contains(), count()
8482 */
8483 int QStringRef::indexOf(QChar ch, int from, Qt::CaseSensitivity cs) const
8484 {
8485     return findChar(unicode(), length(), ch, from, cs);
8486 }
8487
8488 /*!
8489   \since 4.8
8490
8491   Returns the index position of the first occurrence of the string \a
8492   str in this string reference, searching forward from index position
8493   \a from. Returns -1 if \a str is not found.
8494
8495   If \a cs is Qt::CaseSensitive (default), the search is case
8496   sensitive; otherwise the search is case insensitive.
8497
8498   If \a from is -1, the search starts at the last character; if it is
8499   -2, at the next to last character and so on.
8500
8501   \sa QString::indexOf(), lastIndexOf(), contains(), count()
8502 */
8503 int QStringRef::indexOf(QLatin1String str, int from, Qt::CaseSensitivity cs) const
8504 {
8505     return qt_find_latin1_string(unicode(), size(), str, from, cs);
8506 }
8507
8508 /*!
8509     \since 4.8
8510
8511     \overload indexOf()
8512
8513     Returns the index position of the first occurrence of the string
8514     reference \a str in this string reference, searching forward from
8515     index position \a from. Returns -1 if \a str is not found.
8516
8517     If \a cs is Qt::CaseSensitive (default), the search is case
8518     sensitive; otherwise the search is case insensitive.
8519
8520     \sa QString::indexOf(), lastIndexOf(), contains(), count()
8521 */
8522 int QStringRef::indexOf(const QStringRef &str, int from, Qt::CaseSensitivity cs) const
8523 {
8524     return qFindString(unicode(), size(), from, str.unicode(), str.size(), cs);
8525 }
8526
8527 /*!
8528   \since 4.8
8529
8530   Returns the index position of the last occurrence of the string \a
8531   str in this string reference, searching backward from index position
8532   \a from. If \a from is -1 (default), the search starts at the last
8533   character; if \a from is -2, at the next to last character and so
8534   on. Returns -1 if \a str is not found.
8535
8536   If \a cs is Qt::CaseSensitive (default), the search is case
8537   sensitive; otherwise the search is case insensitive.
8538
8539   \sa QString::lastIndexOf(), indexOf(), contains(), count()
8540 */
8541 int QStringRef::lastIndexOf(const QString &str, int from, Qt::CaseSensitivity cs) const
8542 {
8543     const int sl = str.size();
8544     if (sl == 1)
8545         return lastIndexOf(str.at(0), from, cs);
8546
8547     const int l = size();;
8548     if (from < 0)
8549         from += l;
8550     int delta = l - sl;
8551     if (from == l && sl == 0)
8552         return from;
8553     if (from < 0 || from >= l || delta < 0)
8554         return -1;
8555     if (from > delta)
8556         from = delta;
8557
8558     return lastIndexOfHelper(reinterpret_cast<const ushort*>(unicode()), from,
8559                              reinterpret_cast<const ushort*>(str.unicode()), str.size(), cs);
8560 }
8561
8562 /*!
8563   \since 4.8
8564   \overload lastIndexOf()
8565
8566   Returns the index position of the last occurrence of the character
8567   \a ch, searching backward from position \a from.
8568
8569   \sa QString::lastIndexOf(), indexOf(), contains(), count()
8570 */
8571 int QStringRef::lastIndexOf(QChar ch, int from, Qt::CaseSensitivity cs) const
8572 {
8573     return qt_last_index_of(unicode(), size(), ch, from, cs);
8574 }
8575
8576 /*!
8577   \since 4.8
8578   \overload lastIndexOf()
8579
8580   Returns the index position of the last occurrence of the string \a
8581   str in this string reference, searching backward from index position
8582   \a from. If \a from is -1 (default), the search starts at the last
8583   character; if \a from is -2, at the next to last character and so
8584   on. Returns -1 if \a str is not found.
8585
8586   If \a cs is Qt::CaseSensitive (default), the search is case
8587   sensitive; otherwise the search is case insensitive.
8588
8589   \sa QString::lastIndexOf(), indexOf(), contains(), count()
8590 */
8591 int QStringRef::lastIndexOf(QLatin1String str, int from, Qt::CaseSensitivity cs) const
8592 {
8593     const int sl = str.size();
8594     if (sl == 1)
8595         return lastIndexOf(QLatin1Char(str.latin1()[0]), from, cs);
8596
8597     const int l = size();
8598     if (from < 0)
8599         from += l;
8600     int delta = l - sl;
8601     if (from == l && sl == 0)
8602         return from;
8603     if (from < 0 || from >= l || delta < 0)
8604         return -1;
8605     if (from > delta)
8606         from = delta;
8607
8608     QVarLengthArray<ushort> s(sl);
8609     for (int i = 0; i < sl; ++i)
8610         s[i] = str.latin1()[i];
8611
8612     return lastIndexOfHelper(reinterpret_cast<const ushort*>(unicode()), from, s.data(), sl, cs);
8613 }
8614
8615 /*!
8616   \since 4.8
8617   \overload lastIndexOf()
8618
8619   Returns the index position of the last occurrence of the string
8620   reference \a str in this string reference, searching backward from
8621   index position \a from. If \a from is -1 (default), the search
8622   starts at the last character; if \a from is -2, at the next to last
8623   character and so on. Returns -1 if \a str is not found.
8624
8625   If \a cs is Qt::CaseSensitive (default), the search is case
8626   sensitive; otherwise the search is case insensitive.
8627
8628   \sa QString::lastIndexOf(), indexOf(), contains(), count()
8629 */
8630 int QStringRef::lastIndexOf(const QStringRef &str, int from, Qt::CaseSensitivity cs) const
8631 {
8632     const int sl = str.size();
8633     if (sl == 1)
8634         return lastIndexOf(str.at(0), from, cs);
8635
8636     const int l = size();
8637     if (from < 0)
8638         from += l;
8639     int delta = l - sl;
8640     if (from == l && sl == 0)
8641         return from;
8642     if (from < 0 || from >= l || delta < 0)
8643         return -1;
8644     if (from > delta)
8645         from = delta;
8646
8647     return lastIndexOfHelper(reinterpret_cast<const ushort*>(unicode()), from,
8648                              reinterpret_cast<const ushort*>(str.unicode()),
8649                              str.size(), cs);
8650 }
8651
8652 /*!
8653     \since 4.8
8654     Returns the number of (potentially overlapping) occurrences of
8655     the string \a str in this string reference.
8656
8657     If \a cs is Qt::CaseSensitive (default), the search is
8658     case sensitive; otherwise the search is case insensitive.
8659
8660     \sa QString::count(), contains(), indexOf()
8661 */
8662 int QStringRef::count(const QString &str, Qt::CaseSensitivity cs) const
8663 {
8664     return qt_string_count(unicode(), size(), str.unicode(), str.size(), cs);
8665 }
8666
8667 /*!
8668     \since 4.8
8669     \overload count()
8670
8671     Returns the number of occurrences of the character \a ch in the
8672     string reference.
8673
8674     If \a cs is Qt::CaseSensitive (default), the search is
8675     case sensitive; otherwise the search is case insensitive.
8676
8677     \sa QString::count(), contains(), indexOf()
8678 */
8679 int QStringRef::count(QChar ch, Qt::CaseSensitivity cs) const
8680 {
8681     return qt_string_count(unicode(), size(), ch, cs);
8682 }
8683
8684 /*!
8685     \since 4.8
8686     \overload count()
8687
8688     Returns the number of (potentially overlapping) occurrences of the
8689     string reference \a str in this string reference.
8690
8691     If \a cs is Qt::CaseSensitive (default), the search is
8692     case sensitive; otherwise the search is case insensitive.
8693
8694     \sa QString::count(), contains(), indexOf()
8695 */
8696 int QStringRef::count(const QStringRef &str, Qt::CaseSensitivity cs) const
8697 {
8698     return qt_string_count(unicode(), size(), str.unicode(), str.size(), cs);
8699 }
8700
8701 /*!
8702     \since 4.8
8703
8704     Returns true if the string reference starts with \a str; otherwise
8705     returns false.
8706
8707     If \a cs is Qt::CaseSensitive (default), the search is
8708     case sensitive; otherwise the search is case insensitive.
8709
8710     \sa QString::startsWith(), endsWith()
8711 */
8712 bool QStringRef::startsWith(const QString &str, Qt::CaseSensitivity cs) const
8713 {
8714     return qt_starts_with(isNull() ? 0 : unicode(), size(),
8715                           str.isNull() ? 0 : str.unicode(), str.size(), cs);
8716 }
8717
8718 /*!
8719     \since 4.8
8720     \overload startsWith()
8721     \sa QString::startsWith(), endsWith()
8722 */
8723 bool QStringRef::startsWith(QLatin1String str, Qt::CaseSensitivity cs) const
8724 {
8725     return qt_starts_with(isNull() ? 0 : unicode(), size(), str, cs);
8726 }
8727
8728 /*!
8729     \since 4.8
8730     \overload startsWith()
8731     \sa QString::startsWith(), endsWith()
8732 */
8733 bool QStringRef::startsWith(const QStringRef &str, Qt::CaseSensitivity cs) const
8734 {
8735     return qt_starts_with(isNull() ? 0 : unicode(), size(),
8736                           str.isNull() ? 0 : str.unicode(), str.size(), cs);
8737 }
8738
8739 /*!
8740     \since 4.8
8741     \overload startsWith()
8742
8743     Returns true if the string reference starts with \a ch; otherwise
8744     returns false.
8745
8746     If \a cs is Qt::CaseSensitive (default), the search is case
8747     sensitive; otherwise the search is case insensitive.
8748
8749     \sa QString::startsWith(), endsWith()
8750 */
8751 bool QStringRef::startsWith(QChar ch, Qt::CaseSensitivity cs) const
8752 {
8753     if (!isEmpty()) {
8754         const ushort *data = reinterpret_cast<const ushort*>(unicode());
8755         return (cs == Qt::CaseSensitive
8756                 ? data[0] == ch
8757                 : foldCase(data[0]) == foldCase(ch.unicode()));
8758     } else {
8759         return false;
8760     }
8761 }
8762
8763 /*!
8764     \since 4.8
8765     Returns true if the string reference ends with \a str; otherwise
8766     returns false.
8767
8768     If \a cs is Qt::CaseSensitive (default), the search is case
8769     sensitive; otherwise the search is case insensitive.
8770
8771     \sa QString::endsWith(), startsWith()
8772 */
8773 bool QStringRef::endsWith(const QString &str, Qt::CaseSensitivity cs) const
8774 {
8775     return qt_ends_with(isNull() ? 0 : unicode(), size(),
8776                         str.isNull() ? 0 : str.unicode(), str.size(), cs);
8777 }
8778
8779 /*!
8780     \since 4.8
8781     \overload endsWith()
8782
8783     Returns true if the string reference ends with \a ch; otherwise
8784     returns false.
8785
8786     If \a cs is Qt::CaseSensitive (default), the search is case
8787     sensitive; otherwise the search is case insensitive.
8788
8789     \sa QString::endsWith(), endsWith()
8790 */
8791 bool QStringRef::endsWith(QChar ch, Qt::CaseSensitivity cs) const
8792 {
8793     if (!isEmpty()) {
8794         const ushort *data = reinterpret_cast<const ushort*>(unicode());
8795         const int size = length();
8796         return (cs == Qt::CaseSensitive
8797                 ? data[size - 1] == ch
8798                 : foldCase(data[size - 1]) == foldCase(ch.unicode()));
8799     } else {
8800         return false;
8801     }
8802 }
8803
8804 /*!
8805     \since 4.8
8806     \overload endsWith()
8807     \sa QString::endsWith(), endsWith()
8808 */
8809 bool QStringRef::endsWith(QLatin1String str, Qt::CaseSensitivity cs) const
8810 {
8811     return qt_ends_with(isNull() ? 0 : unicode(), size(), str, cs);
8812 }
8813
8814 /*!
8815     \since 4.8
8816     \overload endsWith()
8817     \sa QString::endsWith(), endsWith()
8818 */
8819 bool QStringRef::endsWith(const QStringRef &str, Qt::CaseSensitivity cs) const
8820 {
8821     return qt_ends_with(isNull() ? 0 : unicode(), size(),
8822                         str.isNull() ? 0 : str.unicode(), str.size(), cs);
8823 }
8824
8825
8826 /*! \fn bool QStringRef::contains(const QString &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
8827
8828     \since 4.8
8829     Returns true if this string reference contains an occurrence of
8830     the string \a str; otherwise returns false.
8831
8832     If \a cs is Qt::CaseSensitive (default), the search is
8833     case sensitive; otherwise the search is case insensitive.
8834
8835     \sa indexOf(), count()
8836 */
8837
8838 /*! \fn bool QStringRef::contains(QChar ch, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
8839
8840     \overload contains()
8841     \since 4.8
8842
8843     Returns true if this string contains an occurrence of the
8844     character \a ch; otherwise returns false.
8845
8846     If \a cs is Qt::CaseSensitive (default), the search is
8847     case sensitive; otherwise the search is case insensitive.
8848
8849 */
8850
8851 /*! \fn bool QStringRef::contains(const QStringRef &str, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
8852     \overload contains()
8853     \since 4.8
8854
8855     Returns true if this string reference contains an occurrence of
8856     the string reference \a str; otherwise returns false.
8857
8858     If \a cs is Qt::CaseSensitive (default), the search is
8859     case sensitive; otherwise the search is case insensitive.
8860
8861     \sa indexOf(), count()
8862 */
8863
8864 /*! \fn bool QStringRef::contains(QLatin1String str, Qt::CaseSensitivity cs) const
8865     \since 4,8
8866     \overload contains()
8867
8868     Returns true if this string reference contains an occurrence of
8869     the string \a str; otherwise returns false.
8870
8871     If \a cs is Qt::CaseSensitive (default), the search is
8872     case sensitive; otherwise the search is case insensitive.
8873
8874     \sa indexOf(), count()
8875 */
8876
8877 static inline int qt_last_index_of(const QChar *haystack, int haystackLen, QChar needle,
8878                                    int from, Qt::CaseSensitivity cs)
8879 {
8880     ushort c = needle.unicode();
8881     if (from < 0)
8882         from += haystackLen;
8883     if (from < 0 || from >= haystackLen)
8884         return -1;
8885     if (from >= 0) {
8886         const ushort *b = reinterpret_cast<const ushort*>(haystack);
8887         const ushort *n = b + from;
8888         if (cs == Qt::CaseSensitive) {
8889             for (; n >= b; --n)
8890                 if (*n == c)
8891                     return n - b;
8892         } else {
8893             c = foldCase(c);
8894             for (; n >= b; --n)
8895                 if (foldCase(*n) == c)
8896                     return n - b;
8897         }
8898     }
8899     return -1;
8900
8901
8902 }
8903
8904 static inline int qt_string_count(const QChar *haystack, int haystackLen,
8905                                   const QChar *needle, int needleLen,
8906                                   Qt::CaseSensitivity cs)
8907 {
8908     int num = 0;
8909     int i = -1;
8910     if (haystackLen > 500 && needleLen > 5) {
8911         QStringMatcher matcher(needle, needleLen, cs);
8912         while ((i = matcher.indexIn(haystack, haystackLen, i + 1)) != -1)
8913             ++num;
8914     } else {
8915         while ((i = qFindString(haystack, haystackLen, i + 1, needle, needleLen, cs)) != -1)
8916             ++num;
8917     }
8918     return num;
8919 }
8920
8921 static inline int qt_string_count(const QChar *unicode, int size, QChar ch,
8922                                   Qt::CaseSensitivity cs)
8923 {
8924     ushort c = ch.unicode();
8925     int num = 0;
8926     const ushort *b = reinterpret_cast<const ushort*>(unicode);
8927     const ushort *i = b + size;
8928     if (cs == Qt::CaseSensitive) {
8929         while (i != b)
8930             if (*--i == c)
8931                 ++num;
8932     } else {
8933         c = foldCase(c);
8934         while (i != b)
8935             if (foldCase(*(--i)) == c)
8936                 ++num;
8937     }
8938     return num;
8939 }
8940
8941 static inline int qt_find_latin1_string(const QChar *haystack, int size,
8942                                         const QLatin1String &needle,
8943                                         int from, Qt::CaseSensitivity cs)
8944 {
8945     const char *latin1 = needle.latin1();
8946     int len = needle.size();
8947     QVarLengthArray<ushort> s(len);
8948     for (int i = 0; i < len; ++i)
8949         s[i] = latin1[i];
8950
8951     return qFindString(haystack, size, from,
8952                        reinterpret_cast<const QChar*>(s.constData()), len, cs);
8953 }
8954
8955 static inline bool qt_starts_with(const QChar *haystack, int haystackLen,
8956                                   const QChar *needle, int needleLen, Qt::CaseSensitivity cs)
8957 {
8958     if (!haystack)
8959         return !needle;
8960     if (haystackLen == 0)
8961         return needleLen == 0;
8962     if (needleLen > haystackLen)
8963         return false;
8964
8965     const ushort *h = reinterpret_cast<const ushort*>(haystack);
8966     const ushort *n = reinterpret_cast<const ushort*>(needle);
8967
8968     if (cs == Qt::CaseSensitive) {
8969         return qMemEquals(h, n, needleLen);
8970     } else {
8971         uint last = 0;
8972         uint olast = 0;
8973         for (int i = 0; i < needleLen; ++i)
8974             if (foldCase(h[i], last) != foldCase(n[i], olast))
8975                 return false;
8976     }
8977     return true;
8978 }
8979
8980 static inline bool qt_starts_with(const QChar *haystack, int haystackLen,
8981                                   QLatin1String needle, Qt::CaseSensitivity cs)
8982 {
8983     if (!haystack)
8984         return !needle.latin1();
8985     if (haystackLen == 0)
8986         return !needle.latin1() || *needle.latin1() == 0;
8987     const int slen = needle.size();
8988     if (slen > haystackLen)
8989         return false;
8990     const ushort *data = reinterpret_cast<const ushort*>(haystack);
8991     const uchar *latin = reinterpret_cast<const uchar*>(needle.latin1());
8992     if (cs == Qt::CaseSensitive) {
8993         for (int i = 0; i < slen; ++i)
8994             if (data[i] != latin[i])
8995                 return false;
8996     } else {
8997         for (int i = 0; i < slen; ++i)
8998             if (foldCase(data[i]) != foldCase((ushort)latin[i]))
8999                 return false;
9000     }
9001     return true;
9002 }
9003
9004 static inline bool qt_ends_with(const QChar *haystack, int haystackLen,
9005                                 const QChar *needle, int needleLen, Qt::CaseSensitivity cs)
9006 {
9007     if (!haystack)
9008         return !needle;
9009     if (haystackLen == 0)
9010         return needleLen == 0;
9011     const int pos = haystackLen - needleLen;
9012     if (pos < 0)
9013         return false;
9014
9015     const ushort *h = reinterpret_cast<const ushort*>(haystack);
9016     const ushort *n = reinterpret_cast<const ushort*>(needle);
9017
9018     if (cs == Qt::CaseSensitive) {
9019         return qMemEquals(h + pos, n, needleLen);
9020     } else {
9021         uint last = 0;
9022         uint olast = 0;
9023         for (int i = 0; i < needleLen; i++)
9024             if (foldCase(h[pos+i], last) != foldCase(n[i], olast))
9025                 return false;
9026     }
9027     return true;
9028 }
9029
9030
9031 static inline bool qt_ends_with(const QChar *haystack, int haystackLen,
9032                                 QLatin1String needle, Qt::CaseSensitivity cs)
9033 {
9034     if (!haystack)
9035         return !needle.latin1();
9036     if (haystackLen == 0)
9037         return !needle.latin1() || *needle.latin1() == 0;
9038     const int slen = needle.size();
9039     int pos = haystackLen - slen;
9040     if (pos < 0)
9041         return false;
9042     const uchar *latin = reinterpret_cast<const uchar*>(needle.latin1());
9043     const ushort *data = reinterpret_cast<const ushort*>(haystack);
9044     if (cs == Qt::CaseSensitive) {
9045         for (int i = 0; i < slen; i++)
9046             if (data[pos+i] != latin[i])
9047                 return false;
9048     } else {
9049         for (int i = 0; i < slen; i++)
9050             if (foldCase(data[pos+i]) != foldCase((ushort)latin[i]))
9051                 return false;
9052     }
9053     return true;
9054 }
9055
9056 /*!
9057     \since 4.8
9058
9059     Returns a Latin-1 representation of the string as a QByteArray.
9060
9061     The returned byte array is undefined if the string contains non-Latin1
9062     characters. Those characters may be suppressed or replaced with a
9063     question mark.
9064
9065     \sa toAscii(), toUtf8(), toLocal8Bit(), QTextCodec
9066 */
9067 QByteArray QStringRef::toLatin1() const
9068 {
9069     return toLatin1_helper(unicode(), length());
9070 }
9071
9072 /*!
9073     \since 4.8
9074
9075     Returns an 8-bit representation of the string as a QByteArray.
9076
9077     This function does the same as toLatin1().
9078
9079     Note that, despite the name, this function does not necessarily return an US-ASCII
9080     (ANSI X3.4-1986) string and its result may not be US-ASCII compatible.
9081
9082     \sa toLatin1(), toUtf8(), toLocal8Bit(), QTextCodec
9083 */
9084 QByteArray QStringRef::toAscii() const
9085 {
9086     return toLatin1();
9087 }
9088
9089 /*!
9090     \since 4.8
9091
9092     Returns the local 8-bit representation of the string as a
9093     QByteArray. The returned byte array is undefined if the string
9094     contains characters not supported by the local 8-bit encoding.
9095
9096     QTextCodec::codecForLocale() is used to perform the conversion from
9097     Unicode. If the locale encoding could not be determined, this function
9098     does the same as toLatin1().
9099
9100     If this string contains any characters that cannot be encoded in the
9101     locale, the returned byte array is undefined. Those characters may be
9102     suppressed or replaced by another.
9103
9104     \sa toAscii(), toLatin1(), toUtf8(), QTextCodec
9105 */
9106 QByteArray QStringRef::toLocal8Bit() const
9107 {
9108 #ifndef QT_NO_TEXTCODEC
9109     if (QTextCodec::codecForLocale())
9110         return QTextCodec::codecForLocale()->fromUnicode(unicode(), length());
9111 #endif // QT_NO_TEXTCODEC
9112     return toLatin1();
9113 }
9114
9115 /*!
9116     \since 4.8
9117
9118     Returns a UTF-8 representation of the string as a QByteArray.
9119
9120     UTF-8 is a Unicode codec and can represent all characters in a Unicode
9121     string like QString.
9122
9123     However, in the Unicode range, there are certain codepoints that are not
9124     considered characters. The Unicode standard reserves the last two
9125     codepoints in each Unicode Plane (U+FFFE, U+FFFF, U+1FFFE, U+1FFFF,
9126     U+2FFFE, etc.), as well as 16 codepoints in the range U+FDD0..U+FDDF,
9127     inclusive, as non-characters. If any of those appear in the string, they
9128     may be discarded and will not appear in the UTF-8 representation, or they
9129     may be replaced by one or more replacement characters.
9130
9131     \sa toAscii(), toLatin1(), toLocal8Bit(), QTextCodec
9132 */
9133 QByteArray QStringRef::toUtf8() const
9134 {
9135     if (isNull())
9136         return QByteArray();
9137
9138     return QUtf8::convertFromUnicode(constData(), length(), 0);
9139 }
9140
9141 /*!
9142     \since 4.8
9143
9144     Returns a UCS-4/UTF-32 representation of the string as a QVector<uint>.
9145
9146     UCS-4 is a Unicode codec and is lossless. All characters from this string
9147     can be encoded in UCS-4.
9148
9149     \sa toAscii(), toLatin1(), toLocal8Bit(), QTextCodec
9150 */
9151 QVector<uint> QStringRef::toUcs4() const
9152 {
9153     QVector<uint> v(length());
9154     uint *a = v.data();
9155     int len = QString::toUcs4_helper(reinterpret_cast<const ushort *>(unicode()), length(), a);
9156     v.resize(len);
9157     return v;
9158 }
9159
9160
9161 /*!
9162     \obsolete
9163     \fn QString Qt::escape(const QString &plain)
9164
9165     \sa QString::toHtmlEscaped()
9166 */
9167
9168 /*!
9169     Converts the plain text string \a plain to a HTML string with
9170     HTML metacharacters \c{<}, \c{>}, \c{&}, and \c{"} replaced by HTML
9171     entities.
9172
9173     Example:
9174
9175     \snippet doc/src/snippets/code/src_corelib_tools_qstring.cpp 7
9176 */
9177 QString QString::toHtmlEscaped() const
9178 {
9179     QString rich;
9180     const int len = length();
9181     rich.reserve(int(len * 1.1));
9182     for (int i = 0; i < len; ++i) {
9183         if (at(i) == QLatin1Char('<'))
9184             rich += QLatin1String("&lt;");
9185         else if (at(i) == QLatin1Char('>'))
9186             rich += QLatin1String("&gt;");
9187         else if (at(i) == QLatin1Char('&'))
9188             rich += QLatin1String("&amp;");
9189         else if (at(i) == QLatin1Char('"'))
9190             rich += QLatin1String("&quot;");
9191         else
9192             rich += at(i);
9193     }
9194     rich.squeeze();
9195     return rich;
9196 }
9197
9198 /*!
9199   \macro QStringLiteral(str)
9200   \relates QString
9201
9202   The macro generates the data for a QString out of \a str at compile time if the compiler supports it.
9203   Creating a QString from it is free in this case, and the generated string data is stored in
9204   the read-only segment of the compiled object file.
9205
9206   For compilers not supporting the creation of compile time strings, QStringLiteral will fall back to
9207   QLatin1String.
9208
9209   The result of the QStringLiteral expression can be cast into a QString.
9210
9211   If you have code looking like:
9212   \code
9213   if (node.hasAttribute("http-contents-length")) //...
9214   \endcode
9215   One temporary QString will be created to be passed as the hasAttribute function parameter.
9216   This can be quite expensive, as it involves a memory allocation and the copy and the conversion
9217   of the data into QString's internal encoding.
9218
9219   This can be avoided by doing
9220   \code
9221   if (node.hasAttribute(QStringLiteral("http-contents-length"))) //...
9222   \endcode
9223   Then the QString's internal data will be generated at compile time and no conversion or allocation
9224   will occur at runtime
9225
9226   Using QStringLiteral instead of a double quoted ascii literal can significantly speed up creation
9227   of QString's from data known at compile time.
9228
9229   If the compiler is C++11 enabled the string \a str can actually contain unicode data.
9230
9231   \note There are still a few cases in which QLatin1String is more efficient than QStringLiteral:
9232   If it is passed to a function that has an overload that takes the QLatin1String directly, without
9233   conversion to QString. For instance, this is the case of QString::operator==
9234   \code
9235   if (attribute.name() == QLatin1String("http-contents-length")) //...
9236   \endcode
9237 */
9238
9239 QT_END_NAMESPACE