d8c0668a39b49314b6b30fea062f05ff242147a3
[profile/ivi/qtbase.git] / src / corelib / tools / qbytearray.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
6 **
7 ** This file is part of the QtCore module of the Qt Toolkit.
8 **
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 **
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 **
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
29 **
30 ** Other Usage
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "qbytearray.h"
43 #include "qbytearraymatcher.h"
44 #include "qtools_p.h"
45 #include "qstring.h"
46 #include "qlist.h"
47 #include "qlocale.h"
48 #include "qlocale_p.h"
49 #include "qscopedpointer.h"
50 #include <qdatastream.h>
51
52 #ifndef QT_NO_COMPRESS
53 #include <zlib.h>
54 #endif
55 #include <ctype.h>
56 #include <limits.h>
57 #include <string.h>
58 #include <stdlib.h>
59
60 #define IS_RAW_DATA(d) ((d)->offset != 0)
61
62 QT_BEGIN_NAMESPACE
63
64
65 int qFindByteArray(
66     const char *haystack0, int haystackLen, int from,
67     const char *needle0, int needleLen);
68
69
70 int qAllocMore(int alloc, int extra)
71 {
72     if (alloc == 0 && extra == 0)
73         return 0;
74     const int page = 1 << 12;
75     int nalloc;
76     alloc += extra;
77     if (alloc < 1<<6) {
78         nalloc = (1<<3) + ((alloc >>3) << 3);
79     } else  {
80         // don't do anything if the loop will overflow signed int.
81         if (alloc >= INT_MAX/2)
82             return INT_MAX;
83         nalloc = (alloc < page) ? 1 << 3 : page;
84         while (nalloc < alloc) {
85             if (nalloc <= 0)
86                 return INT_MAX;
87             nalloc *= 2;
88         }
89     }
90     return nalloc - extra;
91 }
92
93 /*****************************************************************************
94   Safe and portable C string functions; extensions to standard string.h
95  *****************************************************************************/
96
97 /*! \relates QByteArray
98
99     Returns a duplicate string.
100
101     Allocates space for a copy of \a src, copies it, and returns a
102     pointer to the copy. If \a src is 0, it immediately returns 0.
103
104     Ownership is passed to the caller, so the returned string must be
105     deleted using \c delete[].
106 */
107
108 char *qstrdup(const char *src)
109 {
110     if (!src)
111         return 0;
112     char *dst = new char[strlen(src) + 1];
113     return qstrcpy(dst, src);
114 }
115
116 /*! \relates QByteArray
117
118     Copies all the characters up to and including the '\\0' from \a
119     src into \a dst and returns a pointer to \a dst. If \a src is 0,
120     it immediately returns 0.
121
122     This function assumes that \a dst is large enough to hold the
123     contents of \a src.
124
125     \sa qstrncpy()
126 */
127
128 char *qstrcpy(char *dst, const char *src)
129 {
130     if (!src)
131         return 0;
132 #if defined(_MSC_VER) && _MSC_VER >= 1400
133     int len = qstrlen(src);
134         // This is actually not secure!!! It will be fixed
135         // properly in a later release!
136     if (len >= 0 && strcpy_s(dst, len+1, src) == 0)
137             return dst;
138     return 0;
139 #else
140     return strcpy(dst, src);
141 #endif
142 }
143
144 /*! \relates QByteArray
145
146     A safe \c strncpy() function.
147
148     Copies at most \a len bytes from \a src (stopping at \a len or the
149     terminating '\\0' whichever comes first) into \a dst and returns a
150     pointer to \a dst. Guarantees that \a dst is '\\0'-terminated. If
151     \a src or \a dst is 0, returns 0 immediately.
152
153     This function assumes that \a dst is at least \a len characters
154     long.
155
156     \note When compiling with Visual C++ compiler version 14.00
157     (Visual C++ 2005) or later, internally the function strncpy_s
158     will be used.
159
160     \sa qstrcpy()
161 */
162
163 char *qstrncpy(char *dst, const char *src, uint len)
164 {
165     if (!src || !dst)
166         return 0;
167 #if defined(_MSC_VER) && _MSC_VER >= 1400
168         strncpy_s(dst, len, src, len-1);
169 #else
170     strncpy(dst, src, len);
171 #endif
172     if (len > 0)
173         dst[len-1] = '\0';
174     return dst;
175 }
176
177 /*! \fn uint qstrlen(const char *str)
178     \relates QByteArray
179
180     A safe \c strlen() function.
181
182     Returns the number of characters that precede the terminating '\\0',
183     or 0 if \a str is 0.
184
185     \sa qstrnlen()
186 */
187
188 /*! \fn uint qstrnlen(const char *str, uint maxlen)
189     \relates QByteArray
190     \since 4.2
191
192     A safe \c strnlen() function.
193
194     Returns the number of characters that precede the terminating '\\0', but
195     at most \a maxlen. If \a str is 0, returns 0.
196
197     \sa qstrlen()
198 */
199
200 /*!
201     \relates QByteArray
202
203     A safe \c strcmp() function.
204
205     Compares \a str1 and \a str2. Returns a negative value if \a str1
206     is less than \a str2, 0 if \a str1 is equal to \a str2 or a
207     positive value if \a str1 is greater than \a str2.
208
209     Special case 1: Returns 0 if \a str1 and \a str2 are both 0.
210
211     Special case 2: Returns an arbitrary non-zero value if \a str1 is 0
212     or \a str2 is 0 (but not both).
213
214     \sa qstrncmp(), qstricmp(), qstrnicmp(), {8-bit Character Comparisons}
215 */
216 int qstrcmp(const char *str1, const char *str2)
217 {
218     return (str1 && str2) ? strcmp(str1, str2)
219         : (str1 ? 1 : (str2 ? -1 : 0));
220 }
221
222 /*! \fn int qstrncmp(const char *str1, const char *str2, uint len);
223
224     \relates QByteArray
225
226     A safe \c strncmp() function.
227
228     Compares at most \a len bytes of \a str1 and \a str2.
229
230     Returns a negative value if \a str1 is less than \a str2, 0 if \a
231     str1 is equal to \a str2 or a positive value if \a str1 is greater
232     than \a str2.
233
234     Special case 1: Returns 0 if \a str1 and \a str2 are both 0.
235
236     Special case 2: Returns a random non-zero value if \a str1 is 0
237     or \a str2 is 0 (but not both).
238
239     \sa qstrcmp(), qstricmp(), qstrnicmp(), {8-bit Character Comparisons}
240 */
241
242 /*! \relates QByteArray
243
244     A safe \c stricmp() function.
245
246     Compares \a str1 and \a str2 ignoring the case of the
247     characters. The encoding of the strings is assumed to be Latin-1.
248
249     Returns a negative value if \a str1 is less than \a str2, 0 if \a
250     str1 is equal to \a str2 or a positive value if \a str1 is greater
251     than \a str2.
252
253     Special case 1: Returns 0 if \a str1 and \a str2 are both 0.
254
255     Special case 2: Returns a random non-zero value if \a str1 is 0
256     or \a str2 is 0 (but not both).
257
258     \sa qstrcmp(), qstrncmp(), qstrnicmp(), {8-bit Character Comparisons}
259 */
260
261 int qstricmp(const char *str1, const char *str2)
262 {
263     register const uchar *s1 = reinterpret_cast<const uchar *>(str1);
264     register const uchar *s2 = reinterpret_cast<const uchar *>(str2);
265     int res;
266     uchar c;
267     if (!s1 || !s2)
268         return s1 ? 1 : (s2 ? -1 : 0);
269     for (; !(res = (c = QChar::toLower((ushort)*s1)) - QChar::toLower((ushort)*s2)); s1++, s2++)
270         if (!c)                                // strings are equal
271             break;
272     return res;
273 }
274
275 /*! \relates QByteArray
276
277     A safe \c strnicmp() function.
278
279     Compares at most \a len bytes of \a str1 and \a str2 ignoring the
280     case of the characters. The encoding of the strings is assumed to
281     be Latin-1.
282
283     Returns a negative value if \a str1 is less than \a str2, 0 if \a str1
284     is equal to \a str2 or a positive value if \a str1 is greater than \a
285     str2.
286
287     Special case 1: Returns 0 if \a str1 and \a str2 are both 0.
288
289     Special case 2: Returns a random non-zero value if \a str1 is 0
290     or \a str2 is 0 (but not both).
291
292     \sa qstrcmp(), qstrncmp(), qstricmp(), {8-bit Character Comparisons}
293 */
294
295 int qstrnicmp(const char *str1, const char *str2, uint len)
296 {
297     register const uchar *s1 = reinterpret_cast<const uchar *>(str1);
298     register const uchar *s2 = reinterpret_cast<const uchar *>(str2);
299     int res;
300     uchar c;
301     if (!s1 || !s2)
302         return s1 ? 1 : (s2 ? -1 : 0);
303     for (; len--; s1++, s2++) {
304         if ((res = (c = QChar::toLower((ushort)*s1)) - QChar::toLower((ushort)*s2)))
305             return res;
306         if (!c)                                // strings are equal
307             break;
308     }
309     return 0;
310 }
311
312 /*!
313     \internal
314  */
315 int qstrcmp(const QByteArray &str1, const char *str2)
316 {
317     if (!str2)
318         return str1.isEmpty() ? 0 : +1;
319
320     const char *str1data = str1.constData();
321     const char *str1end = str1data + str1.length();
322     for ( ; str1data < str1end && *str2; ++str1data, ++str2) {
323         register int diff = int(uchar(*str1data)) - uchar(*str2);
324         if (diff)
325             // found a difference
326             return diff;
327     }
328
329     // Why did we stop?
330     if (*str2 != '\0')
331         // not the null, so we stopped because str1 is shorter
332         return -1;
333     if (str1data < str1end)
334         // we haven't reached the end, so str1 must be longer
335         return +1;
336     return 0;
337 }
338
339 /*!
340     \internal
341  */
342 int qstrcmp(const QByteArray &str1, const QByteArray &str2)
343 {
344     int l1 = str1.length();
345     int l2 = str2.length();
346     int ret = memcmp(str1, str2, qMin(l1, l2));
347     if (ret != 0)
348         return ret;
349
350     // they matched qMin(l1, l2) bytes
351     // so the longer one is lexically after the shorter one
352     return l1 - l2;
353 }
354
355 // the CRC table below is created by the following piece of code
356 #if 0
357 static void createCRC16Table()                        // build CRC16 lookup table
358 {
359     register unsigned int i;
360     register unsigned int j;
361     unsigned short crc_tbl[16];
362     unsigned int v0, v1, v2, v3;
363     for (i = 0; i < 16; i++) {
364         v0 = i & 1;
365         v1 = (i >> 1) & 1;
366         v2 = (i >> 2) & 1;
367         v3 = (i >> 3) & 1;
368         j = 0;
369 #undef SET_BIT
370 #define SET_BIT(x, b, v) (x) |= (v) << (b)
371         SET_BIT(j,  0, v0);
372         SET_BIT(j,  7, v0);
373         SET_BIT(j, 12, v0);
374         SET_BIT(j,  1, v1);
375         SET_BIT(j,  8, v1);
376         SET_BIT(j, 13, v1);
377         SET_BIT(j,  2, v2);
378         SET_BIT(j,  9, v2);
379         SET_BIT(j, 14, v2);
380         SET_BIT(j,  3, v3);
381         SET_BIT(j, 10, v3);
382         SET_BIT(j, 15, v3);
383         crc_tbl[i] = j;
384     }
385     printf("static const quint16 crc_tbl[16] = {\n");
386     for (int i = 0; i < 16; i +=4)
387         printf("    0x%04x, 0x%04x, 0x%04x, 0x%04x,\n", crc_tbl[i], crc_tbl[i+1], crc_tbl[i+2], crc_tbl[i+3]);
388     printf("};\n");
389 }
390 #endif
391
392 static const quint16 crc_tbl[16] = {
393     0x0000, 0x1081, 0x2102, 0x3183,
394     0x4204, 0x5285, 0x6306, 0x7387,
395     0x8408, 0x9489, 0xa50a, 0xb58b,
396     0xc60c, 0xd68d, 0xe70e, 0xf78f
397 };
398
399 /*! 
400     \relates QByteArray
401
402     Returns the CRC-16 checksum of the first \a len bytes of \a data.
403
404     The checksum is independent of the byte order (endianness).
405
406     \note This function is a 16-bit cache conserving (16 entry table)
407     implementation of the CRC-16-CCITT algorithm.
408 */
409
410 quint16 qChecksum(const char *data, uint len)
411 {
412     register quint16 crc = 0xffff;
413     uchar c;
414     const uchar *p = reinterpret_cast<const uchar *>(data);
415     while (len--) {
416         c = *p++;
417         crc = ((crc >> 4) & 0x0fff) ^ crc_tbl[((crc ^ c) & 15)];
418         c >>= 4;
419         crc = ((crc >> 4) & 0x0fff) ^ crc_tbl[((crc ^ c) & 15)];
420     }
421     return ~crc & 0xffff;
422 }
423
424 /*!     
425     \fn QByteArray qCompress(const QByteArray& data, int compressionLevel)
426
427     \relates QByteArray
428
429     Compresses the \a data byte array and returns the compressed data
430     in a new byte array.
431
432     The \a compressionLevel parameter specifies how much compression
433     should be used. Valid values are between 0 and 9, with 9
434     corresponding to the greatest compression (i.e. smaller compressed
435     data) at the cost of using a slower algorithm. Smaller values (8,
436     7, ..., 1) provide successively less compression at slightly
437     faster speeds. The value 0 corresponds to no compression at all.
438     The default value is -1, which specifies zlib's default
439     compression.
440
441     \sa qUncompress()
442 */
443
444 /*! \relates QByteArray
445
446     \overload
447
448     Compresses the first \a nbytes of \a data and returns the
449     compressed data in a new byte array.
450 */
451
452 #ifndef QT_NO_COMPRESS
453 QByteArray qCompress(const uchar* data, int nbytes, int compressionLevel)
454 {
455     if (nbytes == 0) {
456         return QByteArray(4, '\0');
457     }
458     if (!data) {
459         qWarning("qCompress: Data is null");
460         return QByteArray();
461     }
462     if (compressionLevel < -1 || compressionLevel > 9)
463         compressionLevel = -1;
464
465     ulong len = nbytes + nbytes / 100 + 13;
466     QByteArray bazip;
467     int res;
468     do {
469         bazip.resize(len + 4);
470         res = ::compress2((uchar*)bazip.data()+4, &len, (uchar*)data, nbytes, compressionLevel);
471
472         switch (res) {
473         case Z_OK:
474             bazip.resize(len + 4);
475             bazip[0] = (nbytes & 0xff000000) >> 24;
476             bazip[1] = (nbytes & 0x00ff0000) >> 16;
477             bazip[2] = (nbytes & 0x0000ff00) >> 8;
478             bazip[3] = (nbytes & 0x000000ff);
479             break;
480         case Z_MEM_ERROR:
481             qWarning("qCompress: Z_MEM_ERROR: Not enough memory");
482             bazip.resize(0);
483             break;
484         case Z_BUF_ERROR:
485             len *= 2;
486             break;
487         }
488     } while (res == Z_BUF_ERROR);
489
490     return bazip;
491 }
492 #endif
493
494 /*!
495     \fn QByteArray qUncompress(const QByteArray &data)
496
497     \relates QByteArray
498
499     Uncompresses the \a data byte array and returns a new byte array
500     with the uncompressed data.
501
502     Returns an empty QByteArray if the input data was corrupt.
503
504     This function will uncompress data compressed with qCompress()
505     from this and any earlier Qt version, back to Qt 3.1 when this
506     feature was added.
507
508     \bold{Note:} If you want to use this function to uncompress external
509     data that was compressed using zlib, you first need to prepend a four
510     byte header to the byte array containing the data. The header must
511     contain the expected length (in bytes) of the uncompressed data,
512     expressed as an unsigned, big-endian, 32-bit integer.
513
514     \sa qCompress()
515 */
516
517 /*! \relates QByteArray
518
519     \overload
520
521     Uncompresses the first \a nbytes of \a data and returns a new byte
522     array with the uncompressed data.
523 */
524
525 #ifndef QT_NO_COMPRESS
526 QByteArray qUncompress(const uchar* data, int nbytes)
527 {
528     if (!data) {
529         qWarning("qUncompress: Data is null");
530         return QByteArray();
531     }
532     if (nbytes <= 4) {
533         if (nbytes < 4 || (data[0]!=0 || data[1]!=0 || data[2]!=0 || data[3]!=0))
534             qWarning("qUncompress: Input data is corrupted");
535         return QByteArray();
536     }
537     ulong expectedSize = (data[0] << 24) | (data[1] << 16) |
538                        (data[2] <<  8) | (data[3]      );
539     ulong len = qMax(expectedSize, 1ul);
540     QScopedPointer<QByteArray::Data, QScopedPointerPodDeleter> d;
541
542     forever {
543         ulong alloc = len;
544         if (len  >= (1u << 31u) - sizeof(QByteArray::Data)) {
545             //QByteArray does not support that huge size anyway.
546             qWarning("qUncompress: Input data is corrupted");
547             return QByteArray();
548         }
549         QByteArray::Data *p = static_cast<QByteArray::Data *>(qRealloc(d.data(), sizeof(QByteArray::Data) + alloc + 1));
550         if (!p) {
551             // we are not allowed to crash here when compiling with QT_NO_EXCEPTIONS
552             qWarning("qUncompress: could not allocate enough memory to uncompress data");
553             return QByteArray();
554         }
555         d.take(); // realloc was successful
556         d.reset(p);
557         d->offset = 0;
558
559         int res = ::uncompress((uchar*)d->data(), &len,
560                                (uchar*)data+4, nbytes-4);
561
562         switch (res) {
563         case Z_OK:
564             if (len != alloc) {
565                 if (len  >= (1u << 31u) - sizeof(QByteArray::Data)) {
566                     //QByteArray does not support that huge size anyway.
567                     qWarning("qUncompress: Input data is corrupted");
568                     return QByteArray();
569                 }
570                 QByteArray::Data *p = static_cast<QByteArray::Data *>(qRealloc(d.data(), sizeof(QByteArray::Data) + len + 1));
571                 if (!p) {
572                     // we are not allowed to crash here when compiling with QT_NO_EXCEPTIONS
573                     qWarning("qUncompress: could not allocate enough memory to uncompress data");
574                     return QByteArray();
575                 }
576                 d.take(); // realloc was successful
577                 d.reset(p);
578             }
579             d->ref = 1;
580             d->size = len;
581             d->alloc = len;
582             d->capacityReserved = false;
583             d->offset = 0;
584             d->data()[len] = 0;
585
586             return QByteArray(d.take(), 0, 0);
587
588         case Z_MEM_ERROR:
589             qWarning("qUncompress: Z_MEM_ERROR: Not enough memory");
590             return QByteArray();
591
592         case Z_BUF_ERROR:
593             len *= 2;
594             continue;
595
596         case Z_DATA_ERROR:
597             qWarning("qUncompress: Z_DATA_ERROR: Input data is corrupted");
598             return QByteArray();
599         }
600     }
601 }
602 #endif
603
604 static inline bool qIsUpper(char c)
605 {
606     return c >= 'A' && c <= 'Z';
607 }
608
609 static inline char qToLower(char c)
610 {
611     if (c >= 'A' && c <= 'Z')
612         return c - 'A' + 'a';
613     else
614         return c;
615 }
616
617 const QConstByteArrayData<1> QByteArray::shared_null = { { Q_REFCOUNT_INITIALIZER(-1),
618                                                            0, 0, 0, { 0 } }, { 0 } };
619 const QConstByteArrayData<1> QByteArray::shared_empty = { { Q_REFCOUNT_INITIALIZER(-1),
620                                                             0, 0, 0, { 0 } }, { 0 } };
621
622 /*!
623     \class QByteArray
624     \brief The QByteArray class provides an array of bytes.
625
626     \ingroup tools
627     \ingroup shared
628     \ingroup string-processing
629
630     \reentrant
631
632     QByteArray can be used to store both raw bytes (including '\\0's)
633     and traditional 8-bit '\\0'-terminated strings. Using QByteArray
634     is much more convenient than using \c{const char *}. Behind the
635     scenes, it always ensures that the data is followed by a '\\0'
636     terminator, and uses \l{implicit sharing} (copy-on-write) to
637     reduce memory usage and avoid needless copying of data.
638
639     In addition to QByteArray, Qt also provides the QString class to
640     store string data. For most purposes, QString is the class you
641     want to use. It stores 16-bit Unicode characters, making it easy
642     to store non-ASCII/non-Latin-1 characters in your application.
643     Furthermore, QString is used throughout in the Qt API. The two
644     main cases where QByteArray is appropriate are when you need to
645     store raw binary data, and when memory conservation is critical
646     (e.g., with Qt for Embedded Linux).
647
648     One way to initialize a QByteArray is simply to pass a \c{const
649     char *} to its constructor. For example, the following code
650     creates a byte array of size 5 containing the data "Hello":
651
652     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 0
653
654     Although the size() is 5, the byte array also maintains an extra
655     '\\0' character at the end so that if a function is used that
656     asks for a pointer to the underlying data (e.g. a call to
657     data()), the data pointed to is guaranteed to be
658     '\\0'-terminated.
659
660     QByteArray makes a deep copy of the \c{const char *} data, so you
661     can modify it later without experiencing side effects. (If for
662     performance reasons you don't want to take a deep copy of the
663     character data, use QByteArray::fromRawData() instead.)
664
665     Another approach is to set the size of the array using resize()
666     and to initialize the data byte per byte. QByteArray uses 0-based
667     indexes, just like C++ arrays. To access the byte at a particular
668     index position, you can use operator[](). On non-const byte
669     arrays, operator[]() returns a reference to a byte that can be
670     used on the left side of an assignment. For example:
671
672     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 1
673
674     For read-only access, an alternative syntax is to use at():
675
676     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 2
677
678     at() can be faster than operator[](), because it never causes a
679     \l{deep copy} to occur.
680
681     To extract many bytes at a time, use left(), right(), or mid().
682
683     A QByteArray can embed '\\0' bytes. The size() function always
684     returns the size of the whole array, including embedded '\\0'
685     bytes. If you want to obtain the length of the data up to and
686     excluding the first '\\0' character, call qstrlen() on the byte
687     array.
688
689     After a call to resize(), newly allocated bytes have undefined
690     values. To set all the bytes to a particular value, call fill().
691
692     To obtain a pointer to the actual character data, call data() or
693     constData(). These functions return a pointer to the beginning of the data.
694     The pointer is guaranteed to remain valid until a non-const function is
695     called on the QByteArray. It is also guaranteed that the data ends with a
696     '\\0' byte unless the QByteArray was created from a \l{fromRawData()}{raw
697     data}. This '\\0' byte is automatically provided by QByteArray and is not
698     counted in size().
699
700     QByteArray provides the following basic functions for modifying
701     the byte data: append(), prepend(), insert(), replace(), and
702     remove(). For example:
703
704     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 3
705
706     The replace() and remove() functions' first two arguments are the
707     position from which to start erasing and the number of bytes that
708     should be erased.
709
710     When you append() data to a non-empty array, the array will be
711     reallocated and the new data copied to it. You can avoid this
712     behavior by calling reserve(), which preallocates a certain amount
713     of memory. You can also call capacity() to find out how much
714     memory QByteArray actually allocated. Data appended to an empty
715     array is not copied.
716
717     A frequent requirement is to remove whitespace characters from a
718     byte array ('\\n', '\\t', ' ', etc.). If you want to remove
719     whitespace from both ends of a QByteArray, use trimmed(). If you
720     want to remove whitespace from both ends and replace multiple
721     consecutive whitespaces with a single space character within the
722     byte array, use simplified().
723
724     If you want to find all occurrences of a particular character or
725     substring in a QByteArray, use indexOf() or lastIndexOf(). The
726     former searches forward starting from a given index position, the
727     latter searches backward. Both return the index position of the
728     character or substring if they find it; otherwise, they return -1.
729     For example, here's a typical loop that finds all occurrences of a
730     particular substring:
731
732     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 4
733
734     If you simply want to check whether a QByteArray contains a
735     particular character or substring, use contains(). If you want to
736     find out how many times a particular character or substring
737     occurs in the byte array, use count(). If you want to replace all
738     occurrences of a particular value with another, use one of the
739     two-parameter replace() overloads.
740
741     QByteArrays can be compared using overloaded operators such as
742     operator<(), operator<=(), operator==(), operator>=(), and so on.
743     The comparison is based exclusively on the numeric values
744     of the characters and is very fast, but is not what a human would
745     expect. QString::localeAwareCompare() is a better choice for
746     sorting user-interface strings.
747
748     For historical reasons, QByteArray distinguishes between a null
749     byte array and an empty byte array. A \e null byte array is a
750     byte array that is initialized using QByteArray's default
751     constructor or by passing (const char *)0 to the constructor. An
752     \e empty byte array is any byte array with size 0. A null byte
753     array is always empty, but an empty byte array isn't necessarily
754     null:
755
756     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 5
757
758     All functions except isNull() treat null byte arrays the same as
759     empty byte arrays. For example, data() returns a pointer to a
760     '\\0' character for a null byte array (\e not a null pointer),
761     and QByteArray() compares equal to QByteArray(""). We recommend
762     that you always use isEmpty() and avoid isNull().
763
764     \section1 Notes on Locale
765
766     \section2 Number-String Conversions
767
768     Functions that perform conversions between numeric data types and
769     strings are performed in the C locale, irrespective of the user's
770     locale settings. Use QString to perform locale-aware conversions
771     between numbers and strings.
772
773     \section2 8-bit Character Comparisons
774
775     In QByteArray, the notion of uppercase and lowercase and of which
776     character is greater than or less than another character is
777     locale dependent. This affects functions that support a case
778     insensitive option or that compare or lowercase or uppercase
779     their arguments. Case insensitive operations and comparisons will
780     be accurate if both strings contain only ASCII characters. (If \c
781     $LC_CTYPE is set, most Unix systems do "the right thing".)
782     Functions that this affects include contains(), indexOf(),
783     lastIndexOf(), operator<(), operator<=(), operator>(),
784     operator>=(), toLower() and toUpper().
785
786     This issue does not apply to QStrings since they represent
787     characters using Unicode.
788
789     \sa QString, QBitArray
790 */
791
792 /*! \fn QByteArray::iterator QByteArray::begin()
793
794     \internal
795 */
796
797 /*! \fn QByteArray::const_iterator QByteArray::begin() const
798
799     \internal
800 */
801
802 /*! \fn QByteArray::const_iterator QByteArray::constBegin() const
803
804     \internal
805 */
806
807 /*! \fn QByteArray::iterator QByteArray::end()
808
809     \internal
810 */
811
812 /*! \fn QByteArray::const_iterator QByteArray::end() const
813
814     \internal
815 */
816
817 /*! \fn QByteArray::const_iterator QByteArray::constEnd() const
818
819     \internal
820 */
821
822 /*! \fn void QByteArray::push_back(const QByteArray &other)
823
824     This function is provided for STL compatibility. It is equivalent
825     to append(\a other).
826 */
827
828 /*! \fn void QByteArray::push_back(const char *str)
829
830     \overload
831
832     Same as append(\a str).
833 */
834
835 /*! \fn void QByteArray::push_back(char ch)
836
837     \overload
838
839     Same as append(\a ch).
840 */
841
842 /*! \fn void QByteArray::push_front(const QByteArray &other)
843
844     This function is provided for STL compatibility. It is equivalent
845     to prepend(\a other).
846 */
847
848 /*! \fn void QByteArray::push_front(const char *str)
849
850     \overload
851
852     Same as prepend(\a str).
853 */
854
855 /*! \fn void QByteArray::push_front(char ch)
856
857     \overload
858
859     Same as prepend(\a ch).
860 */
861
862 /*! \fn QByteArray::QByteArray(const QByteArray &other)
863
864     Constructs a copy of \a other.
865
866     This operation takes \l{constant time}, because QByteArray is
867     \l{implicitly shared}. This makes returning a QByteArray from a
868     function very fast. If a shared instance is modified, it will be
869     copied (copy-on-write), taking \l{linear time}.
870
871     \sa operator=()
872 */
873
874 /*! \fn QByteArray::~QByteArray()
875     Destroys the byte array.
876 */
877
878 /*!
879     Assigns \a other to this byte array and returns a reference to
880     this byte array.
881 */
882 QByteArray &QByteArray::operator=(const QByteArray & other)
883 {
884     other.d->ref.ref();
885     if (!d->ref.deref())
886         qFree(d);
887     d = other.d;
888     return *this;
889 }
890
891
892 /*!
893     \overload
894
895     Assigns \a str to this byte array.
896 */
897
898 QByteArray &QByteArray::operator=(const char *str)
899 {
900     Data *x;
901     if (!str) {
902         x = const_cast<Data *>(&shared_null.ba);
903     } else if (!*str) {
904         x = const_cast<Data *>(&shared_empty.ba);
905     } else {
906         int len = qstrlen(str);
907         if (d->ref != 1 || len > int(d->alloc) || (len < d->size && len < int(d->alloc) >> 1))
908             realloc(len);
909         x = d;
910         memcpy(x->data(), str, len + 1); // include null terminator
911         x->size = len;
912     }
913     x->ref.ref();
914     if (!d->ref.deref())
915          qFree(d);
916     d = x;
917     return *this;
918 }
919
920 /*! \fn void QByteArray::swap(QByteArray &other)
921     \since 4.8
922
923     Swaps byte array \a other with this byte array. This operation is very
924     fast and never fails.
925 */
926
927 /*! \fn int QByteArray::size() const
928
929     Returns the number of bytes in this byte array.
930
931     The last byte in the byte array is at position size() - 1. In addition,
932     QByteArray ensures that the byte at position size() is always '\\0', so
933     that you can use the return value of data() and constData() as arguments to
934     functions that expect '\\0'-terminated strings. If the QByteArray object
935     was created from a \l{fromRawData()}{raw data} that didn't include the
936     trailing null-termination character then QByteArray doesn't add it
937     automaticall unless the \l{deep copy} is created.
938
939     Example:
940     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 6
941
942     \sa isEmpty(), resize()
943 */
944
945 /*! \fn bool QByteArray::isEmpty() const
946
947     Returns true if the byte array has size 0; otherwise returns false.
948
949     Example:
950     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 7
951
952     \sa size()
953 */
954
955 /*! \fn int QByteArray::capacity() const
956
957     Returns the maximum number of bytes that can be stored in the
958     byte array without forcing a reallocation.
959
960     The sole purpose of this function is to provide a means of fine
961     tuning QByteArray's memory usage. In general, you will rarely
962     ever need to call this function. If you want to know how many
963     bytes are in the byte array, call size().
964
965     \sa reserve(), squeeze()
966 */
967
968 /*! \fn void QByteArray::reserve(int size)
969
970     Attempts to allocate memory for at least \a size bytes. If you
971     know in advance how large the byte array will be, you can call
972     this function, and if you call resize() often you are likely to
973     get better performance. If \a size is an underestimate, the worst
974     that will happen is that the QByteArray will be a bit slower.
975
976     The sole purpose of this function is to provide a means of fine
977     tuning QByteArray's memory usage. In general, you will rarely
978     ever need to call this function. If you want to change the size
979     of the byte array, call resize().
980
981     \sa squeeze(), capacity()
982 */
983
984 /*! \fn void QByteArray::squeeze()
985
986     Releases any memory not required to store the array's data.
987
988     The sole purpose of this function is to provide a means of fine
989     tuning QByteArray's memory usage. In general, you will rarely
990     ever need to call this function.
991
992     \sa reserve(), capacity()
993 */
994
995 /*! \fn QByteArray::operator const char *() const
996     \fn QByteArray::operator const void *() const
997
998     Returns a pointer to the data stored in the byte array. The
999     pointer can be used to access the bytes that compose the array.
1000     The data is '\\0'-terminated. The pointer remains valid as long
1001     as the array isn't reallocated or destroyed.
1002
1003     This operator is mostly useful to pass a byte array to a function
1004     that accepts a \c{const char *}.
1005
1006     You can disable this operator by defining \c
1007     QT_NO_CAST_FROM_BYTEARRAY when you compile your applications.
1008
1009     Note: A QByteArray can store any byte values including '\\0's,
1010     but most functions that take \c{char *} arguments assume that the
1011     data ends at the first '\\0' they encounter.
1012
1013     \sa constData()
1014 */
1015
1016 /*!
1017   \macro QT_NO_CAST_FROM_BYTEARRAY
1018   \relates QByteArray
1019
1020   Disables automatic conversions from QByteArray to
1021   const char * or const void *.
1022
1023   \sa QT_NO_CAST_TO_ASCII, QT_NO_CAST_FROM_ASCII
1024 */
1025
1026 /*! \fn char *QByteArray::data()
1027
1028     Returns a pointer to the data stored in the byte array. The
1029     pointer can be used to access and modify the bytes that compose
1030     the array. The data is '\\0'-terminated, i.e. the number of
1031     bytes in the returned character string is size() + 1 for the
1032     '\\0' terminator.
1033
1034     Example:
1035     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 8
1036
1037     The pointer remains valid as long as the byte array isn't
1038     reallocated or destroyed. For read-only access, constData() is
1039     faster because it never causes a \l{deep copy} to occur.
1040
1041     This function is mostly useful to pass a byte array to a function
1042     that accepts a \c{const char *}.
1043
1044     The following example makes a copy of the char* returned by
1045     data(), but it will corrupt the heap and cause a crash because it
1046     does not allocate a byte for the '\\0' at the end:
1047
1048     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 46
1049
1050     This one allocates the correct amount of space:
1051
1052     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 47
1053
1054     Note: A QByteArray can store any byte values including '\\0's,
1055     but most functions that take \c{char *} arguments assume that the
1056     data ends at the first '\\0' they encounter.
1057
1058     \sa constData(), operator[]()
1059 */
1060
1061 /*! \fn const char *QByteArray::data() const
1062
1063     \overload
1064 */
1065
1066 /*! \fn const char *QByteArray::constData() const
1067
1068     Returns a pointer to the data stored in the byte array. The pointer can be
1069     used to access the bytes that compose the array. The data is
1070     '\\0'-terminated unless the QByteArray object was created from raw data.
1071     The pointer remains valid as long as the byte array isn't reallocated or
1072     destroyed.
1073
1074     This function is mostly useful to pass a byte array to a function
1075     that accepts a \c{const char *}.
1076
1077     Note: A QByteArray can store any byte values including '\\0's,
1078     but most functions that take \c{char *} arguments assume that the
1079     data ends at the first '\\0' they encounter.
1080
1081     \sa data(), operator[](), fromRawData()
1082 */
1083
1084 /*! \fn void QByteArray::detach()
1085
1086     \internal
1087 */
1088
1089 /*! \fn bool QByteArray::isDetached() const
1090
1091     \internal
1092 */
1093
1094 /*! \fn bool QByteArray::isSharedWith(const QByteArray &other) const
1095
1096     \internal
1097 */
1098
1099 /*! \fn char QByteArray::at(int i) const
1100
1101     Returns the character at index position \a i in the byte array.
1102
1103     \a i must be a valid index position in the byte array (i.e., 0 <=
1104     \a i < size()).
1105
1106     \sa operator[]()
1107 */
1108
1109 /*! \fn QByteRef QByteArray::operator[](int i)
1110
1111     Returns the byte at index position \a i as a modifiable reference.
1112
1113     If an assignment is made beyond the end of the byte array, the
1114     array is extended with resize() before the assignment takes
1115     place.
1116
1117     Example:
1118     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 9
1119
1120     The return value is of type QByteRef, a helper class for
1121     QByteArray. When you get an object of type QByteRef, you can use
1122     it as if it were a char &. If you assign to it, the assignment
1123     will apply to the character in the QByteArray from which you got
1124     the reference.
1125
1126     \sa at()
1127 */
1128
1129 /*! \fn char QByteArray::operator[](int i) const
1130
1131     \overload
1132
1133     Same as at(\a i).
1134 */
1135
1136 /*! \fn QByteRef QByteArray::operator[](uint i)
1137
1138     \overload
1139 */
1140
1141 /*! \fn char QByteArray::operator[](uint i) const
1142
1143     \overload
1144 */
1145
1146 /*! \fn QBool QByteArray::contains(const QByteArray &ba) const
1147
1148     Returns true if the byte array contains an occurrence of the byte
1149     array \a ba; otherwise returns false.
1150
1151     \sa indexOf(), count()
1152 */
1153
1154 /*! \fn QBool QByteArray::contains(const char *str) const
1155
1156     \overload
1157
1158     Returns true if the byte array contains the string \a str;
1159     otherwise returns false.
1160 */
1161
1162 /*! \fn QBool QByteArray::contains(char ch) const
1163
1164     \overload
1165
1166     Returns true if the byte array contains the character \a ch;
1167     otherwise returns false.
1168 */
1169
1170 /*!
1171
1172     Truncates the byte array at index position \a pos.
1173
1174     If \a pos is beyond the end of the array, nothing happens.
1175
1176     Example:
1177     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 10
1178
1179     \sa chop(), resize(), left()
1180 */
1181 void QByteArray::truncate(int pos)
1182 {
1183     if (pos < d->size)
1184         resize(pos);
1185 }
1186
1187 /*!
1188
1189     Removes \a n bytes from the end of the byte array.
1190
1191     If \a n is greater than size(), the result is an empty byte
1192     array.
1193
1194     Example:
1195     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 11
1196
1197     \sa truncate(), resize(), left()
1198 */
1199
1200 void QByteArray::chop(int n)
1201 {
1202     if (n > 0)
1203         resize(d->size - n);
1204 }
1205
1206
1207 /*! \fn QByteArray &QByteArray::operator+=(const QByteArray &ba)
1208
1209     Appends the byte array \a ba onto the end of this byte array and
1210     returns a reference to this byte array.
1211
1212     Example:
1213     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 12
1214
1215     Note: QByteArray is an \l{implicitly shared} class. Consequently,
1216     if \e this is an empty QByteArray, then \e this will just share
1217     the data held in \a ba. In this case, no copying of data is done,
1218     taking \l{constant time}. If a shared instance is modified, it will
1219     be copied (copy-on-write), taking \l{linear time}.
1220
1221     If \e this is not an empty QByteArray, a deep copy of the data is
1222     performed, taking \l{linear time}.
1223
1224     This operation typically does not suffer from allocation overhead,
1225     because QByteArray preallocates extra space at the end of the data
1226     so that it may grow without reallocating for each append operation.
1227
1228     \sa append(), prepend()
1229 */
1230
1231 /*! \fn QByteArray &QByteArray::operator+=(const QString &str)
1232
1233     \overload
1234
1235     Appends the string \a str onto the end of this byte array and
1236     returns a reference to this byte array. The Unicode data is
1237     converted into 8-bit characters using QString::toAscii().
1238
1239     If the QString contains non-ASCII Unicode characters, using this
1240     operator can lead to loss of information. You can disable this
1241     operator by defining \c QT_NO_CAST_TO_ASCII when you compile your
1242     applications. You then need to call QString::toAscii() (or
1243     QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
1244     explicitly if you want to convert the data to \c{const char *}.
1245 */
1246
1247 /*! \fn QByteArray &QByteArray::operator+=(const char *str)
1248
1249     \overload
1250
1251     Appends the string \a str onto the end of this byte array and
1252     returns a reference to this byte array.
1253 */
1254
1255 /*! \fn QByteArray &QByteArray::operator+=(char ch)
1256
1257     \overload
1258
1259     Appends the character \a ch onto the end of this byte array and
1260     returns a reference to this byte array.
1261 */
1262
1263 /*! \fn int QByteArray::length() const
1264
1265     Same as size().
1266 */
1267
1268 /*! \fn bool QByteArray::isNull() const
1269
1270     Returns true if this byte array is null; otherwise returns false.
1271
1272     Example:
1273     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 13
1274
1275     Qt makes a distinction between null byte arrays and empty byte
1276     arrays for historical reasons. For most applications, what
1277     matters is whether or not a byte array contains any data,
1278     and this can be determined using isEmpty().
1279
1280     \sa isEmpty()
1281 */
1282
1283 /*! \fn QByteArray::QByteArray()
1284
1285     Constructs an empty byte array.
1286
1287     \sa isEmpty()
1288 */
1289
1290 /*! \fn QByteArray::QByteArray(const char *str)
1291
1292     Constructs a byte array initialized with the string \a str.
1293
1294     QByteArray makes a deep copy of the string data.
1295 */
1296
1297 QByteArray::QByteArray(const char *str)
1298 {
1299     if (!str) {
1300         d = const_cast<Data *>(&shared_null.ba);
1301     } else if (!*str) {
1302         d = const_cast<Data *>(&shared_empty.ba);
1303     } else {
1304         int len = qstrlen(str);
1305         d = static_cast<Data *>(qMalloc(sizeof(Data) + len + 1));
1306         Q_CHECK_PTR(d);
1307         d->ref = 1;
1308         d->size = len;
1309         d->alloc = len;
1310         d->capacityReserved = false;
1311         d->offset = 0;
1312         memcpy(d->data(), str, len+1); // include null terminator
1313     }
1314 }
1315
1316 /*!
1317     Constructs a byte array containing the first \a size bytes of
1318     array \a data.
1319
1320     If \a data is 0, a null byte array is constructed.
1321
1322     QByteArray makes a deep copy of the string data.
1323
1324     \sa fromRawData()
1325 */
1326
1327 QByteArray::QByteArray(const char *data, int size)
1328 {
1329     if (!data) {
1330         d = const_cast<Data *>(&shared_null.ba);
1331     } else if (size <= 0) {
1332         d = const_cast<Data *>(&shared_empty.ba);
1333     } else {
1334         d = static_cast<Data *>(qMalloc(sizeof(Data) + size + 1));
1335         Q_CHECK_PTR(d);
1336         d->ref = 1;
1337         d->size = size;
1338         d->alloc = size;
1339         d->capacityReserved = false;
1340         d->offset = 0;
1341         memcpy(d->data(), data, size);
1342         d->data()[size] = '\0';
1343     }
1344 }
1345
1346 /*!
1347     Constructs a byte array of size \a size with every byte set to
1348     character \a ch.
1349
1350     \sa fill()
1351 */
1352
1353 QByteArray::QByteArray(int size, char ch)
1354 {
1355     if (size <= 0) {
1356         d = const_cast<Data *>(&shared_null.ba);
1357     } else {
1358         d = static_cast<Data *>(qMalloc(sizeof(Data) + size + 1));
1359         Q_CHECK_PTR(d);
1360         d->ref = 1;
1361         d->size = size;
1362         d->alloc = size;
1363         d->capacityReserved = false;
1364         d->offset = 0;
1365         memset(d->data(), ch, size);
1366         d->data()[size] = '\0';
1367     }
1368 }
1369
1370 /*!
1371     \internal 
1372
1373     Constructs a byte array of size \a size with uninitialized contents.
1374 */
1375
1376 QByteArray::QByteArray(int size, Qt::Initialization)
1377 {
1378     d = static_cast<Data *>(qMalloc(sizeof(Data) + size + 1));
1379     Q_CHECK_PTR(d);
1380     d->ref = 1;
1381     d->size = size;
1382     d->alloc = size;
1383     d->capacityReserved = false;
1384     d->offset = 0;
1385     d->data()[size] = '\0';
1386 }
1387
1388 /*!
1389     Sets the size of the byte array to \a size bytes.
1390
1391     If \a size is greater than the current size, the byte array is
1392     extended to make it \a size bytes with the extra bytes added to
1393     the end. The new bytes are uninitialized.
1394
1395     If \a size is less than the current size, bytes are removed from
1396     the end.
1397
1398     \sa size(), truncate()
1399 */
1400
1401 void QByteArray::resize(int size)
1402 {
1403     if (size < 0)
1404         size = 0;
1405
1406     if (d->offset && d->ref == 1 && size < d->size) {
1407         d->size = size;
1408         return;
1409     }
1410
1411     if (size == 0 && !d->capacityReserved) {
1412         Data *x = const_cast<Data *>(&shared_empty.ba);
1413         if (!d->ref.deref())
1414             qFree(d);
1415         d = x;
1416     } else if (d == &shared_null.ba || d == &shared_empty.ba) {
1417         //
1418         // Optimize the idiom:
1419         //    QByteArray a;
1420         //    a.resize(sz);
1421         //    ...
1422         // which is used in place of the Qt 3 idiom:
1423         //    QByteArray a(sz);
1424         //
1425         Data *x = static_cast<Data *>(qMalloc(sizeof(Data) + size + 1));
1426         Q_CHECK_PTR(x);
1427         x->ref = 1;
1428         x->size = size;
1429         x->alloc = size;
1430         x->capacityReserved = false;
1431         x->offset = 0;
1432         x->data()[size] = '\0';
1433         d = x;
1434     } else {
1435         if (d->ref != 1 || size > int(d->alloc)
1436             || (!d->capacityReserved && size < d->size && size < int(d->alloc) >> 1))
1437             realloc(qAllocMore(size, sizeof(Data)));
1438         if (int(d->alloc) >= size) {
1439             d->size = size;
1440             d->data()[size] = '\0';
1441         }
1442     }
1443 }
1444
1445 /*!
1446     Sets every byte in the byte array to character \a ch. If \a size
1447     is different from -1 (the default), the byte array is resized to
1448     size \a size beforehand.
1449
1450     Example:
1451     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 14
1452
1453     \sa resize()
1454 */
1455
1456 QByteArray &QByteArray::fill(char ch, int size)
1457 {
1458     resize(size < 0 ? d->size : size);
1459     if (d->size)
1460         memset(d->data(), ch, d->size);
1461     return *this;
1462 }
1463
1464 void QByteArray::realloc(int alloc)
1465 {
1466     if (d->ref != 1 || d->offset) {
1467         Data *x = static_cast<Data *>(qMalloc(sizeof(Data) + alloc + 1));
1468         Q_CHECK_PTR(x);
1469         x->ref = 1;
1470         x->size = qMin(alloc, d->size);
1471         x->alloc = alloc;
1472         x->capacityReserved = d->capacityReserved;
1473         x->offset = 0;
1474         ::memcpy(x->data(), d->data(), x->size);
1475         x->data()[x->size] = '\0';
1476         if (!d->ref.deref())
1477             qFree(d);
1478         d = x;
1479     } else {
1480         Data *x = static_cast<Data *>(qRealloc(d, sizeof(Data) + alloc + 1));
1481         Q_CHECK_PTR(x);
1482         x->alloc = alloc;
1483         x->offset = 0;
1484         d = x;
1485     }
1486 }
1487
1488 void QByteArray::expand(int i)
1489 {
1490     resize(qMax(i + 1, d->size));
1491 }
1492
1493 /*!
1494    \internal
1495    Return a QByteArray that is sure to be NUL-terminated.
1496
1497    By default, all QByteArray have an extra NUL at the end,
1498    guaranteeing that assumption. However, if QByteArray::fromRawData
1499    is used, then the NUL is there only if the user put it there. We
1500    can't be sure.
1501 */
1502 QByteArray QByteArray::nulTerminated() const
1503 {
1504     // is this fromRawData?
1505     if (!d->offset)
1506         return *this;           // no, then we're sure we're zero terminated
1507
1508     QByteArray copy(*this);
1509     copy.detach();
1510     return copy;
1511 }
1512
1513 /*!
1514     Prepends the byte array \a ba to this byte array and returns a
1515     reference to this byte array.
1516
1517     Example:
1518     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 15
1519
1520     This is the same as insert(0, \a ba).
1521
1522     Note: QByteArray is an \l{implicitly shared} class. Consequently,
1523     if \e this is an empty QByteArray, then \e this will just share
1524     the data held in \a ba. In this case, no copying of data is done,
1525     taking \l{constant time}. If a shared instance is modified, it will
1526     be copied (copy-on-write), taking \l{linear time}.
1527
1528     If \e this is not an empty QByteArray, a deep copy of the data is
1529     performed, taking \l{linear time}.
1530
1531     \sa append(), insert()
1532 */
1533
1534 QByteArray &QByteArray::prepend(const QByteArray &ba)
1535 {
1536     if ((d == &shared_null.ba || d == &shared_empty.ba) && !IS_RAW_DATA(ba.d)) {
1537         *this = ba;
1538     } else if (ba.d != &shared_null.ba) {
1539         QByteArray tmp = *this;
1540         *this = ba;
1541         append(tmp);
1542     }
1543     return *this;
1544 }
1545
1546 /*!
1547     \overload
1548
1549     Prepends the string \a str to this byte array.
1550 */
1551
1552 QByteArray &QByteArray::prepend(const char *str)
1553 {
1554     return prepend(str, qstrlen(str));
1555 }
1556
1557 /*!
1558     \overload
1559     \since 4.6
1560
1561     Prepends \a len bytes of the string \a str to this byte array.
1562 */
1563
1564 QByteArray &QByteArray::prepend(const char *str, int len)
1565 {
1566     if (str) {
1567         if (d->ref != 1 || d->size + len > int(d->alloc))
1568             realloc(qAllocMore(d->size + len, sizeof(Data)));
1569         memmove(d->data()+len, d->data(), d->size);
1570         memcpy(d->data(), str, len);
1571         d->size += len;
1572         d->data()[d->size] = '\0';
1573     }
1574     return *this;
1575 }
1576
1577 /*!
1578     \overload
1579
1580     Prepends the character \a ch to this byte array.
1581 */
1582
1583 QByteArray &QByteArray::prepend(char ch)
1584 {
1585     if (d->ref != 1 || d->size + 1 > int(d->alloc))
1586         realloc(qAllocMore(d->size + 1, sizeof(Data)));
1587     memmove(d->data()+1, d->data(), d->size);
1588     d->data()[0] = ch;
1589     ++d->size;
1590     d->data()[d->size] = '\0';
1591     return *this;
1592 }
1593
1594 /*!
1595     Appends the byte array \a ba onto the end of this byte array.
1596
1597     Example:
1598     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 16
1599
1600     This is the same as insert(size(), \a ba).
1601
1602     Note: QByteArray is an \l{implicitly shared} class. Consequently,
1603     if \e this is an empty QByteArray, then \e this will just share
1604     the data held in \a ba. In this case, no copying of data is done,
1605     taking \l{constant time}. If a shared instance is modified, it will
1606     be copied (copy-on-write), taking \l{linear time}.
1607
1608     If \e this is not an empty QByteArray, a deep copy of the data is
1609     performed, taking \l{linear time}.
1610
1611     This operation typically does not suffer from allocation overhead,
1612     because QByteArray preallocates extra space at the end of the data
1613     so that it may grow without reallocating for each append operation.
1614
1615     \sa operator+=(), prepend(), insert()
1616 */
1617
1618 QByteArray &QByteArray::append(const QByteArray &ba)
1619 {
1620     if ((d == &shared_null.ba || d == &shared_empty.ba) && !IS_RAW_DATA(ba.d)) {
1621         *this = ba;
1622     } else if (ba.d != &shared_null.ba) {
1623         if (d->ref != 1 || d->size + ba.d->size > int(d->alloc))
1624             realloc(qAllocMore(d->size + ba.d->size, sizeof(Data)));
1625         memcpy(d->data() + d->size, ba.d->data(), ba.d->size);
1626         d->size += ba.d->size;
1627         d->data()[d->size] = '\0';
1628     }
1629     return *this;
1630 }
1631
1632 /*! \fn QByteArray &QByteArray::append(const QString &str)
1633
1634     \overload
1635
1636     Appends the string \a str to this byte array. The Unicode data is
1637     converted into 8-bit characters using QString::toAscii().
1638
1639     If the QString contains non-ASCII Unicode characters, using this
1640     function can lead to loss of information. You can disable this
1641     function by defining \c QT_NO_CAST_TO_ASCII when you compile your
1642     applications. You then need to call QString::toAscii() (or
1643     QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
1644     explicitly if you want to convert the data to \c{const char *}.
1645 */
1646
1647 /*!
1648     \overload
1649
1650     Appends the string \a str to this byte array.
1651 */
1652
1653 QByteArray& QByteArray::append(const char *str)
1654 {
1655     if (str) {
1656         int len = qstrlen(str);
1657         if (d->ref != 1 || d->size + len > int(d->alloc))
1658             realloc(qAllocMore(d->size + len, sizeof(Data)));
1659         memcpy(d->data() + d->size, str, len + 1); // include null terminator
1660         d->size += len;
1661     }
1662     return *this;
1663 }
1664
1665 /*!
1666     \overload append()
1667
1668     Appends the first \a len characters of the string \a str to this byte
1669     array and returns a reference to this byte array.
1670
1671     If \a len is negative, the length of the string will be determined
1672     automatically using qstrlen(). If \a len is zero or \a str is
1673     null, nothing is appended to the byte array. Ensure that \a len is
1674     \e not longer than \a str.
1675 */
1676
1677 QByteArray &QByteArray::append(const char *str, int len)
1678 {
1679     if (len < 0)
1680         len = qstrlen(str);
1681     if (str && len) {
1682         if (d->ref != 1 || d->size + len > int(d->alloc))
1683             realloc(qAllocMore(d->size + len, sizeof(Data)));
1684         memcpy(d->data() + d->size, str, len); // include null terminator
1685         d->size += len;
1686         d->data()[d->size] = '\0';
1687     }
1688     return *this;
1689 }
1690
1691 /*!
1692     \overload
1693
1694     Appends the character \a ch to this byte array.
1695 */
1696
1697 QByteArray& QByteArray::append(char ch)
1698 {
1699     if (d->ref != 1 || d->size + 1 > int(d->alloc))
1700         realloc(qAllocMore(d->size + 1, sizeof(Data)));
1701     d->data()[d->size++] = ch;
1702     d->data()[d->size] = '\0';
1703     return *this;
1704 }
1705
1706 /*!
1707   \internal
1708   Inserts \a len bytes from the array \a arr at position \a pos and returns a
1709   reference the modified byte array.
1710 */
1711 static inline QByteArray &qbytearray_insert(QByteArray *ba,
1712                                             int pos, const char *arr, int len)
1713 {
1714     Q_ASSERT(pos >= 0);
1715
1716     if (pos < 0 || len <= 0 || arr == 0)
1717         return *ba;
1718
1719     int oldsize = ba->size();
1720     ba->resize(qMax(pos, oldsize) + len);
1721     char *dst = ba->data();
1722     if (pos > oldsize)
1723         ::memset(dst + oldsize, 0x20, pos - oldsize);
1724     else
1725         ::memmove(dst + pos + len, dst + pos, oldsize - pos);
1726     memcpy(dst + pos, arr, len);
1727     return *ba;
1728 }
1729
1730 /*!
1731     Inserts the byte array \a ba at index position \a i and returns a
1732     reference to this byte array.
1733
1734     Example:
1735     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 17
1736
1737     \sa append(), prepend(), replace(), remove()
1738 */
1739
1740 QByteArray &QByteArray::insert(int i, const QByteArray &ba)
1741 {
1742     QByteArray copy(ba);
1743     return qbytearray_insert(this, i, copy.d->data(), copy.d->size);
1744 }
1745
1746 /*!
1747     \fn QByteArray &QByteArray::insert(int i, const QString &str)
1748
1749     \overload
1750
1751     Inserts the string \a str at index position \a i in the byte
1752     array. The Unicode data is converted into 8-bit characters using
1753     QString::toAscii().
1754
1755     If \a i is greater than size(), the array is first extended using
1756     resize().
1757
1758     If the QString contains non-ASCII Unicode characters, using this
1759     function can lead to loss of information. You can disable this
1760     function by defining \c QT_NO_CAST_TO_ASCII when you compile your
1761     applications. You then need to call QString::toAscii() (or
1762     QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
1763     explicitly if you want to convert the data to \c{const char *}.
1764 */
1765
1766 /*!
1767     \overload
1768
1769     Inserts the string \a str at position \a i in the byte array.
1770
1771     If \a i is greater than size(), the array is first extended using
1772     resize().
1773 */
1774
1775 QByteArray &QByteArray::insert(int i, const char *str)
1776 {
1777     return qbytearray_insert(this, i, str, qstrlen(str));
1778 }
1779
1780 /*!
1781     \overload
1782     \since 4.6
1783
1784     Inserts \a len bytes of the string \a str at position
1785     \a i in the byte array.
1786
1787     If \a i is greater than size(), the array is first extended using
1788     resize().
1789 */
1790
1791 QByteArray &QByteArray::insert(int i, const char *str, int len)
1792 {
1793     return qbytearray_insert(this, i, str, len);
1794 }
1795
1796 /*!
1797     \overload
1798
1799     Inserts character \a ch at index position \a i in the byte array.
1800     If \a i is greater than size(), the array is first extended using
1801     resize().
1802 */
1803
1804 QByteArray &QByteArray::insert(int i, char ch)
1805 {
1806     return qbytearray_insert(this, i, &ch, 1);
1807 }
1808
1809 /*!
1810     Removes \a len bytes from the array, starting at index position \a
1811     pos, and returns a reference to the array.
1812
1813     If \a pos is out of range, nothing happens. If \a pos is valid,
1814     but \a pos + \a len is larger than the size of the array, the
1815     array is truncated at position \a pos.
1816
1817     Example:
1818     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 18
1819
1820     \sa insert(), replace()
1821 */
1822
1823 QByteArray &QByteArray::remove(int pos, int len)
1824 {
1825     if (len <= 0  || pos >= d->size || pos < 0)
1826         return *this;
1827     detach();
1828     if (pos + len >= d->size) {
1829         resize(pos);
1830     } else {
1831         memmove(d->data() + pos, d->data() + pos + len, d->size - pos - len);
1832         resize(d->size - len);
1833     }
1834     return *this;
1835 }
1836
1837 /*!
1838     Replaces \a len bytes from index position \a pos with the byte
1839     array \a after, and returns a reference to this byte array.
1840
1841     Example:
1842     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 19
1843
1844     \sa insert(), remove()
1845 */
1846
1847 QByteArray &QByteArray::replace(int pos, int len, const QByteArray &after)
1848 {
1849     if (len == after.d->size && (pos + len <= d->size)) {
1850         detach();
1851         memmove(d->data() + pos, after.d->data(), len*sizeof(char));
1852         return *this;
1853     } else {
1854         QByteArray copy(after);
1855         // ### optimize me
1856         remove(pos, len);
1857         return insert(pos, copy);
1858     }
1859 }
1860
1861 /*! \fn QByteArray &QByteArray::replace(int pos, int len, const char *after)
1862
1863     \overload
1864
1865     Replaces \a len bytes from index position \a pos with the zero terminated
1866     string \a after.
1867
1868     Notice: this can change the length of the byte array.
1869 */
1870 QByteArray &QByteArray::replace(int pos, int len, const char *after)
1871 {
1872     return replace(pos,len,after,qstrlen(after));
1873 }
1874
1875 /*! \fn QByteArray &QByteArray::replace(int pos, int len, const char *after, int alen)
1876
1877     \overload
1878
1879     Replaces \a len bytes from index position \a pos with \a alen bytes
1880     from the string \a after. \a after is allowed to have '\0' characters.
1881
1882     \since 4.7
1883 */
1884 QByteArray &QByteArray::replace(int pos, int len, const char *after, int alen)
1885 {
1886     if (len == alen && (pos + len <= d->size)) {
1887         detach();
1888         memcpy(d->data() + pos, after, len*sizeof(char));
1889         return *this;
1890     } else {
1891         remove(pos, len);
1892         return qbytearray_insert(this, pos, after, alen);
1893     }
1894 }
1895
1896 // ### optimize all other replace method, by offering
1897 // QByteArray::replace(const char *before, int blen, const char *after, int alen)
1898
1899 /*!
1900     \overload
1901
1902     Replaces every occurrence of the byte array \a before with the
1903     byte array \a after.
1904
1905     Example:
1906     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 20
1907 */
1908
1909 QByteArray &QByteArray::replace(const QByteArray &before, const QByteArray &after)
1910 {
1911     if (isNull() || before.d == after.d)
1912         return *this;
1913
1914     QByteArray aft = after;
1915     if (after.d == d)
1916         aft.detach();
1917     
1918     return replace(before.constData(), before.size(), aft.constData(), aft.size());
1919 }
1920
1921 /*!
1922     \fn QByteArray &QByteArray::replace(const char *before, const QByteArray &after)
1923     \overload
1924
1925     Replaces every occurrence of the string \a before with the
1926     byte array \a after.
1927 */
1928
1929 QByteArray &QByteArray::replace(const char *c, const QByteArray &after)
1930 {
1931     QByteArray aft = after;
1932     if (after.d == d)
1933         aft.detach();
1934     
1935     return replace(c, qstrlen(c), aft.constData(), aft.size());
1936 }
1937
1938 /*!
1939     \fn QByteArray &QByteArray::replace(const char *before, int bsize, const char *after, int asize)
1940     \overload
1941
1942     Replaces every occurrence of the string \a before with the string \a after.
1943     Since the sizes of the strings are given by \a bsize and \a asize, they
1944     may contain zero characters and do not need to be zero-terminated.
1945 */
1946
1947 QByteArray &QByteArray::replace(const char *before, int bsize, const char *after, int asize)
1948 {
1949     if (isNull() || (before == after && bsize == asize))
1950         return *this;
1951
1952     // protect against before or after being part of this
1953     const char *a = after;
1954     const char *b = before;
1955     if (after >= d->data() && after < d->data() + d->size) {
1956         char *copy = (char *)malloc(asize);
1957         Q_CHECK_PTR(copy);
1958         memcpy(copy, after, asize);
1959         a = copy;
1960     }
1961     if (before >= d->data() && before < d->data() + d->size) {
1962         char *copy = (char *)malloc(bsize);
1963         Q_CHECK_PTR(copy);
1964         memcpy(copy, before, bsize);
1965         b = copy;
1966     }
1967     
1968     QByteArrayMatcher matcher(before, bsize);
1969     int index = 0;
1970     int len = d->size;
1971     char *d = data();
1972
1973     if (bsize == asize) {
1974         if (bsize) {
1975             while ((index = matcher.indexIn(*this, index)) != -1) {
1976                 memcpy(d + index, after, asize);
1977                 index += bsize;
1978             }
1979         }
1980     } else if (asize < bsize) {
1981         uint to = 0;
1982         uint movestart = 0;
1983         uint num = 0;
1984         while ((index = matcher.indexIn(*this, index)) != -1) {
1985             if (num) {
1986                 int msize = index - movestart;
1987                 if (msize > 0) {
1988                     memmove(d + to, d + movestart, msize);
1989                     to += msize;
1990                 }
1991             } else {
1992                 to = index;
1993             }
1994             if (asize) {
1995                 memcpy(d + to, after, asize);
1996                 to += asize;
1997             }
1998             index += bsize;
1999             movestart = index;
2000             num++;
2001         }
2002         if (num) {
2003             int msize = len - movestart;
2004             if (msize > 0)
2005                 memmove(d + to, d + movestart, msize);
2006             resize(len - num*(bsize-asize));
2007         }
2008     } else {
2009         // the most complex case. We don't want to lose performance by doing repeated
2010         // copies and reallocs of the string.
2011         while (index != -1) {
2012             uint indices[4096];
2013             uint pos = 0;
2014             while(pos < 4095) {
2015                 index = matcher.indexIn(*this, index);
2016                 if (index == -1)
2017                     break;
2018                 indices[pos++] = index;
2019                 index += bsize;
2020                 // avoid infinite loop
2021                 if (!bsize)
2022                     index++;
2023             }
2024             if (!pos)
2025                 break;
2026
2027             // we have a table of replacement positions, use them for fast replacing
2028             int adjust = pos*(asize-bsize);
2029             // index has to be adjusted in case we get back into the loop above.
2030             if (index != -1)
2031                 index += adjust;
2032             int newlen = len + adjust;
2033             int moveend = len;
2034             if (newlen > len) {
2035                 resize(newlen);
2036                 len = newlen;
2037             }
2038             d = this->d->data();
2039
2040             while(pos) {
2041                 pos--;
2042                 int movestart = indices[pos] + bsize;
2043                 int insertstart = indices[pos] + pos*(asize-bsize);
2044                 int moveto = insertstart + asize;
2045                 memmove(d + moveto, d + movestart, (moveend - movestart));
2046                 if (asize)
2047                     memcpy(d + insertstart, after, asize);
2048                 moveend = movestart - bsize;
2049             }
2050         }
2051     }
2052
2053     if (a != after)
2054         ::free((char *)a);
2055     if (b != before)
2056         ::free((char *)b);
2057     
2058     
2059     return *this;
2060 }
2061
2062
2063 /*!
2064     \fn QByteArray &QByteArray::replace(const QByteArray &before, const char *after)
2065     \overload
2066
2067     Replaces every occurrence of the byte array \a before with the
2068     string \a after.
2069 */
2070
2071 /*! \fn QByteArray &QByteArray::replace(const QString &before, const QByteArray &after)
2072
2073     \overload
2074
2075     Replaces every occurrence of the string \a before with the byte
2076     array \a after. The Unicode data is converted into 8-bit
2077     characters using QString::toAscii().
2078
2079     If the QString contains non-ASCII Unicode characters, using this
2080     function can lead to loss of information. You can disable this
2081     function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2082     applications. You then need to call QString::toAscii() (or
2083     QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2084     explicitly if you want to convert the data to \c{const char *}.
2085 */
2086
2087 /*! \fn QByteArray &QByteArray::replace(const QString &before, const char *after)
2088     \overload
2089
2090     Replaces every occurrence of the string \a before with the string
2091     \a after.
2092 */
2093
2094 /*! \fn QByteArray &QByteArray::replace(const char *before, const char *after)
2095
2096     \overload
2097
2098     Replaces every occurrence of the string \a before with the string
2099     \a after.
2100 */
2101
2102 /*!
2103     \overload
2104
2105     Replaces every occurrence of the character \a before with the
2106     byte array \a after.
2107 */
2108
2109 QByteArray &QByteArray::replace(char before, const QByteArray &after)
2110 {
2111     char b[2] = { before, '\0' };
2112     QByteArray cb = fromRawData(b, 1);
2113     return replace(cb, after);
2114 }
2115
2116 /*! \fn QByteArray &QByteArray::replace(char before, const QString &after)
2117
2118     \overload
2119
2120     Replaces every occurrence of the character \a before with the
2121     string \a after. The Unicode data is converted into 8-bit
2122     characters using QString::toAscii().
2123
2124     If the QString contains non-ASCII Unicode characters, using this
2125     function can lead to loss of information. You can disable this
2126     function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2127     applications. You then need to call QString::toAscii() (or
2128     QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2129     explicitly if you want to convert the data to \c{const char *}.
2130 */
2131
2132 /*! \fn QByteArray &QByteArray::replace(char before, const char *after)
2133
2134     \overload
2135
2136     Replaces every occurrence of the character \a before with the
2137     string \a after.
2138 */
2139
2140 /*!
2141     \overload
2142
2143     Replaces every occurrence of the character \a before with the
2144     character \a after.
2145 */
2146
2147 QByteArray &QByteArray::replace(char before, char after)
2148 {
2149     if (d->size) {
2150         char *i = data();
2151         char *e = i + d->size;
2152         for (; i != e; ++i)
2153             if (*i == before)
2154                 * i = after;
2155     }
2156     return *this;
2157 }
2158
2159 /*!
2160     Splits the byte array into subarrays wherever \a sep occurs, and
2161     returns the list of those arrays. If \a sep does not match
2162     anywhere in the byte array, split() returns a single-element list
2163     containing this byte array.
2164 */
2165
2166 QList<QByteArray> QByteArray::split(char sep) const
2167 {
2168     QList<QByteArray> list;
2169     int start = 0;
2170     int end;
2171     while ((end = indexOf(sep, start)) != -1) {
2172         list.append(mid(start, end - start));
2173         start = end + 1;
2174     }
2175     list.append(mid(start));
2176     return list;
2177 }
2178
2179 /*!
2180     \since 4.5
2181
2182     Returns a copy of this byte array repeated the specified number of \a times.
2183
2184     If \a times is less than 1, an empty byte array is returned.
2185
2186     Example:
2187
2188     \code
2189         QByteArray ba("ab");
2190         ba.repeated(4);             // returns "abababab"
2191     \endcode
2192 */
2193 QByteArray QByteArray::repeated(int times) const
2194 {
2195     if (d->size == 0)
2196         return *this;
2197
2198     if (times <= 1) {
2199         if (times == 1)
2200             return *this;
2201         return QByteArray();
2202     }
2203
2204     const int resultSize = times * d->size;
2205
2206     QByteArray result;
2207     result.reserve(resultSize);
2208     if (int(result.d->alloc) != resultSize)
2209         return QByteArray(); // not enough memory
2210
2211     memcpy(result.d->data(), d->data(), d->size);
2212
2213     int sizeSoFar = d->size;
2214     char *end = result.d->data() + sizeSoFar;
2215
2216     const int halfResultSize = resultSize >> 1;
2217     while (sizeSoFar <= halfResultSize) {
2218         memcpy(end, result.d->data(), sizeSoFar);
2219         end += sizeSoFar;
2220         sizeSoFar <<= 1;
2221     }
2222     memcpy(end, result.d->data(), resultSize - sizeSoFar);
2223     result.d->data()[resultSize] = '\0';
2224     result.d->size = resultSize;
2225     return result;
2226 }
2227
2228 #define REHASH(a) \
2229     if (ol_minus_1 < sizeof(uint) * CHAR_BIT) \
2230         hashHaystack -= (a) << ol_minus_1; \
2231     hashHaystack <<= 1
2232
2233 /*!
2234     Returns the index position of the first occurrence of the byte
2235     array \a ba in this byte array, searching forward from index
2236     position \a from. Returns -1 if \a ba could not be found.
2237
2238     Example:
2239     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 21
2240
2241     \sa lastIndexOf(), contains(), count()
2242 */
2243
2244 int QByteArray::indexOf(const QByteArray &ba, int from) const
2245 {
2246     const int ol = ba.d->size;
2247     if (ol == 0)
2248         return from;
2249     if (ol == 1)
2250         return indexOf(*ba.d->data(), from);
2251
2252     const int l = d->size;
2253     if (from > d->size || ol + from > l)
2254         return -1;
2255
2256     return qFindByteArray(d->data(), d->size, from, ba.d->data(), ol);
2257 }
2258
2259 /*! \fn int QByteArray::indexOf(const QString &str, int from) const
2260
2261     \overload
2262
2263     Returns the index position of the first occurrence of the string
2264     \a str in the byte array, searching forward from index position
2265     \a from. Returns -1 if \a str could not be found.
2266
2267     The Unicode data is converted into 8-bit characters using
2268     QString::toAscii().
2269
2270     If the QString contains non-ASCII Unicode characters, using this
2271     function can lead to loss of information. You can disable this
2272     function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2273     applications. You then need to call QString::toAscii() (or
2274     QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2275     explicitly if you want to convert the data to \c{const char *}.
2276 */
2277
2278 /*! \fn int QByteArray::indexOf(const char *str, int from) const
2279
2280     \overload
2281
2282     Returns the index position of the first occurrence of the string
2283     \a str in the byte array, searching forward from index position \a
2284     from. Returns -1 if \a str could not be found.
2285 */
2286 int QByteArray::indexOf(const char *c, int from) const
2287 {
2288     const int ol = qstrlen(c);
2289     if (ol == 1)
2290         return indexOf(*c, from);
2291     
2292     const int l = d->size;
2293     if (from > d->size || ol + from > l)
2294         return -1;
2295     if (ol == 0)
2296         return from;
2297
2298     return qFindByteArray(d->data(), d->size, from, c, ol);
2299 }
2300
2301 /*!
2302     \overload
2303
2304     Returns the index position of the first occurrence of the
2305     character \a ch in the byte array, searching forward from index
2306     position \a from. Returns -1 if \a ch could not be found.
2307
2308     Example:
2309     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 22
2310
2311     \sa lastIndexOf(), contains()
2312 */
2313
2314 int QByteArray::indexOf(char ch, int from) const
2315 {
2316     if (from < 0)
2317         from = qMax(from + d->size, 0);
2318     if (from < d->size) {
2319         const char *n = d->data() + from - 1;
2320         const char *e = d->data() + d->size;
2321         while (++n != e)
2322         if (*n == ch)
2323             return  n - d->data();
2324     }
2325     return -1;
2326 }
2327
2328
2329 static int lastIndexOfHelper(const char *haystack, int l, const char *needle, int ol, int from)
2330 {
2331     int delta = l - ol;
2332     if (from < 0)
2333         from = delta;
2334     if (from < 0 || from > l)
2335         return -1;
2336     if (from > delta)
2337         from = delta;
2338
2339     const char *end = haystack;
2340     haystack += from;
2341     const uint ol_minus_1 = ol - 1;
2342     const char *n = needle + ol_minus_1;
2343     const char *h = haystack + ol_minus_1;
2344     uint hashNeedle = 0, hashHaystack = 0;
2345     int idx;
2346     for (idx = 0; idx < ol; ++idx) {
2347         hashNeedle = ((hashNeedle<<1) + *(n-idx));
2348         hashHaystack = ((hashHaystack<<1) + *(h-idx));
2349     }
2350     hashHaystack -= *haystack;
2351     while (haystack >= end) {
2352         hashHaystack += *haystack;
2353         if (hashHaystack == hashNeedle && memcmp(needle, haystack, ol) == 0)
2354             return haystack - end;
2355         --haystack;
2356         REHASH(*(haystack + ol));
2357     }
2358     return -1;
2359
2360 }
2361
2362 /*!
2363     \fn int QByteArray::lastIndexOf(const QByteArray &ba, int from) const
2364
2365     Returns the index position of the last occurrence of the byte
2366     array \a ba in this byte array, searching backward from index
2367     position \a from. If \a from is -1 (the default), the search
2368     starts at the last byte. Returns -1 if \a ba could not be found.
2369
2370     Example:
2371     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 23
2372
2373     \sa indexOf(), contains(), count()
2374 */
2375
2376 int QByteArray::lastIndexOf(const QByteArray &ba, int from) const
2377 {
2378     const int ol = ba.d->size;
2379     if (ol == 1)
2380         return lastIndexOf(*ba.d->data(), from);
2381
2382     return lastIndexOfHelper(d->data(), d->size, ba.d->data(), ol, from);
2383 }
2384
2385 /*! \fn int QByteArray::lastIndexOf(const QString &str, int from) const
2386
2387     \overload
2388
2389     Returns the index position of the last occurrence of the string \a
2390     str in the byte array, searching backward from index position \a
2391     from. If \a from is -1 (the default), the search starts at the
2392     last (size() - 1) byte. Returns -1 if \a str could not be found.
2393
2394     The Unicode data is converted into 8-bit characters using
2395     QString::toAscii().
2396
2397     If the QString contains non-ASCII Unicode characters, using this
2398     function can lead to loss of information. You can disable this
2399     function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2400     applications. You then need to call QString::toAscii() (or
2401     QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2402     explicitly if you want to convert the data to \c{const char *}.
2403 */
2404
2405 /*! \fn int QByteArray::lastIndexOf(const char *str, int from) const
2406     \overload
2407
2408     Returns the index position of the last occurrence of the string \a
2409     str in the byte array, searching backward from index position \a
2410     from. If \a from is -1 (the default), the search starts at the
2411     last (size() - 1) byte. Returns -1 if \a str could not be found.
2412 */
2413 int QByteArray::lastIndexOf(const char *str, int from) const
2414 {
2415     const int ol = qstrlen(str);
2416     if (ol == 1)
2417         return lastIndexOf(*str, from);
2418
2419     return lastIndexOfHelper(d->data(), d->size, str, ol, from);
2420 }
2421
2422 /*!
2423     \overload
2424
2425     Returns the index position of the last occurrence of character \a
2426     ch in the byte array, searching backward from index position \a
2427     from. If \a from is -1 (the default), the search starts at the
2428     last (size() - 1) byte. Returns -1 if \a ch could not be found.
2429
2430     Example:
2431     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 24
2432
2433     \sa indexOf(), contains()
2434 */
2435
2436 int QByteArray::lastIndexOf(char ch, int from) const
2437 {
2438     if (from < 0)
2439         from += d->size;
2440     else if (from > d->size)
2441         from = d->size-1;
2442     if (from >= 0) {
2443         const char *b = d->data();
2444         const char *n = d->data() + from + 1;
2445         while (n-- != b)
2446             if (*n == ch)
2447                 return  n - b;
2448     }
2449     return -1;
2450 }
2451
2452 /*!
2453     Returns the number of (potentially overlapping) occurrences of
2454     byte array \a ba in this byte array.
2455
2456     \sa contains(), indexOf()
2457 */
2458
2459 int QByteArray::count(const QByteArray &ba) const
2460 {
2461     int num = 0;
2462     int i = -1;
2463     if (d->size > 500 && ba.d->size > 5) {
2464         QByteArrayMatcher matcher(ba);
2465         while ((i = matcher.indexIn(*this, i + 1)) != -1)
2466             ++num;
2467     } else {
2468         while ((i = indexOf(ba, i + 1)) != -1)
2469             ++num;
2470     }
2471     return num;
2472 }
2473
2474 /*!
2475     \overload
2476
2477     Returns the number of (potentially overlapping) occurrences of
2478     string \a str in the byte array.
2479 */
2480
2481 int QByteArray::count(const char *str) const
2482 {
2483     return count(fromRawData(str, qstrlen(str)));
2484 }
2485
2486 /*!
2487     \overload
2488
2489     Returns the number of occurrences of character \a ch in the byte
2490     array.
2491
2492     \sa contains(), indexOf()
2493 */
2494
2495 int QByteArray::count(char ch) const
2496 {
2497     int num = 0;
2498     const char *i = d->data() + d->size;
2499     const char *b = d->data();
2500     while (i != b)
2501         if (*--i == ch)
2502             ++num;
2503     return num;
2504 }
2505
2506 /*! \fn int QByteArray::count() const
2507
2508     \overload
2509
2510     Same as size().
2511 */
2512
2513 /*!
2514     Returns true if this byte array starts with byte array \a ba;
2515     otherwise returns false.
2516
2517     Example:
2518     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 25
2519
2520     \sa endsWith(), left()
2521 */
2522 bool QByteArray::startsWith(const QByteArray &ba) const
2523 {
2524     if (d == ba.d || ba.d->size == 0)
2525         return true;
2526     if (d->size < ba.d->size)
2527         return false;
2528     return memcmp(d->data(), ba.d->data(), ba.d->size) == 0;
2529 }
2530
2531 /*! \overload
2532
2533     Returns true if this byte array starts with string \a str;
2534     otherwise returns false.
2535 */
2536 bool QByteArray::startsWith(const char *str) const
2537 {
2538     if (!str || !*str)
2539         return true;
2540     int len = qstrlen(str);
2541     if (d->size < len)
2542         return false;
2543     return qstrncmp(d->data(), str, len) == 0;
2544 }
2545
2546 /*! \overload
2547
2548     Returns true if this byte array starts with character \a ch;
2549     otherwise returns false.
2550 */
2551 bool QByteArray::startsWith(char ch) const
2552 {
2553     if (d->size == 0)
2554         return false;
2555     return d->data()[0] == ch;
2556 }
2557
2558 /*!
2559     Returns true if this byte array ends with byte array \a ba;
2560     otherwise returns false.
2561
2562     Example:
2563     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 26
2564
2565     \sa startsWith(), right()
2566 */
2567 bool QByteArray::endsWith(const QByteArray &ba) const
2568 {
2569     if (d == ba.d || ba.d->size == 0)
2570         return true;
2571     if (d->size < ba.d->size)
2572         return false;
2573     return memcmp(d->data() + d->size - ba.d->size, ba.d->data(), ba.d->size) == 0;
2574 }
2575
2576 /*! \overload
2577
2578     Returns true if this byte array ends with string \a str; otherwise
2579     returns false.
2580 */
2581 bool QByteArray::endsWith(const char *str) const
2582 {
2583     if (!str || !*str)
2584         return true;
2585     int len = qstrlen(str);
2586     if (d->size < len)
2587         return false;
2588     return qstrncmp(d->data() + d->size - len, str, len) == 0;
2589 }
2590
2591 /*! \overload
2592
2593     Returns true if this byte array ends with character \a ch;
2594     otherwise returns false.
2595 */
2596 bool QByteArray::endsWith(char ch) const
2597 {
2598     if (d->size == 0)
2599         return false;
2600     return d->data()[d->size - 1] == ch;
2601 }
2602
2603 /*!
2604     Returns a byte array that contains the leftmost \a len bytes of
2605     this byte array.
2606
2607     The entire byte array is returned if \a len is greater than
2608     size().
2609
2610     Example:
2611     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 27
2612
2613     \sa right(), mid(), startsWith(), truncate()
2614 */
2615
2616 QByteArray QByteArray::left(int len)  const
2617 {
2618     if (len >= d->size)
2619         return *this;
2620     if (len < 0)
2621         len = 0;
2622     return QByteArray(d->data(), len);
2623 }
2624
2625 /*!
2626     Returns a byte array that contains the rightmost \a len bytes of
2627     this byte array.
2628
2629     The entire byte array is returned if \a len is greater than
2630     size().
2631
2632     Example:
2633     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 28
2634
2635     \sa endsWith(), left(), mid()
2636 */
2637
2638 QByteArray QByteArray::right(int len) const
2639 {
2640     if (len >= d->size)
2641         return *this;
2642     if (len < 0)
2643         len = 0;
2644     return QByteArray(d->data() + d->size - len, len);
2645 }
2646
2647 /*!
2648     Returns a byte array containing \a len bytes from this byte array,
2649     starting at position \a pos.
2650
2651     If \a len is -1 (the default), or \a pos + \a len >= size(),
2652     returns a byte array containing all bytes starting at position \a
2653     pos until the end of the byte array.
2654
2655     Example:
2656     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 29
2657
2658     \sa left(), right()
2659 */
2660
2661 QByteArray QByteArray::mid(int pos, int len) const
2662 {
2663     if (d == &shared_null.ba || d == &shared_empty.ba || pos >= d->size)
2664         return QByteArray();
2665     if (len < 0)
2666         len = d->size - pos;
2667     if (pos < 0) {
2668         len += pos;
2669         pos = 0;
2670     }
2671     if (len + pos > d->size)
2672         len = d->size - pos;
2673     if (pos == 0 && len == d->size)
2674         return *this;
2675     return QByteArray(d->data() + pos, len);
2676 }
2677
2678 /*!
2679     Returns a lowercase copy of the byte array. The bytearray is
2680     interpreted as a Latin-1 encoded string.
2681
2682     Example:
2683     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 30
2684
2685     \sa toUpper(), {8-bit Character Comparisons}
2686 */
2687 QByteArray QByteArray::toLower() const
2688 {
2689     QByteArray s(*this);
2690     register uchar *p = reinterpret_cast<uchar *>(s.data());
2691     if (p) {
2692         while (*p) {
2693             *p = QChar::toLower((ushort)*p);
2694             p++;
2695         }
2696     }
2697     return s;
2698 }
2699
2700 /*!
2701     Returns an uppercase copy of the byte array. The bytearray is
2702     interpreted as a Latin-1 encoded string.
2703
2704     Example:
2705     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 31
2706
2707     \sa toLower(), {8-bit Character Comparisons}
2708 */
2709
2710 QByteArray QByteArray::toUpper() const
2711 {
2712     QByteArray s(*this);
2713     register uchar *p = reinterpret_cast<uchar *>(s.data());
2714     if (p) {
2715         while (*p) {
2716             *p = QChar::toUpper((ushort)*p);
2717             p++;
2718         }
2719     }
2720     return s;
2721 }
2722
2723 /*! \fn void QByteArray::clear()
2724
2725     Clears the contents of the byte array and makes it empty.
2726
2727     \sa resize(), isEmpty()
2728 */
2729
2730 void QByteArray::clear()
2731 {
2732     if (!d->ref.deref())
2733         qFree(d);
2734     d = const_cast<Data *>(&shared_null.ba);
2735     d->ref.ref();
2736 }
2737
2738 #if !defined(QT_NO_DATASTREAM) || (defined(QT_BOOTSTRAPPED) && !defined(QT_BUILD_QMAKE))
2739
2740 /*! \relates QByteArray
2741
2742     Writes byte array \a ba to the stream \a out and returns a reference
2743     to the stream.
2744
2745     \sa {Serializing Qt Data Types}
2746 */
2747
2748 QDataStream &operator<<(QDataStream &out, const QByteArray &ba)
2749 {
2750     if (ba.isNull() && out.version() >= 6) {
2751         out << (quint32)0xffffffff;
2752         return out;
2753     }
2754     return out.writeBytes(ba, ba.size());
2755 }
2756
2757 /*! \relates QByteArray
2758
2759     Reads a byte array into \a ba from the stream \a in and returns a
2760     reference to the stream.
2761
2762     \sa {Serializing Qt Data Types}
2763 */
2764
2765 QDataStream &operator>>(QDataStream &in, QByteArray &ba)
2766 {
2767     ba.clear();
2768     quint32 len;
2769     in >> len;
2770     if (len == 0xffffffff)
2771         return in;
2772
2773     const quint32 Step = 1024 * 1024;
2774     quint32 allocated = 0;
2775
2776     do {
2777         int blockSize = qMin(Step, len - allocated);
2778         ba.resize(allocated + blockSize);
2779         if (in.readRawData(ba.data() + allocated, blockSize) != blockSize) {
2780             ba.clear();
2781             in.setStatus(QDataStream::ReadPastEnd);
2782             return in;
2783         }
2784         allocated += blockSize;
2785     } while (allocated < len);
2786
2787     return in;
2788 }
2789 #endif // QT_NO_DATASTREAM
2790
2791 /*! \fn bool QByteArray::operator==(const QString &str) const
2792
2793     Returns true if this byte array is equal to string \a str;
2794     otherwise returns false.
2795
2796     The Unicode data is converted into 8-bit characters using
2797     QString::toAscii().
2798
2799     The comparison is case sensitive.
2800
2801     You can disable this operator by defining \c
2802     QT_NO_CAST_FROM_ASCII when you compile your applications. You
2803     then need to call QString::fromAscii(), QString::fromLatin1(),
2804     QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2805     you want to convert the byte array to a QString before doing the
2806     comparison.
2807 */
2808
2809 /*! \fn bool QByteArray::operator!=(const QString &str) const
2810
2811     Returns true if this byte array is not equal to string \a str;
2812     otherwise returns false.
2813
2814     The Unicode data is converted into 8-bit characters using
2815     QString::toAscii().
2816
2817     The comparison is case sensitive.
2818
2819     You can disable this operator by defining \c
2820     QT_NO_CAST_FROM_ASCII when you compile your applications. You
2821     then need to call QString::fromAscii(), QString::fromLatin1(),
2822     QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2823     you want to convert the byte array to a QString before doing the
2824     comparison.
2825 */
2826
2827 /*! \fn bool QByteArray::operator<(const QString &str) const
2828
2829     Returns true if this byte array is lexically less than string \a
2830     str; otherwise returns false.
2831
2832     The Unicode data is converted into 8-bit characters using
2833     QString::toAscii().
2834
2835     The comparison is case sensitive.
2836
2837     You can disable this operator by defining \c
2838     QT_NO_CAST_FROM_ASCII when you compile your applications. You
2839     then need to call QString::fromAscii(), QString::fromLatin1(),
2840     QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2841     you want to convert the byte array to a QString before doing the
2842     comparison.
2843 */
2844
2845 /*! \fn bool QByteArray::operator>(const QString &str) const
2846
2847     Returns true if this byte array is lexically greater than string
2848     \a str; otherwise returns false.
2849
2850     The Unicode data is converted into 8-bit characters using
2851     QString::toAscii().
2852
2853     The comparison is case sensitive.
2854
2855     You can disable this operator by defining \c
2856     QT_NO_CAST_FROM_ASCII when you compile your applications. You
2857     then need to call QString::fromAscii(), QString::fromLatin1(),
2858     QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2859     you want to convert the byte array to a QString before doing the
2860     comparison.
2861 */
2862
2863 /*! \fn bool QByteArray::operator<=(const QString &str) const
2864
2865     Returns true if this byte array is lexically less than or equal
2866     to string \a str; otherwise returns false.
2867
2868     The Unicode data is converted into 8-bit characters using
2869     QString::toAscii().
2870
2871     The comparison is case sensitive.
2872
2873     You can disable this operator by defining \c
2874     QT_NO_CAST_FROM_ASCII when you compile your applications. You
2875     then need to call QString::fromAscii(), QString::fromLatin1(),
2876     QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2877     you want to convert the byte array to a QString before doing the
2878     comparison.
2879 */
2880
2881 /*! \fn bool QByteArray::operator>=(const QString &str) const
2882
2883     Returns true if this byte array is greater than or equal to string
2884     \a str; otherwise returns false.
2885
2886     The Unicode data is converted into 8-bit characters using
2887     QString::toAscii().
2888
2889     The comparison is case sensitive.
2890
2891     You can disable this operator by defining \c
2892     QT_NO_CAST_FROM_ASCII when you compile your applications. You
2893     then need to call QString::fromAscii(), QString::fromLatin1(),
2894     QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2895     you want to convert the byte array to a QString before doing the
2896     comparison.
2897 */
2898
2899 /*! \fn bool operator==(const QByteArray &a1, const QByteArray &a2)
2900     \relates QByteArray
2901
2902     \overload
2903
2904     Returns true if byte array \a a1 is equal to byte array \a a2;
2905     otherwise returns false.
2906 */
2907
2908 /*! \fn bool operator==(const QByteArray &a1, const char *a2)
2909     \relates QByteArray
2910
2911     \overload
2912
2913     Returns true if byte array \a a1 is equal to string \a a2;
2914     otherwise returns false.
2915 */
2916
2917 /*! \fn bool operator==(const char *a1, const QByteArray &a2)
2918     \relates QByteArray
2919
2920     \overload
2921
2922     Returns true if string \a a1 is equal to byte array \a a2;
2923     otherwise returns false.
2924 */
2925
2926 /*! \fn bool operator!=(const QByteArray &a1, const QByteArray &a2)
2927     \relates QByteArray
2928
2929     \overload
2930
2931     Returns true if byte array \a a1 is not equal to byte array \a a2;
2932     otherwise returns false.
2933 */
2934
2935 /*! \fn bool operator!=(const QByteArray &a1, const char *a2)
2936     \relates QByteArray
2937
2938     \overload
2939
2940     Returns true if byte array \a a1 is not equal to string \a a2;
2941     otherwise returns false.
2942 */
2943
2944 /*! \fn bool operator!=(const char *a1, const QByteArray &a2)
2945     \relates QByteArray
2946
2947     \overload
2948
2949     Returns true if string \a a1 is not equal to byte array \a a2;
2950     otherwise returns false.
2951 */
2952
2953 /*! \fn bool operator<(const QByteArray &a1, const QByteArray &a2)
2954     \relates QByteArray
2955
2956     \overload
2957
2958     Returns true if byte array \a a1 is lexically less than byte array
2959     \a a2; otherwise returns false.
2960 */
2961
2962 /*! \fn inline bool operator<(const QByteArray &a1, const char *a2)
2963     \relates QByteArray
2964
2965     \overload
2966
2967     Returns true if byte array \a a1 is lexically less than string
2968     \a a2; otherwise returns false.
2969 */
2970
2971 /*! \fn bool operator<(const char *a1, const QByteArray &a2)
2972     \relates QByteArray
2973
2974     \overload
2975
2976     Returns true if string \a a1 is lexically less than byte array
2977     \a a2; otherwise returns false.
2978 */
2979
2980 /*! \fn bool operator<=(const QByteArray &a1, const QByteArray &a2)
2981     \relates QByteArray
2982
2983     \overload
2984
2985     Returns true if byte array \a a1 is lexically less than or equal
2986     to byte array \a a2; otherwise returns false.
2987 */
2988
2989 /*! \fn bool operator<=(const QByteArray &a1, const char *a2)
2990     \relates QByteArray
2991
2992     \overload
2993
2994     Returns true if byte array \a a1 is lexically less than or equal
2995     to string \a a2; otherwise returns false.
2996 */
2997
2998 /*! \fn bool operator<=(const char *a1, const QByteArray &a2)
2999     \relates QByteArray
3000
3001     \overload
3002
3003     Returns true if string \a a1 is lexically less than or equal
3004     to byte array \a a2; otherwise returns false.
3005 */
3006
3007 /*! \fn bool operator>(const QByteArray &a1, const QByteArray &a2)
3008     \relates QByteArray
3009
3010     \overload
3011
3012     Returns true if byte array \a a1 is lexically greater than byte
3013     array \a a2; otherwise returns false.
3014 */
3015
3016 /*! \fn bool operator>(const QByteArray &a1, const char *a2)
3017     \relates QByteArray
3018
3019     \overload
3020
3021     Returns true if byte array \a a1 is lexically greater than string
3022     \a a2; otherwise returns false.
3023 */
3024
3025 /*! \fn bool operator>(const char *a1, const QByteArray &a2)
3026     \relates QByteArray
3027
3028     \overload
3029
3030     Returns true if string \a a1 is lexically greater than byte array
3031     \a a2; otherwise returns false.
3032 */
3033
3034 /*! \fn bool operator>=(const QByteArray &a1, const QByteArray &a2)
3035     \relates QByteArray
3036
3037     \overload
3038
3039     Returns true if byte array \a a1 is lexically greater than or
3040     equal to byte array \a a2; otherwise returns false.
3041 */
3042
3043 /*! \fn bool operator>=(const QByteArray &a1, const char *a2)
3044     \relates QByteArray
3045
3046     \overload
3047
3048     Returns true if byte array \a a1 is lexically greater than or
3049     equal to string \a a2; otherwise returns false.
3050 */
3051
3052 /*! \fn bool operator>=(const char *a1, const QByteArray &a2)
3053     \relates QByteArray
3054
3055     \overload
3056
3057     Returns true if string \a a1 is lexically greater than or
3058     equal to byte array \a a2; otherwise returns false.
3059 */
3060
3061 /*! \fn const QByteArray operator+(const QByteArray &a1, const QByteArray &a2)
3062     \relates QByteArray
3063
3064     Returns a byte array that is the result of concatenating byte
3065     array \a a1 and byte array \a a2.
3066
3067     \sa QByteArray::operator+=()
3068 */
3069
3070 /*! \fn const QByteArray operator+(const QByteArray &a1, const char *a2)
3071     \relates QByteArray
3072
3073     \overload
3074
3075     Returns a byte array that is the result of concatenating byte
3076     array \a a1 and string \a a2.
3077 */
3078
3079 /*! \fn const QByteArray operator+(const QByteArray &a1, char a2)
3080     \relates QByteArray
3081
3082     \overload
3083
3084     Returns a byte array that is the result of concatenating byte
3085     array \a a1 and character \a a2.
3086 */
3087
3088 /*! \fn const QByteArray operator+(const char *a1, const QByteArray &a2)
3089     \relates QByteArray
3090
3091     \overload
3092
3093     Returns a byte array that is the result of concatenating string
3094     \a a1 and byte array \a a2.
3095 */
3096
3097 /*! \fn const QByteArray operator+(char a1, const QByteArray &a2)
3098     \relates QByteArray
3099
3100     \overload
3101
3102     Returns a byte array that is the result of concatenating character
3103     \a a1 and byte array \a a2.
3104 */
3105
3106 /*!
3107     Returns a byte array that has whitespace removed from the start
3108     and the end, and which has each sequence of internal whitespace
3109     replaced with a single space.
3110
3111     Whitespace means any character for which the standard C++
3112     isspace() function returns true. This includes the ASCII
3113     characters '\\t', '\\n', '\\v', '\\f', '\\r', and ' '.
3114
3115     Example:
3116     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 32
3117
3118     \sa trimmed()
3119 */
3120 QByteArray QByteArray::simplified() const
3121 {
3122     if (d->size == 0)
3123         return *this;
3124     QByteArray result(d->size, Qt::Uninitialized);
3125     const char *from = d->data();
3126     const char *fromend = from + d->size;
3127     int outc=0;
3128     char *to = result.d->data();
3129     for (;;) {
3130         while (from!=fromend && isspace(uchar(*from)))
3131             from++;
3132         while (from!=fromend && !isspace(uchar(*from)))
3133             to[outc++] = *from++;
3134         if (from!=fromend)
3135             to[outc++] = ' ';
3136         else
3137             break;
3138     }
3139     if (outc > 0 && to[outc-1] == ' ')
3140         outc--;
3141     result.resize(outc);
3142     return result;
3143 }
3144
3145 /*!
3146     Returns a byte array that has whitespace removed from the start
3147     and the end.
3148
3149     Whitespace means any character for which the standard C++
3150     isspace() function returns true. This includes the ASCII
3151     characters '\\t', '\\n', '\\v', '\\f', '\\r', and ' '.
3152
3153     Example:
3154     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 33
3155
3156     Unlike simplified(), trimmed() leaves internal whitespace alone.
3157
3158     \sa simplified()
3159 */
3160 QByteArray QByteArray::trimmed() const
3161 {
3162     if (d->size == 0)
3163         return *this;
3164     const char *s = d->data();
3165     if (!isspace(uchar(*s)) && !isspace(uchar(s[d->size-1])))
3166         return *this;
3167     int start = 0;
3168     int end = d->size - 1;
3169     while (start<=end && isspace(uchar(s[start])))  // skip white space from start
3170         start++;
3171     if (start <= end) {                          // only white space
3172         while (end && isspace(uchar(s[end])))           // skip white space from end
3173             end--;
3174     }
3175     int l = end - start + 1;
3176     if (l <= 0) {
3177         return QByteArray(const_cast<Data *>(&shared_empty.ba), 0, 0);
3178     }
3179     return QByteArray(s+start, l);
3180 }
3181
3182 /*!
3183     Returns a byte array of size \a width that contains this byte
3184     array padded by the \a fill character.
3185
3186     If \a truncate is false and the size() of the byte array is more
3187     than \a width, then the returned byte array is a copy of this byte
3188     array.
3189
3190     If \a truncate is true and the size() of the byte array is more
3191     than \a width, then any bytes in a copy of the byte array
3192     after position \a width are removed, and the copy is returned.
3193
3194     Example:
3195     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 34
3196
3197     \sa rightJustified()
3198 */
3199
3200 QByteArray QByteArray::leftJustified(int width, char fill, bool truncate) const
3201 {
3202     QByteArray result;
3203     int len = d->size;
3204     int padlen = width - len;
3205     if (padlen > 0) {
3206         result.resize(len+padlen);
3207         if (len)
3208             memcpy(result.d->data(), d->data(), len);
3209         memset(result.d->data()+len, fill, padlen);
3210     } else {
3211         if (truncate)
3212             result = left(width);
3213         else
3214             result = *this;
3215     }
3216     return result;
3217 }
3218
3219 /*!
3220     Returns a byte array of size \a width that contains the \a fill
3221     character followed by this byte array.
3222
3223     If \a truncate is false and the size of the byte array is more
3224     than \a width, then the returned byte array is a copy of this byte
3225     array.
3226
3227     If \a truncate is true and the size of the byte array is more
3228     than \a width, then the resulting byte array is truncated at
3229     position \a width.
3230
3231     Example:
3232     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 35
3233
3234     \sa leftJustified()
3235 */
3236
3237 QByteArray QByteArray::rightJustified(int width, char fill, bool truncate) const
3238 {
3239     QByteArray result;
3240     int len = d->size;
3241     int padlen = width - len;
3242     if (padlen > 0) {
3243         result.resize(len+padlen);
3244         if (len)
3245             memcpy(result.d->data()+padlen, data(), len);
3246         memset(result.d->data(), fill, padlen);
3247     } else {
3248         if (truncate)
3249             result = left(width);
3250         else
3251             result = *this;
3252     }
3253     return result;
3254 }
3255
3256 bool QByteArray::isNull() const { return d == &shared_null.ba; }
3257
3258
3259 /*!
3260     Returns the byte array converted to a \c {long long} using base \a
3261     base, which is 10 by default and must be between 2 and 36, or 0.
3262
3263     If \a base is 0, the base is determined automatically using the
3264     following rules: If the byte array begins with "0x", it is assumed to
3265     be hexadecimal; if it begins with "0", it is assumed to be octal;
3266     otherwise it is assumed to be decimal.
3267
3268     Returns 0 if the conversion fails.
3269
3270     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3271     false; otherwise *\a{ok} is set to true.
3272
3273     \note The conversion of the number is performed in the default C locale,
3274     irrespective of the user's locale.
3275
3276     \sa number()
3277 */
3278
3279 qlonglong QByteArray::toLongLong(bool *ok, int base) const
3280 {
3281 #if defined(QT_CHECK_RANGE)
3282     if (base != 0 && (base < 2 || base > 36)) {
3283         qWarning("QByteArray::toLongLong: Invalid base %d", base);
3284         base = 10;
3285     }
3286 #endif
3287
3288     return QLocalePrivate::bytearrayToLongLong(nulTerminated().constData(), base, ok);
3289 }
3290
3291 /*!
3292     Returns the byte array converted to an \c {unsigned long long}
3293     using base \a base, which is 10 by default and must be between 2
3294     and 36, or 0.
3295
3296     If \a base is 0, the base is determined automatically using the
3297     following rules: If the byte array begins with "0x", it is assumed to
3298     be hexadecimal; if it begins with "0", it is assumed to be octal;
3299     otherwise it is assumed to be decimal.
3300
3301     Returns 0 if the conversion fails.
3302
3303     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3304     false; otherwise *\a{ok} is set to true.
3305
3306     \note The conversion of the number is performed in the default C locale,
3307     irrespective of the user's locale.
3308
3309     \sa number()
3310 */
3311
3312 qulonglong QByteArray::toULongLong(bool *ok, int base) const
3313 {
3314 #if defined(QT_CHECK_RANGE)
3315     if (base != 0 && (base < 2 || base > 36)) {
3316         qWarning("QByteArray::toULongLong: Invalid base %d", base);
3317         base = 10;
3318     }
3319 #endif
3320
3321     return QLocalePrivate::bytearrayToUnsLongLong(nulTerminated().constData(), base, ok);
3322 }
3323
3324
3325 /*!
3326     Returns the byte array converted to an \c int using base \a
3327     base, which is 10 by default and must be between 2 and 36, or 0.
3328
3329     If \a base is 0, the base is determined automatically using the
3330     following rules: If the byte array begins with "0x", it is assumed to
3331     be hexadecimal; if it begins with "0", it is assumed to be octal;
3332     otherwise it is assumed to be decimal.
3333
3334     Returns 0 if the conversion fails.
3335
3336     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3337     false; otherwise *\a{ok} is set to true.
3338
3339     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 36
3340
3341     \note The conversion of the number is performed in the default C locale,
3342     irrespective of the user's locale.
3343
3344     \sa number()
3345 */
3346
3347 int QByteArray::toInt(bool *ok, int base) const
3348 {
3349     qlonglong v = toLongLong(ok, base);
3350     if (v < INT_MIN || v > INT_MAX) {
3351         if (ok)
3352             *ok = false;
3353         v = 0;
3354     }
3355     return int(v);
3356 }
3357
3358 /*!
3359     Returns the byte array converted to an \c {unsigned int} using base \a
3360     base, which is 10 by default and must be between 2 and 36, or 0.
3361
3362     If \a base is 0, the base is determined automatically using the
3363     following rules: If the byte array begins with "0x", it is assumed to
3364     be hexadecimal; if it begins with "0", it is assumed to be octal;
3365     otherwise it is assumed to be decimal.
3366
3367     Returns 0 if the conversion fails.
3368
3369     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3370     false; otherwise *\a{ok} is set to true.
3371
3372     \note The conversion of the number is performed in the default C locale,
3373     irrespective of the user's locale.
3374
3375     \sa number()
3376 */
3377
3378 uint QByteArray::toUInt(bool *ok, int base) const
3379 {
3380     qulonglong v = toULongLong(ok, base);
3381     if (v > UINT_MAX) {
3382         if (ok)
3383             *ok = false;
3384         v = 0;
3385     }
3386     return uint(v);
3387 }
3388
3389 /*!
3390     \since 4.1
3391
3392     Returns the byte array converted to a \c long int using base \a
3393     base, which is 10 by default and must be between 2 and 36, or 0.
3394
3395     If \a base is 0, the base is determined automatically using the
3396     following rules: If the byte array begins with "0x", it is assumed to
3397     be hexadecimal; if it begins with "0", it is assumed to be octal;
3398     otherwise it is assumed to be decimal.
3399
3400     Returns 0 if the conversion fails.
3401
3402     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3403     false; otherwise *\a{ok} is set to true.
3404
3405     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 37
3406
3407     \note The conversion of the number is performed in the default C locale,
3408     irrespective of the user's locale.
3409
3410     \sa number()
3411 */
3412 long QByteArray::toLong(bool *ok, int base) const
3413 {
3414     qlonglong v = toLongLong(ok, base);
3415     if (v < LONG_MIN || v > LONG_MAX) {
3416         if (ok)
3417             *ok = false;
3418         v = 0;
3419     }
3420     return long(v);
3421 }
3422
3423 /*!
3424     \since 4.1
3425
3426     Returns the byte array converted to an \c {unsigned long int} using base \a
3427     base, which is 10 by default and must be between 2 and 36, or 0.
3428
3429     If \a base is 0, the base is determined automatically using the
3430     following rules: If the byte array begins with "0x", it is assumed to
3431     be hexadecimal; if it begins with "0", it is assumed to be octal;
3432     otherwise it is assumed to be decimal.
3433
3434     Returns 0 if the conversion fails.
3435
3436     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3437     false; otherwise *\a{ok} is set to true.
3438
3439     \note The conversion of the number is performed in the default C locale,
3440     irrespective of the user's locale.
3441
3442     \sa number()
3443 */
3444 ulong QByteArray::toULong(bool *ok, int base) const
3445 {
3446     qulonglong v = toULongLong(ok, base);
3447     if (v > ULONG_MAX) {
3448         if (ok)
3449             *ok = false;
3450         v = 0;
3451     }
3452     return ulong(v);
3453 }
3454
3455 /*!
3456     Returns the byte array converted to a \c short using base \a
3457     base, which is 10 by default and must be between 2 and 36, or 0.
3458
3459     If \a base is 0, the base is determined automatically using the
3460     following rules: If the byte array begins with "0x", it is assumed to
3461     be hexadecimal; if it begins with "0", it is assumed to be octal;
3462     otherwise it is assumed to be decimal.
3463
3464     Returns 0 if the conversion fails.
3465
3466     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3467     false; otherwise *\a{ok} is set to true.
3468
3469     \note The conversion of the number is performed in the default C locale,
3470     irrespective of the user's locale.
3471
3472     \sa number()
3473 */
3474
3475 short QByteArray::toShort(bool *ok, int base) const
3476 {
3477     qlonglong v = toLongLong(ok, base);
3478     if (v < SHRT_MIN || v > SHRT_MAX) {
3479         if (ok)
3480             *ok = false;
3481         v = 0;
3482     }
3483     return short(v);
3484 }
3485
3486 /*!
3487     Returns the byte array converted to an \c {unsigned short} using base \a
3488     base, which is 10 by default and must be between 2 and 36, or 0.
3489
3490     If \a base is 0, the base is determined automatically using the
3491     following rules: If the byte array begins with "0x", it is assumed to
3492     be hexadecimal; if it begins with "0", it is assumed to be octal;
3493     otherwise it is assumed to be decimal.
3494
3495     Returns 0 if the conversion fails.
3496
3497     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3498     false; otherwise *\a{ok} is set to true.
3499
3500     \note The conversion of the number is performed in the default C locale,
3501     irrespective of the user's locale.
3502
3503     \sa number()
3504 */
3505
3506 ushort QByteArray::toUShort(bool *ok, int base) const
3507 {
3508     qulonglong v = toULongLong(ok, base);
3509     if (v > USHRT_MAX) {
3510         if (ok)
3511             *ok = false;
3512         v = 0;
3513     }
3514     return ushort(v);
3515 }
3516
3517
3518 /*!
3519     Returns the byte array converted to a \c double value.
3520
3521     Returns 0.0 if the conversion fails.
3522
3523     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3524     false; otherwise *\a{ok} is set to true.
3525
3526     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 38
3527
3528     \note The conversion of the number is performed in the default C locale,
3529     irrespective of the user's locale.
3530
3531     \sa number()
3532 */
3533
3534 double QByteArray::toDouble(bool *ok) const
3535 {
3536     return QLocalePrivate::bytearrayToDouble(nulTerminated().constData(), ok);
3537 }
3538
3539 /*!
3540     Returns the byte array converted to a \c float value.
3541
3542     Returns 0.0 if the conversion fails.
3543
3544     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3545     false; otherwise *\a{ok} is set to true.
3546
3547     \note The conversion of the number is performed in the default C locale,
3548     irrespective of the user's locale.
3549
3550     \sa number()
3551 */
3552
3553 float QByteArray::toFloat(bool *ok) const
3554 {
3555     return float(toDouble(ok));
3556 }
3557
3558 /*!
3559     Returns a copy of the byte array, encoded as Base64.
3560
3561     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 39
3562
3563     The algorithm used to encode Base64-encoded data is defined in \l{RFC 2045}.
3564
3565     \sa fromBase64()
3566 */
3567 QByteArray QByteArray::toBase64() const
3568 {
3569     const char alphabet[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
3570                             "ghijklmn" "opqrstuv" "wxyz0123" "456789+/";
3571     const char padchar = '=';
3572     int padlen = 0;
3573
3574     QByteArray tmp((d->size * 4) / 3 + 3, Qt::Uninitialized);
3575
3576     int i = 0;
3577     char *out = tmp.data();
3578     while (i < d->size) {
3579         int chunk = 0;
3580         chunk |= int(uchar(d->data()[i++])) << 16;
3581         if (i == d->size) {
3582             padlen = 2;
3583         } else {
3584             chunk |= int(uchar(d->data()[i++])) << 8;
3585             if (i == d->size) padlen = 1;
3586             else chunk |= int(uchar(d->data()[i++]));
3587         }
3588
3589         int j = (chunk & 0x00fc0000) >> 18;
3590         int k = (chunk & 0x0003f000) >> 12;
3591         int l = (chunk & 0x00000fc0) >> 6;
3592         int m = (chunk & 0x0000003f);
3593         *out++ = alphabet[j];
3594         *out++ = alphabet[k];
3595         if (padlen > 1) *out++ = padchar;
3596         else *out++ = alphabet[l];
3597         if (padlen > 0) *out++ = padchar;
3598         else *out++ = alphabet[m];
3599     }
3600
3601     tmp.truncate(out - tmp.data());
3602     return tmp;
3603 }
3604
3605 /*! 
3606     \fn QByteArray &QByteArray::setNum(int n, int base)
3607
3608     Sets the byte array to the printed value of \a n in base \a base (10
3609     by default) and returns a reference to the byte array. The \a base can
3610     be any value between 2 and 36.
3611
3612     Example:
3613     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 40
3614
3615     \note The format of the number is not localized; the default C locale
3616     is used irrespective of the user's locale.
3617
3618     \sa number(), toInt()
3619 */
3620
3621 /*! 
3622     \fn QByteArray &QByteArray::setNum(uint n, int base)
3623     \overload
3624
3625     \sa toUInt()
3626 */
3627
3628 /*! 
3629     \fn QByteArray &QByteArray::setNum(short n, int base)
3630     \overload
3631
3632     \sa toShort()
3633 */
3634
3635 /*! 
3636     \fn QByteArray &QByteArray::setNum(ushort n, int base)
3637     \overload
3638
3639     \sa toUShort()
3640 */
3641
3642 /*!
3643     \overload
3644
3645     \sa toLongLong()
3646 */
3647
3648 QByteArray &QByteArray::setNum(qlonglong n, int base)
3649 {
3650 #if defined(QT_CHECK_RANGE)
3651     if (base < 2 || base > 36) {
3652         qWarning("QByteArray::setNum: Invalid base %d", base);
3653         base = 10;
3654     }
3655 #endif
3656     QLocale locale(QLocale::C);
3657     *this = locale.d()->longLongToString(n, -1, base).toLatin1();
3658     return *this;
3659 }
3660
3661 /*!
3662     \overload
3663
3664     \sa toULongLong()
3665 */
3666
3667 QByteArray &QByteArray::setNum(qulonglong n, int base)
3668 {
3669 #if defined(QT_CHECK_RANGE)
3670     if (base < 2 || base > 36) {
3671         qWarning("QByteArray::setNum: Invalid base %d", base);
3672         base = 10;
3673     }
3674 #endif
3675     QLocale locale(QLocale::C);
3676     *this = locale.d()->unsLongLongToString(n, -1, base).toLatin1();
3677     return *this;
3678 }
3679
3680 /*! 
3681     \overload
3682
3683     Sets the byte array to the printed value of \a n, formatted in format
3684     \a f with precision \a prec, and returns a reference to the
3685     byte array.
3686
3687     The format \a f can be any of the following:
3688
3689     \table
3690     \header \i Format \i Meaning
3691     \row \i \c e \i format as [-]9.9e[+|-]999
3692     \row \i \c E \i format as [-]9.9E[+|-]999
3693     \row \i \c f \i format as [-]9.9
3694     \row \i \c g \i use \c e or \c f format, whichever is the most concise
3695     \row \i \c G \i use \c E or \c f format, whichever is the most concise
3696     \endtable
3697
3698     With 'e', 'E', and 'f', \a prec is the number of digits after the
3699     decimal point. With 'g' and 'G', \a prec is the maximum number of
3700     significant digits (trailing zeroes are omitted).
3701
3702     \note The format of the number is not localized; the default C locale
3703     is used irrespective of the user's locale.
3704
3705     \sa toDouble()
3706 */
3707
3708 QByteArray &QByteArray::setNum(double n, char f, int prec)
3709 {
3710     QLocalePrivate::DoubleForm form = QLocalePrivate::DFDecimal;
3711     uint flags = 0;
3712
3713     if (qIsUpper(f))
3714         flags = QLocalePrivate::CapitalEorX;
3715     f = qToLower(f);
3716
3717     switch (f) {
3718         case 'f':
3719             form = QLocalePrivate::DFDecimal;
3720             break;
3721         case 'e':
3722             form = QLocalePrivate::DFExponent;
3723             break;
3724         case 'g':
3725             form = QLocalePrivate::DFSignificantDigits;
3726             break;
3727         default:
3728 #if defined(QT_CHECK_RANGE)
3729             qWarning("QByteArray::setNum: Invalid format char '%c'", f);
3730 #endif
3731             break;
3732     }
3733
3734     QLocale locale(QLocale::C);
3735     *this = locale.d()->doubleToString(n, prec, form, -1, flags).toLatin1();
3736     return *this;
3737 }
3738
3739 /*! 
3740     \fn QByteArray &QByteArray::setNum(float n, char f, int prec)
3741     \overload
3742
3743     Sets the byte array to the printed value of \a n, formatted in format
3744     \a f with precision \a prec, and returns a reference to the
3745     byte array.
3746
3747     \note The format of the number is not localized; the default C locale
3748     is used irrespective of the user's locale.
3749
3750     \sa toFloat()
3751 */
3752
3753 /*!
3754     Returns a byte array containing the string equivalent of the
3755     number \a n to base \a base (10 by default). The \a base can be
3756     any value between 2 and 36.
3757
3758     Example:
3759     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 41
3760
3761     \note The format of the number is not localized; the default C locale
3762     is used irrespective of the user's locale.
3763
3764     \sa setNum(), toInt()
3765 */
3766 QByteArray QByteArray::number(int n, int base)
3767 {
3768     QByteArray s;
3769     s.setNum(n, base);
3770     return s;
3771 }
3772
3773 /*!
3774     \overload
3775
3776     \sa toUInt()
3777 */
3778 QByteArray QByteArray::number(uint n, int base)
3779 {
3780     QByteArray s;
3781     s.setNum(n, base);
3782     return s;
3783 }
3784
3785 /*!
3786     \overload
3787
3788     \sa toLongLong()
3789 */
3790 QByteArray QByteArray::number(qlonglong n, int base)
3791 {
3792     QByteArray s;
3793     s.setNum(n, base);
3794     return s;
3795 }
3796
3797 /*!
3798     \overload
3799
3800     \sa toULongLong()
3801 */
3802 QByteArray QByteArray::number(qulonglong n, int base)
3803 {
3804     QByteArray s;
3805     s.setNum(n, base);
3806     return s;
3807 }
3808
3809 /*! 
3810     \overload
3811
3812     Returns a byte array that contains the printed value of \a n,
3813     formatted in format \a f with precision \a prec.
3814
3815     Argument \a n is formatted according to the \a f format specified,
3816     which is \c g by default, and can be any of the following:
3817
3818     \table
3819     \header \i Format \i Meaning
3820     \row \i \c e \i format as [-]9.9e[+|-]999
3821     \row \i \c E \i format as [-]9.9E[+|-]999
3822     \row \i \c f \i format as [-]9.9
3823     \row \i \c g \i use \c e or \c f format, whichever is the most concise
3824     \row \i \c G \i use \c E or \c f format, whichever is the most concise
3825     \endtable
3826
3827     With 'e', 'E', and 'f', \a prec is the number of digits after the
3828     decimal point. With 'g' and 'G', \a prec is the maximum number of
3829     significant digits (trailing zeroes are omitted).
3830
3831     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 42
3832
3833     \note The format of the number is not localized; the default C locale
3834     is used irrespective of the user's locale.
3835
3836     \sa toDouble()
3837 */
3838 QByteArray QByteArray::number(double n, char f, int prec)
3839 {
3840     QByteArray s;
3841     s.setNum(n, f, prec);
3842     return s;
3843 }
3844
3845 /*!
3846     Constructs a QByteArray that uses the first \a size bytes of the
3847     \a data array. The bytes are \e not copied. The QByteArray will
3848     contain the \a data pointer. The caller guarantees that \a data
3849     will not be deleted or modified as long as this QByteArray and any
3850     copies of it exist that have not been modified. In other words,
3851     because QByteArray is an \l{implicitly shared} class and the
3852     instance returned by this function contains the \a data pointer,
3853     the caller must not delete \a data or modify it directly as long
3854     as the returned QByteArray and any copies exist. However,
3855     QByteArray does not take ownership of \a data, so the QByteArray
3856     destructor will never delete the raw \a data, even when the
3857     last QByteArray referring to \a data is destroyed.
3858
3859     A subsequent attempt to modify the contents of the returned
3860     QByteArray or any copy made from it will cause it to create a deep
3861     copy of the \a data array before doing the modification. This
3862     ensures that the raw \a data array itself will never be modified
3863     by QByteArray.
3864
3865     Here is an example of how to read data using a QDataStream on raw
3866     data in memory without copying the raw data into a QByteArray:
3867
3868     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 43
3869
3870     \warning A byte array created with fromRawData() is \e not
3871     null-terminated, unless the raw data contains a 0 character at
3872     position \a size. While that does not matter for QDataStream or
3873     functions like indexOf(), passing the byte array to a function
3874     accepting a \c{const char *} expected to be '\\0'-terminated will
3875     fail.
3876
3877     \sa setRawData(), data(), constData()
3878 */
3879
3880 QByteArray QByteArray::fromRawData(const char *data, int size)
3881 {
3882     Data *x;
3883     if (!data) {
3884         x = const_cast<Data *>(&shared_null.ba);
3885     } else if (!size) {
3886         x = const_cast<Data *>(&shared_empty.ba);
3887     } else {
3888         x = static_cast<Data *>(qMalloc(sizeof(Data) + 1));
3889         Q_CHECK_PTR(x);
3890         x->ref = 1;
3891         x->size = size;
3892         x->alloc = 0;
3893         x->capacityReserved = false;
3894         x->offset = data - (x->d + sizeof(qptrdiff));
3895     }
3896     return QByteArray(x, 0, 0);
3897 }
3898
3899 /*!
3900     \since 4.7
3901
3902     Resets the QByteArray to use the first \a size bytes of the
3903     \a data array. The bytes are \e not copied. The QByteArray will
3904     contain the \a data pointer. The caller guarantees that \a data
3905     will not be deleted or modified as long as this QByteArray and any
3906     copies of it exist that have not been modified.
3907
3908     This function can be used instead of fromRawData() to re-use
3909     existings QByteArray objects to save memory re-allocations.
3910
3911     \sa fromRawData(), data(), constData()
3912 */
3913 QByteArray &QByteArray::setRawData(const char *data, uint size)
3914 {
3915     if (d->ref != 1 || d->alloc) {
3916         *this = fromRawData(data, size);
3917     } else {
3918         if (data) {
3919             d->size = size;
3920             d->offset = data - (d->d + sizeof(qptrdiff));
3921         } else {
3922             d->offset = 0;
3923             d->size = 0;
3924             *d->data() = 0;
3925         }
3926     }
3927     return *this;
3928 }
3929
3930 /*!
3931     Returns a decoded copy of the Base64 array \a base64. Input is not checked
3932     for validity; invalid characters in the input are skipped, enabling the
3933     decoding process to continue with subsequent characters.
3934
3935     For example:
3936
3937     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 44
3938
3939     The algorithm used to decode Base64-encoded data is defined in \l{RFC 2045}.
3940
3941     \sa toBase64()
3942 */
3943 QByteArray QByteArray::fromBase64(const QByteArray &base64)
3944 {
3945     unsigned int buf = 0;
3946     int nbits = 0;
3947     QByteArray tmp((base64.size() * 3) / 4, Qt::Uninitialized);
3948
3949     int offset = 0;
3950     for (int i = 0; i < base64.size(); ++i) {
3951         int ch = base64.at(i);
3952         int d;
3953
3954         if (ch >= 'A' && ch <= 'Z')
3955             d = ch - 'A';
3956         else if (ch >= 'a' && ch <= 'z')
3957             d = ch - 'a' + 26;
3958         else if (ch >= '0' && ch <= '9')
3959             d = ch - '0' + 52;
3960         else if (ch == '+')
3961             d = 62;
3962         else if (ch == '/')
3963             d = 63;
3964         else
3965             d = -1;
3966
3967         if (d != -1) {
3968             buf = (buf << 6) | d;
3969             nbits += 6;
3970             if (nbits >= 8) {
3971                 nbits -= 8;
3972                 tmp[offset++] = buf >> nbits;
3973                 buf &= (1 << nbits) - 1;
3974             }
3975         }
3976     }
3977
3978     tmp.truncate(offset);
3979     return tmp;
3980 }
3981
3982 /*!
3983     Returns a decoded copy of the hex encoded array \a hexEncoded. Input is not checked
3984     for validity; invalid characters in the input are skipped, enabling the
3985     decoding process to continue with subsequent characters.
3986
3987     For example:
3988
3989     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 45
3990
3991     \sa toHex()
3992 */
3993 QByteArray QByteArray::fromHex(const QByteArray &hexEncoded)
3994 {
3995     QByteArray res((hexEncoded.size() + 1)/ 2, Qt::Uninitialized);
3996     uchar *result = (uchar *)res.data() + res.size();
3997
3998     bool odd_digit = true;
3999     for (int i = hexEncoded.size() - 1; i >= 0; --i) {
4000         int ch = hexEncoded.at(i);
4001         int tmp;
4002         if (ch >= '0' && ch <= '9')
4003             tmp = ch - '0';
4004         else if (ch >= 'a' && ch <= 'f')
4005             tmp = ch - 'a' + 10;
4006         else if (ch >= 'A' && ch <= 'F')
4007             tmp = ch - 'A' + 10;
4008         else
4009             continue;
4010         if (odd_digit) {
4011             --result;
4012             *result = tmp;
4013             odd_digit = false;
4014         } else {
4015             *result |= tmp << 4;
4016             odd_digit = true;
4017         }
4018     }
4019
4020     res.remove(0, result - (const uchar *)res.constData());
4021     return res;
4022 }
4023
4024 /*!
4025     Returns a hex encoded copy of the byte array. The hex encoding uses the numbers 0-9 and
4026     the letters a-f.
4027
4028     \sa fromHex()
4029 */
4030 QByteArray QByteArray::toHex() const
4031 {
4032     QByteArray hex(d->size * 2, Qt::Uninitialized);
4033     char *hexData = hex.data();
4034     const uchar *data = (const uchar *)d->data();
4035     for (int i = 0; i < d->size; ++i) {
4036         int j = (data[i] >> 4) & 0xf;
4037         if (j <= 9)
4038             hexData[i*2] = (j + '0');
4039          else
4040             hexData[i*2] = (j + 'a' - 10);
4041         j = data[i] & 0xf;
4042         if (j <= 9)
4043             hexData[i*2+1] = (j + '0');
4044          else
4045             hexData[i*2+1] = (j + 'a' - 10);
4046     }
4047     return hex;
4048 }
4049
4050 static void q_fromPercentEncoding(QByteArray *ba, char percent)
4051 {
4052     if (ba->isEmpty())
4053         return;
4054
4055     char *data = ba->data();
4056     const char *inputPtr = data;
4057
4058     int i = 0;
4059     int len = ba->count();
4060     int outlen = 0;
4061     int a, b;
4062     char c;
4063     while (i < len) {
4064         c = inputPtr[i];
4065         if (c == percent && i + 2 < len) {
4066             a = inputPtr[++i];
4067             b = inputPtr[++i];
4068
4069             if (a >= '0' && a <= '9') a -= '0';
4070             else if (a >= 'a' && a <= 'f') a = a - 'a' + 10;
4071             else if (a >= 'A' && a <= 'F') a = a - 'A' + 10;
4072
4073             if (b >= '0' && b <= '9') b -= '0';
4074             else if (b >= 'a' && b <= 'f') b  = b - 'a' + 10;
4075             else if (b >= 'A' && b <= 'F') b  = b - 'A' + 10;
4076
4077             *data++ = (char)((a << 4) | b);
4078         } else {
4079             *data++ = c;
4080         }
4081
4082         ++i;
4083         ++outlen;
4084     }
4085
4086     if (outlen != len)
4087         ba->truncate(outlen);
4088 }
4089
4090 void q_fromPercentEncoding(QByteArray *ba)
4091 {
4092     q_fromPercentEncoding(ba, '%');
4093 }
4094
4095 /*!
4096     \since 4.4
4097
4098     Returns a decoded copy of the URI/URL-style percent-encoded \a input.
4099     The \a percent parameter allows you to replace the '%' character for
4100     another (for instance, '_' or '=').
4101
4102     For example:
4103     \code
4104         QByteArray text = QByteArray::fromPercentEncoding("Qt%20is%20great%33");
4105         text.data();            // returns "Qt is great!"
4106     \endcode
4107
4108     \sa toPercentEncoding(), QUrl::fromPercentEncoding()
4109 */
4110 QByteArray QByteArray::fromPercentEncoding(const QByteArray &input, char percent)
4111 {
4112     if (input.isNull())
4113         return QByteArray();       // preserve null
4114     if (input.isEmpty())
4115         return QByteArray(input.data(), 0);
4116
4117     QByteArray tmp = input;
4118     q_fromPercentEncoding(&tmp, percent);
4119     return tmp;
4120 }
4121
4122 static inline bool q_strchr(const char str[], char chr)
4123 {
4124     if (!str) return false;
4125
4126     const char *ptr = str;
4127     char c;
4128     while ((c = *ptr++))
4129         if (c == chr)
4130             return true;
4131     return false;
4132 }
4133
4134 static inline char toHexHelper(char c)
4135 {
4136     static const char hexnumbers[] = "0123456789ABCDEF";
4137     return hexnumbers[c & 0xf];
4138 }
4139
4140 static void q_toPercentEncoding(QByteArray *ba, const char *dontEncode, const char *alsoEncode, char percent)
4141 {
4142     if (ba->isEmpty())
4143         return;
4144
4145     QByteArray input = *ba;
4146     int len = input.count();
4147     const char *inputData = input.constData();
4148     char *output = 0;
4149     int length = 0;
4150
4151     for (int i = 0; i < len; ++i) {
4152         unsigned char c = *inputData++;
4153         if (((c >= 0x61 && c <= 0x7A) // ALPHA
4154              || (c >= 0x41 && c <= 0x5A) // ALPHA
4155              || (c >= 0x30 && c <= 0x39) // DIGIT
4156              || c == 0x2D // -
4157              || c == 0x2E // .
4158              || c == 0x5F // _
4159              || c == 0x7E // ~
4160              || q_strchr(dontEncode, c))
4161             && !q_strchr(alsoEncode, c)) {
4162             if (output)
4163                 output[length] = c;
4164             ++length;
4165         } else {
4166             if (!output) {
4167                 // detach now
4168                 ba->resize(len*3); // worst case
4169                 output = ba->data();
4170             }
4171             output[length++] = percent;
4172             output[length++] = toHexHelper((c & 0xf0) >> 4);
4173             output[length++] = toHexHelper(c & 0xf);
4174         }
4175     }
4176     if (output)
4177         ba->truncate(length);
4178 }
4179
4180 void q_toPercentEncoding(QByteArray *ba, const char *exclude, const char *include)
4181 {
4182     q_toPercentEncoding(ba, exclude, include, '%');
4183 }
4184
4185 void q_normalizePercentEncoding(QByteArray *ba, const char *exclude)
4186 {
4187     q_fromPercentEncoding(ba, '%');
4188     q_toPercentEncoding(ba, exclude, 0, '%');
4189 }
4190
4191 /*!
4192     \since 4.4
4193
4194     Returns a URI/URL-style percent-encoded copy of this byte array. The
4195     \a percent parameter allows you to override the default '%'
4196     character for another.
4197
4198     By default, this function will encode all characters that are not
4199     one of the following:
4200
4201         ALPHA ("a" to "z" and "A" to "Z") / DIGIT (0 to 9) / "-" / "." / "_" / "~"
4202
4203     To prevent characters from being encoded pass them to \a
4204     exclude. To force characters to be encoded pass them to \a
4205     include. The \a percent character is always encoded.
4206
4207     Example:
4208
4209     \code
4210          QByteArray text = "{a fishy string?}";
4211          QByteArray ba = text.toPercentEncoding("{}", "s");
4212          qDebug(ba.constData());
4213          // prints "{a fi%73hy %73tring%3F}"
4214     \endcode
4215
4216     The hex encoding uses the numbers 0-9 and the uppercase letters A-F.
4217
4218     \sa fromPercentEncoding(), QUrl::toPercentEncoding()
4219 */
4220 QByteArray QByteArray::toPercentEncoding(const QByteArray &exclude, const QByteArray &include,
4221                                          char percent) const
4222 {
4223     if (isNull())
4224         return QByteArray();    // preserve null
4225     if (isEmpty())
4226         return QByteArray(data(), 0);
4227
4228     QByteArray include2 = include;
4229     if (percent != '%')                        // the default
4230         if ((percent >= 0x61 && percent <= 0x7A) // ALPHA
4231             || (percent >= 0x41 && percent <= 0x5A) // ALPHA
4232             || (percent >= 0x30 && percent <= 0x39) // DIGIT
4233             || percent == 0x2D // -
4234             || percent == 0x2E // .
4235             || percent == 0x5F // _
4236             || percent == 0x7E) // ~
4237         include2 += percent;
4238
4239     QByteArray result = *this;
4240     q_toPercentEncoding(&result, exclude.nulTerminated().constData(), include2.nulTerminated().constData(), percent);
4241
4242     return result;
4243 }
4244
4245 /*! \typedef QByteArray::ConstIterator
4246     \internal
4247 */
4248
4249 /*! \typedef QByteArray::Iterator
4250     \internal
4251 */
4252
4253 /*! \typedef QByteArray::const_iterator
4254     \internal
4255 */
4256
4257 /*! \typedef QByteArray::iterator
4258     \internal
4259 */
4260
4261 /*! \typedef QByteArray::const_reference
4262     \internal
4263 */
4264
4265 /*! \typedef QByteArray::reference
4266     \internal
4267 */
4268
4269 /*! \typedef QByteArray::value_type
4270   \internal
4271  */
4272
4273 /*!
4274     \fn DataPtr &QByteArray::data_ptr()
4275     \internal
4276 */
4277
4278 /*!
4279     \typedef QByteArray::DataPtr
4280     \internal
4281 */
4282
4283 QT_END_NAMESPACE