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