Remove constructors taking implicit string sizes
[profile/ivi/qtbase.git] / src / corelib / tools / qbytearray.cpp
1 /****************************************************************************
2 **
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
5 **
6 ** This file is part of the QtCore module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
16 **
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
20 **
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
28 **
29 ** Other Usage
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** conditions contained in a signed written agreement between you and Nokia.
32 **
33 **
34 **
35 **
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41
42 #include "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 *>(::realloc(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 *>(::realloc(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.initializeOwned();
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 QStaticByteArrayData<1> QByteArray::shared_null = { { Q_REFCOUNT_INITIALIZE_STATIC,
618                                                            0, 0, 0, { 0 } }, { 0 } };
619 const QStaticByteArrayData<1> QByteArray::shared_empty = { { Q_REFCOUNT_INITIALIZE_STATIC,
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         free(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.isShared() || 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          free(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 bool 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 bool 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 bool 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 /*!
1291     Constructs a byte array containing the first \a size bytes of
1292     array \a data.
1293
1294     If \a data is 0, a null byte array is constructed.
1295
1296     If \a size is negative, \a data is assumed to point to a nul-terminated
1297     string and its length is determined dynamically. The terminating
1298     nul-character is not considered part of the byte array.
1299
1300     QByteArray makes a deep copy of the string data.
1301
1302     \sa fromRawData()
1303 */
1304
1305 QByteArray::QByteArray(const char *data, int size)
1306 {
1307     if (!data) {
1308         d = const_cast<Data *>(&shared_null.ba);
1309     } else {
1310         if (size < 0)
1311             size = strlen(data);
1312         if (!size) {
1313             d = const_cast<Data *>(&shared_empty.ba);
1314         } else {
1315             d = static_cast<Data *>(malloc(sizeof(Data) + size + 1));
1316             Q_CHECK_PTR(d);
1317             d->ref.initializeOwned();
1318             d->size = size;
1319             d->alloc = size;
1320             d->capacityReserved = false;
1321             d->offset = 0;
1322             memcpy(d->data(), data, size);
1323             d->data()[size] = '\0';
1324         }
1325     }
1326 }
1327
1328 /*!
1329     Constructs a byte array of size \a size with every byte set to
1330     character \a ch.
1331
1332     \sa fill()
1333 */
1334
1335 QByteArray::QByteArray(int size, char ch)
1336 {
1337     if (size <= 0) {
1338         d = const_cast<Data *>(&shared_null.ba);
1339     } else {
1340         d = static_cast<Data *>(malloc(sizeof(Data) + size + 1));
1341         Q_CHECK_PTR(d);
1342         d->ref.initializeOwned();
1343         d->size = size;
1344         d->alloc = size;
1345         d->capacityReserved = false;
1346         d->offset = 0;
1347         memset(d->data(), ch, size);
1348         d->data()[size] = '\0';
1349     }
1350 }
1351
1352 /*!
1353     \internal 
1354
1355     Constructs a byte array of size \a size with uninitialized contents.
1356 */
1357
1358 QByteArray::QByteArray(int size, Qt::Initialization)
1359 {
1360     d = static_cast<Data *>(malloc(sizeof(Data) + size + 1));
1361     Q_CHECK_PTR(d);
1362     d->ref.initializeOwned();
1363     d->size = size;
1364     d->alloc = size;
1365     d->capacityReserved = false;
1366     d->offset = 0;
1367     d->data()[size] = '\0';
1368 }
1369
1370 /*!
1371     Sets the size of the byte array to \a size bytes.
1372
1373     If \a size is greater than the current size, the byte array is
1374     extended to make it \a size bytes with the extra bytes added to
1375     the end. The new bytes are uninitialized.
1376
1377     If \a size is less than the current size, bytes are removed from
1378     the end.
1379
1380     \sa size(), truncate()
1381 */
1382
1383 void QByteArray::resize(int size)
1384 {
1385     if (size < 0)
1386         size = 0;
1387
1388     if (d->offset && !d->ref.isShared() && size < d->size) {
1389         d->size = size;
1390         return;
1391     }
1392
1393     if (size == 0 && !d->capacityReserved) {
1394         Data *x = const_cast<Data *>(&shared_empty.ba);
1395         if (!d->ref.deref())
1396             free(d);
1397         d = x;
1398     } else if (d == &shared_null.ba || d == &shared_empty.ba) {
1399         //
1400         // Optimize the idiom:
1401         //    QByteArray a;
1402         //    a.resize(sz);
1403         //    ...
1404         // which is used in place of the Qt 3 idiom:
1405         //    QByteArray a(sz);
1406         //
1407         Data *x = static_cast<Data *>(malloc(sizeof(Data) + size + 1));
1408         Q_CHECK_PTR(x);
1409         x->ref.initializeOwned();
1410         x->size = size;
1411         x->alloc = size;
1412         x->capacityReserved = false;
1413         x->offset = 0;
1414         x->data()[size] = '\0';
1415         d = x;
1416     } else {
1417         if (d->ref.isShared() || size > int(d->alloc)
1418             || (!d->capacityReserved && size < d->size && size < int(d->alloc) >> 1))
1419             realloc(qAllocMore(size, sizeof(Data)));
1420         if (int(d->alloc) >= size) {
1421             d->size = size;
1422             d->data()[size] = '\0';
1423         }
1424     }
1425 }
1426
1427 /*!
1428     Sets every byte in the byte array to character \a ch. If \a size
1429     is different from -1 (the default), the byte array is resized to
1430     size \a size beforehand.
1431
1432     Example:
1433     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 14
1434
1435     \sa resize()
1436 */
1437
1438 QByteArray &QByteArray::fill(char ch, int size)
1439 {
1440     resize(size < 0 ? d->size : size);
1441     if (d->size)
1442         memset(d->data(), ch, d->size);
1443     return *this;
1444 }
1445
1446 void QByteArray::realloc(int alloc)
1447 {
1448     if (d->ref.isShared() || d->offset) {
1449         Data *x = static_cast<Data *>(malloc(sizeof(Data) + alloc + 1));
1450         Q_CHECK_PTR(x);
1451         x->ref.initializeOwned();
1452         x->size = qMin(alloc, d->size);
1453         x->alloc = alloc;
1454         x->capacityReserved = d->capacityReserved;
1455         x->offset = 0;
1456         ::memcpy(x->data(), d->data(), x->size);
1457         x->data()[x->size] = '\0';
1458         if (!d->ref.deref())
1459             free(d);
1460         d = x;
1461     } else {
1462         Data *x = static_cast<Data *>(::realloc(d, sizeof(Data) + alloc + 1));
1463         Q_CHECK_PTR(x);
1464         x->alloc = alloc;
1465         x->offset = 0;
1466         d = x;
1467     }
1468 }
1469
1470 void QByteArray::expand(int i)
1471 {
1472     resize(qMax(i + 1, d->size));
1473 }
1474
1475 /*!
1476    \internal
1477    Return a QByteArray that is sure to be NUL-terminated.
1478
1479    By default, all QByteArray have an extra NUL at the end,
1480    guaranteeing that assumption. However, if QByteArray::fromRawData
1481    is used, then the NUL is there only if the user put it there. We
1482    can't be sure.
1483 */
1484 QByteArray QByteArray::nulTerminated() const
1485 {
1486     // is this fromRawData?
1487     if (!d->offset)
1488         return *this;           // no, then we're sure we're zero terminated
1489
1490     QByteArray copy(*this);
1491     copy.detach();
1492     return copy;
1493 }
1494
1495 /*!
1496     Prepends the byte array \a ba to this byte array and returns a
1497     reference to this byte array.
1498
1499     Example:
1500     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 15
1501
1502     This is the same as insert(0, \a ba).
1503
1504     Note: QByteArray is an \l{implicitly shared} class. Consequently,
1505     if \e this is an empty QByteArray, then \e this will just share
1506     the data held in \a ba. In this case, no copying of data is done,
1507     taking \l{constant time}. If a shared instance is modified, it will
1508     be copied (copy-on-write), taking \l{linear time}.
1509
1510     If \e this is not an empty QByteArray, a deep copy of the data is
1511     performed, taking \l{linear time}.
1512
1513     \sa append(), insert()
1514 */
1515
1516 QByteArray &QByteArray::prepend(const QByteArray &ba)
1517 {
1518     if ((d == &shared_null.ba || d == &shared_empty.ba) && !IS_RAW_DATA(ba.d)) {
1519         *this = ba;
1520     } else if (ba.d != &shared_null.ba) {
1521         QByteArray tmp = *this;
1522         *this = ba;
1523         append(tmp);
1524     }
1525     return *this;
1526 }
1527
1528 /*!
1529     \overload
1530
1531     Prepends the string \a str to this byte array.
1532 */
1533
1534 QByteArray &QByteArray::prepend(const char *str)
1535 {
1536     return prepend(str, qstrlen(str));
1537 }
1538
1539 /*!
1540     \overload
1541     \since 4.6
1542
1543     Prepends \a len bytes of the string \a str to this byte array.
1544 */
1545
1546 QByteArray &QByteArray::prepend(const char *str, int len)
1547 {
1548     if (str) {
1549         if (d->ref.isShared() || d->size + len > int(d->alloc))
1550             realloc(qAllocMore(d->size + len, sizeof(Data)));
1551         memmove(d->data()+len, d->data(), d->size);
1552         memcpy(d->data(), str, len);
1553         d->size += len;
1554         d->data()[d->size] = '\0';
1555     }
1556     return *this;
1557 }
1558
1559 /*!
1560     \overload
1561
1562     Prepends the character \a ch to this byte array.
1563 */
1564
1565 QByteArray &QByteArray::prepend(char ch)
1566 {
1567     if (d->ref.isShared() || d->size + 1 > int(d->alloc))
1568         realloc(qAllocMore(d->size + 1, sizeof(Data)));
1569     memmove(d->data()+1, d->data(), d->size);
1570     d->data()[0] = ch;
1571     ++d->size;
1572     d->data()[d->size] = '\0';
1573     return *this;
1574 }
1575
1576 /*!
1577     Appends the byte array \a ba onto the end of this byte array.
1578
1579     Example:
1580     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 16
1581
1582     This is the same as insert(size(), \a ba).
1583
1584     Note: QByteArray is an \l{implicitly shared} class. Consequently,
1585     if \e this is an empty QByteArray, then \e this will just share
1586     the data held in \a ba. In this case, no copying of data is done,
1587     taking \l{constant time}. If a shared instance is modified, it will
1588     be copied (copy-on-write), taking \l{linear time}.
1589
1590     If \e this is not an empty QByteArray, a deep copy of the data is
1591     performed, taking \l{linear time}.
1592
1593     This operation typically does not suffer from allocation overhead,
1594     because QByteArray preallocates extra space at the end of the data
1595     so that it may grow without reallocating for each append operation.
1596
1597     \sa operator+=(), prepend(), insert()
1598 */
1599
1600 QByteArray &QByteArray::append(const QByteArray &ba)
1601 {
1602     if ((d == &shared_null.ba || d == &shared_empty.ba) && !IS_RAW_DATA(ba.d)) {
1603         *this = ba;
1604     } else if (ba.d != &shared_null.ba) {
1605         if (d->ref.isShared() || d->size + ba.d->size > int(d->alloc))
1606             realloc(qAllocMore(d->size + ba.d->size, sizeof(Data)));
1607         memcpy(d->data() + d->size, ba.d->data(), ba.d->size);
1608         d->size += ba.d->size;
1609         d->data()[d->size] = '\0';
1610     }
1611     return *this;
1612 }
1613
1614 /*! \fn QByteArray &QByteArray::append(const QString &str)
1615
1616     \overload
1617
1618     Appends the string \a str to this byte array. The Unicode data is
1619     converted into 8-bit characters using QString::toAscii().
1620
1621     If the QString contains non-ASCII Unicode characters, using this
1622     function can lead to loss of information. You can disable this
1623     function by defining \c QT_NO_CAST_TO_ASCII when you compile your
1624     applications. You then need to call QString::toAscii() (or
1625     QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
1626     explicitly if you want to convert the data to \c{const char *}.
1627 */
1628
1629 /*!
1630     \overload
1631
1632     Appends the string \a str to this byte array.
1633 */
1634
1635 QByteArray& QByteArray::append(const char *str)
1636 {
1637     if (str) {
1638         int len = qstrlen(str);
1639         if (d->ref.isShared() || d->size + len > int(d->alloc))
1640             realloc(qAllocMore(d->size + len, sizeof(Data)));
1641         memcpy(d->data() + d->size, str, len + 1); // include null terminator
1642         d->size += len;
1643     }
1644     return *this;
1645 }
1646
1647 /*!
1648     \overload append()
1649
1650     Appends the first \a len characters of the string \a str to this byte
1651     array and returns a reference to this byte array.
1652
1653     If \a len is negative, the length of the string will be determined
1654     automatically using qstrlen(). If \a len is zero or \a str is
1655     null, nothing is appended to the byte array. Ensure that \a len is
1656     \e not longer than \a str.
1657 */
1658
1659 QByteArray &QByteArray::append(const char *str, int len)
1660 {
1661     if (len < 0)
1662         len = qstrlen(str);
1663     if (str && len) {
1664         if (d->ref.isShared() || d->size + len > int(d->alloc))
1665             realloc(qAllocMore(d->size + len, sizeof(Data)));
1666         memcpy(d->data() + d->size, str, len); // include null terminator
1667         d->size += len;
1668         d->data()[d->size] = '\0';
1669     }
1670     return *this;
1671 }
1672
1673 /*!
1674     \overload
1675
1676     Appends the character \a ch to this byte array.
1677 */
1678
1679 QByteArray& QByteArray::append(char ch)
1680 {
1681     if (d->ref.isShared() || d->size + 1 > int(d->alloc))
1682         realloc(qAllocMore(d->size + 1, sizeof(Data)));
1683     d->data()[d->size++] = ch;
1684     d->data()[d->size] = '\0';
1685     return *this;
1686 }
1687
1688 /*!
1689   \internal
1690   Inserts \a len bytes from the array \a arr at position \a pos and returns a
1691   reference the modified byte array.
1692 */
1693 static inline QByteArray &qbytearray_insert(QByteArray *ba,
1694                                             int pos, const char *arr, int len)
1695 {
1696     Q_ASSERT(pos >= 0);
1697
1698     if (pos < 0 || len <= 0 || arr == 0)
1699         return *ba;
1700
1701     int oldsize = ba->size();
1702     ba->resize(qMax(pos, oldsize) + len);
1703     char *dst = ba->data();
1704     if (pos > oldsize)
1705         ::memset(dst + oldsize, 0x20, pos - oldsize);
1706     else
1707         ::memmove(dst + pos + len, dst + pos, oldsize - pos);
1708     memcpy(dst + pos, arr, len);
1709     return *ba;
1710 }
1711
1712 /*!
1713     Inserts the byte array \a ba at index position \a i and returns a
1714     reference to this byte array.
1715
1716     Example:
1717     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 17
1718
1719     \sa append(), prepend(), replace(), remove()
1720 */
1721
1722 QByteArray &QByteArray::insert(int i, const QByteArray &ba)
1723 {
1724     QByteArray copy(ba);
1725     return qbytearray_insert(this, i, copy.d->data(), copy.d->size);
1726 }
1727
1728 /*!
1729     \fn QByteArray &QByteArray::insert(int i, const QString &str)
1730
1731     \overload
1732
1733     Inserts the string \a str at index position \a i in the byte
1734     array. The Unicode data is converted into 8-bit characters using
1735     QString::toAscii().
1736
1737     If \a i is greater than size(), the array is first extended using
1738     resize().
1739
1740     If the QString contains non-ASCII Unicode characters, using this
1741     function can lead to loss of information. You can disable this
1742     function by defining \c QT_NO_CAST_TO_ASCII when you compile your
1743     applications. You then need to call QString::toAscii() (or
1744     QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
1745     explicitly if you want to convert the data to \c{const char *}.
1746 */
1747
1748 /*!
1749     \overload
1750
1751     Inserts the string \a str at position \a i in the byte array.
1752
1753     If \a i is greater than size(), the array is first extended using
1754     resize().
1755 */
1756
1757 QByteArray &QByteArray::insert(int i, const char *str)
1758 {
1759     return qbytearray_insert(this, i, str, qstrlen(str));
1760 }
1761
1762 /*!
1763     \overload
1764     \since 4.6
1765
1766     Inserts \a len bytes of the string \a str at position
1767     \a i in the byte array.
1768
1769     If \a i is greater than size(), the array is first extended using
1770     resize().
1771 */
1772
1773 QByteArray &QByteArray::insert(int i, const char *str, int len)
1774 {
1775     return qbytearray_insert(this, i, str, len);
1776 }
1777
1778 /*!
1779     \overload
1780
1781     Inserts character \a ch at index position \a i in the byte array.
1782     If \a i is greater than size(), the array is first extended using
1783     resize().
1784 */
1785
1786 QByteArray &QByteArray::insert(int i, char ch)
1787 {
1788     return qbytearray_insert(this, i, &ch, 1);
1789 }
1790
1791 /*!
1792     Removes \a len bytes from the array, starting at index position \a
1793     pos, and returns a reference to the array.
1794
1795     If \a pos is out of range, nothing happens. If \a pos is valid,
1796     but \a pos + \a len is larger than the size of the array, the
1797     array is truncated at position \a pos.
1798
1799     Example:
1800     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 18
1801
1802     \sa insert(), replace()
1803 */
1804
1805 QByteArray &QByteArray::remove(int pos, int len)
1806 {
1807     if (len <= 0  || pos >= d->size || pos < 0)
1808         return *this;
1809     detach();
1810     if (pos + len >= d->size) {
1811         resize(pos);
1812     } else {
1813         memmove(d->data() + pos, d->data() + pos + len, d->size - pos - len);
1814         resize(d->size - len);
1815     }
1816     return *this;
1817 }
1818
1819 /*!
1820     Replaces \a len bytes from index position \a pos with the byte
1821     array \a after, and returns a reference to this byte array.
1822
1823     Example:
1824     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 19
1825
1826     \sa insert(), remove()
1827 */
1828
1829 QByteArray &QByteArray::replace(int pos, int len, const QByteArray &after)
1830 {
1831     if (len == after.d->size && (pos + len <= d->size)) {
1832         detach();
1833         memmove(d->data() + pos, after.d->data(), len*sizeof(char));
1834         return *this;
1835     } else {
1836         QByteArray copy(after);
1837         // ### optimize me
1838         remove(pos, len);
1839         return insert(pos, copy);
1840     }
1841 }
1842
1843 /*! \fn QByteArray &QByteArray::replace(int pos, int len, const char *after)
1844
1845     \overload
1846
1847     Replaces \a len bytes from index position \a pos with the zero terminated
1848     string \a after.
1849
1850     Notice: this can change the length of the byte array.
1851 */
1852 QByteArray &QByteArray::replace(int pos, int len, const char *after)
1853 {
1854     return replace(pos,len,after,qstrlen(after));
1855 }
1856
1857 /*! \fn QByteArray &QByteArray::replace(int pos, int len, const char *after, int alen)
1858
1859     \overload
1860
1861     Replaces \a len bytes from index position \a pos with \a alen bytes
1862     from the string \a after. \a after is allowed to have '\0' characters.
1863
1864     \since 4.7
1865 */
1866 QByteArray &QByteArray::replace(int pos, int len, const char *after, int alen)
1867 {
1868     if (len == alen && (pos + len <= d->size)) {
1869         detach();
1870         memcpy(d->data() + pos, after, len*sizeof(char));
1871         return *this;
1872     } else {
1873         remove(pos, len);
1874         return qbytearray_insert(this, pos, after, alen);
1875     }
1876 }
1877
1878 // ### optimize all other replace method, by offering
1879 // QByteArray::replace(const char *before, int blen, const char *after, int alen)
1880
1881 /*!
1882     \overload
1883
1884     Replaces every occurrence of the byte array \a before with the
1885     byte array \a after.
1886
1887     Example:
1888     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 20
1889 */
1890
1891 QByteArray &QByteArray::replace(const QByteArray &before, const QByteArray &after)
1892 {
1893     if (isNull() || before.d == after.d)
1894         return *this;
1895
1896     QByteArray aft = after;
1897     if (after.d == d)
1898         aft.detach();
1899     
1900     return replace(before.constData(), before.size(), aft.constData(), aft.size());
1901 }
1902
1903 /*!
1904     \fn QByteArray &QByteArray::replace(const char *before, const QByteArray &after)
1905     \overload
1906
1907     Replaces every occurrence of the string \a before with the
1908     byte array \a after.
1909 */
1910
1911 QByteArray &QByteArray::replace(const char *c, const QByteArray &after)
1912 {
1913     QByteArray aft = after;
1914     if (after.d == d)
1915         aft.detach();
1916     
1917     return replace(c, qstrlen(c), aft.constData(), aft.size());
1918 }
1919
1920 /*!
1921     \fn QByteArray &QByteArray::replace(const char *before, int bsize, const char *after, int asize)
1922     \overload
1923
1924     Replaces every occurrence of the string \a before with the string \a after.
1925     Since the sizes of the strings are given by \a bsize and \a asize, they
1926     may contain zero characters and do not need to be zero-terminated.
1927 */
1928
1929 QByteArray &QByteArray::replace(const char *before, int bsize, const char *after, int asize)
1930 {
1931     if (isNull() || (before == after && bsize == asize))
1932         return *this;
1933
1934     // protect against before or after being part of this
1935     const char *a = after;
1936     const char *b = before;
1937     if (after >= d->data() && after < d->data() + d->size) {
1938         char *copy = (char *)malloc(asize);
1939         Q_CHECK_PTR(copy);
1940         memcpy(copy, after, asize);
1941         a = copy;
1942     }
1943     if (before >= d->data() && before < d->data() + d->size) {
1944         char *copy = (char *)malloc(bsize);
1945         Q_CHECK_PTR(copy);
1946         memcpy(copy, before, bsize);
1947         b = copy;
1948     }
1949     
1950     QByteArrayMatcher matcher(before, bsize);
1951     int index = 0;
1952     int len = d->size;
1953     char *d = data();
1954
1955     if (bsize == asize) {
1956         if (bsize) {
1957             while ((index = matcher.indexIn(*this, index)) != -1) {
1958                 memcpy(d + index, after, asize);
1959                 index += bsize;
1960             }
1961         }
1962     } else if (asize < bsize) {
1963         uint to = 0;
1964         uint movestart = 0;
1965         uint num = 0;
1966         while ((index = matcher.indexIn(*this, index)) != -1) {
1967             if (num) {
1968                 int msize = index - movestart;
1969                 if (msize > 0) {
1970                     memmove(d + to, d + movestart, msize);
1971                     to += msize;
1972                 }
1973             } else {
1974                 to = index;
1975             }
1976             if (asize) {
1977                 memcpy(d + to, after, asize);
1978                 to += asize;
1979             }
1980             index += bsize;
1981             movestart = index;
1982             num++;
1983         }
1984         if (num) {
1985             int msize = len - movestart;
1986             if (msize > 0)
1987                 memmove(d + to, d + movestart, msize);
1988             resize(len - num*(bsize-asize));
1989         }
1990     } else {
1991         // the most complex case. We don't want to lose performance by doing repeated
1992         // copies and reallocs of the string.
1993         while (index != -1) {
1994             uint indices[4096];
1995             uint pos = 0;
1996             while(pos < 4095) {
1997                 index = matcher.indexIn(*this, index);
1998                 if (index == -1)
1999                     break;
2000                 indices[pos++] = index;
2001                 index += bsize;
2002                 // avoid infinite loop
2003                 if (!bsize)
2004                     index++;
2005             }
2006             if (!pos)
2007                 break;
2008
2009             // we have a table of replacement positions, use them for fast replacing
2010             int adjust = pos*(asize-bsize);
2011             // index has to be adjusted in case we get back into the loop above.
2012             if (index != -1)
2013                 index += adjust;
2014             int newlen = len + adjust;
2015             int moveend = len;
2016             if (newlen > len) {
2017                 resize(newlen);
2018                 len = newlen;
2019             }
2020             d = this->d->data();
2021
2022             while(pos) {
2023                 pos--;
2024                 int movestart = indices[pos] + bsize;
2025                 int insertstart = indices[pos] + pos*(asize-bsize);
2026                 int moveto = insertstart + asize;
2027                 memmove(d + moveto, d + movestart, (moveend - movestart));
2028                 if (asize)
2029                     memcpy(d + insertstart, after, asize);
2030                 moveend = movestart - bsize;
2031             }
2032         }
2033     }
2034
2035     if (a != after)
2036         ::free((char *)a);
2037     if (b != before)
2038         ::free((char *)b);
2039     
2040     
2041     return *this;
2042 }
2043
2044
2045 /*!
2046     \fn QByteArray &QByteArray::replace(const QByteArray &before, const char *after)
2047     \overload
2048
2049     Replaces every occurrence of the byte array \a before with the
2050     string \a after.
2051 */
2052
2053 /*! \fn QByteArray &QByteArray::replace(const QString &before, const QByteArray &after)
2054
2055     \overload
2056
2057     Replaces every occurrence of the string \a before with the byte
2058     array \a after. The Unicode data is converted into 8-bit
2059     characters using QString::toAscii().
2060
2061     If the QString contains non-ASCII Unicode characters, using this
2062     function can lead to loss of information. You can disable this
2063     function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2064     applications. You then need to call QString::toAscii() (or
2065     QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2066     explicitly if you want to convert the data to \c{const char *}.
2067 */
2068
2069 /*! \fn QByteArray &QByteArray::replace(const QString &before, const char *after)
2070     \overload
2071
2072     Replaces every occurrence of the string \a before with the string
2073     \a after.
2074 */
2075
2076 /*! \fn QByteArray &QByteArray::replace(const char *before, const char *after)
2077
2078     \overload
2079
2080     Replaces every occurrence of the string \a before with the string
2081     \a after.
2082 */
2083
2084 /*!
2085     \overload
2086
2087     Replaces every occurrence of the character \a before with the
2088     byte array \a after.
2089 */
2090
2091 QByteArray &QByteArray::replace(char before, const QByteArray &after)
2092 {
2093     char b[2] = { before, '\0' };
2094     QByteArray cb = fromRawData(b, 1);
2095     return replace(cb, after);
2096 }
2097
2098 /*! \fn QByteArray &QByteArray::replace(char before, const QString &after)
2099
2100     \overload
2101
2102     Replaces every occurrence of the character \a before with the
2103     string \a after. The Unicode data is converted into 8-bit
2104     characters using QString::toAscii().
2105
2106     If the QString contains non-ASCII Unicode characters, using this
2107     function can lead to loss of information. You can disable this
2108     function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2109     applications. You then need to call QString::toAscii() (or
2110     QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2111     explicitly if you want to convert the data to \c{const char *}.
2112 */
2113
2114 /*! \fn QByteArray &QByteArray::replace(char before, const char *after)
2115
2116     \overload
2117
2118     Replaces every occurrence of the character \a before with the
2119     string \a after.
2120 */
2121
2122 /*!
2123     \overload
2124
2125     Replaces every occurrence of the character \a before with the
2126     character \a after.
2127 */
2128
2129 QByteArray &QByteArray::replace(char before, char after)
2130 {
2131     if (d->size) {
2132         char *i = data();
2133         char *e = i + d->size;
2134         for (; i != e; ++i)
2135             if (*i == before)
2136                 * i = after;
2137     }
2138     return *this;
2139 }
2140
2141 /*!
2142     Splits the byte array into subarrays wherever \a sep occurs, and
2143     returns the list of those arrays. If \a sep does not match
2144     anywhere in the byte array, split() returns a single-element list
2145     containing this byte array.
2146 */
2147
2148 QList<QByteArray> QByteArray::split(char sep) const
2149 {
2150     QList<QByteArray> list;
2151     int start = 0;
2152     int end;
2153     while ((end = indexOf(sep, start)) != -1) {
2154         list.append(mid(start, end - start));
2155         start = end + 1;
2156     }
2157     list.append(mid(start));
2158     return list;
2159 }
2160
2161 /*!
2162     \since 4.5
2163
2164     Returns a copy of this byte array repeated the specified number of \a times.
2165
2166     If \a times is less than 1, an empty byte array is returned.
2167
2168     Example:
2169
2170     \code
2171         QByteArray ba("ab");
2172         ba.repeated(4);             // returns "abababab"
2173     \endcode
2174 */
2175 QByteArray QByteArray::repeated(int times) const
2176 {
2177     if (d->size == 0)
2178         return *this;
2179
2180     if (times <= 1) {
2181         if (times == 1)
2182             return *this;
2183         return QByteArray();
2184     }
2185
2186     const int resultSize = times * d->size;
2187
2188     QByteArray result;
2189     result.reserve(resultSize);
2190     if (int(result.d->alloc) != resultSize)
2191         return QByteArray(); // not enough memory
2192
2193     memcpy(result.d->data(), d->data(), d->size);
2194
2195     int sizeSoFar = d->size;
2196     char *end = result.d->data() + sizeSoFar;
2197
2198     const int halfResultSize = resultSize >> 1;
2199     while (sizeSoFar <= halfResultSize) {
2200         memcpy(end, result.d->data(), sizeSoFar);
2201         end += sizeSoFar;
2202         sizeSoFar <<= 1;
2203     }
2204     memcpy(end, result.d->data(), resultSize - sizeSoFar);
2205     result.d->data()[resultSize] = '\0';
2206     result.d->size = resultSize;
2207     return result;
2208 }
2209
2210 #define REHASH(a) \
2211     if (ol_minus_1 < sizeof(uint) * CHAR_BIT) \
2212         hashHaystack -= (a) << ol_minus_1; \
2213     hashHaystack <<= 1
2214
2215 /*!
2216     Returns the index position of the first occurrence of the byte
2217     array \a ba in this byte array, searching forward from index
2218     position \a from. Returns -1 if \a ba could not be found.
2219
2220     Example:
2221     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 21
2222
2223     \sa lastIndexOf(), contains(), count()
2224 */
2225
2226 int QByteArray::indexOf(const QByteArray &ba, int from) const
2227 {
2228     const int ol = ba.d->size;
2229     if (ol == 0)
2230         return from;
2231     if (ol == 1)
2232         return indexOf(*ba.d->data(), from);
2233
2234     const int l = d->size;
2235     if (from > d->size || ol + from > l)
2236         return -1;
2237
2238     return qFindByteArray(d->data(), d->size, from, ba.d->data(), ol);
2239 }
2240
2241 /*! \fn int QByteArray::indexOf(const QString &str, int from) const
2242
2243     \overload
2244
2245     Returns the index position of the first occurrence of the string
2246     \a str in the byte array, searching forward from index position
2247     \a from. Returns -1 if \a str could not be found.
2248
2249     The Unicode data is converted into 8-bit characters using
2250     QString::toAscii().
2251
2252     If the QString contains non-ASCII Unicode characters, using this
2253     function can lead to loss of information. You can disable this
2254     function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2255     applications. You then need to call QString::toAscii() (or
2256     QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2257     explicitly if you want to convert the data to \c{const char *}.
2258 */
2259
2260 /*! \fn int QByteArray::indexOf(const char *str, int from) const
2261
2262     \overload
2263
2264     Returns the index position of the first occurrence of the string
2265     \a str in the byte array, searching forward from index position \a
2266     from. Returns -1 if \a str could not be found.
2267 */
2268 int QByteArray::indexOf(const char *c, int from) const
2269 {
2270     const int ol = qstrlen(c);
2271     if (ol == 1)
2272         return indexOf(*c, from);
2273     
2274     const int l = d->size;
2275     if (from > d->size || ol + from > l)
2276         return -1;
2277     if (ol == 0)
2278         return from;
2279
2280     return qFindByteArray(d->data(), d->size, from, c, ol);
2281 }
2282
2283 /*!
2284     \overload
2285
2286     Returns the index position of the first occurrence of the
2287     character \a ch in the byte array, searching forward from index
2288     position \a from. Returns -1 if \a ch could not be found.
2289
2290     Example:
2291     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 22
2292
2293     \sa lastIndexOf(), contains()
2294 */
2295
2296 int QByteArray::indexOf(char ch, int from) const
2297 {
2298     if (from < 0)
2299         from = qMax(from + d->size, 0);
2300     if (from < d->size) {
2301         const char *n = d->data() + from - 1;
2302         const char *e = d->data() + d->size;
2303         while (++n != e)
2304         if (*n == ch)
2305             return  n - d->data();
2306     }
2307     return -1;
2308 }
2309
2310
2311 static int lastIndexOfHelper(const char *haystack, int l, const char *needle, int ol, int from)
2312 {
2313     int delta = l - ol;
2314     if (from < 0)
2315         from = delta;
2316     if (from < 0 || from > l)
2317         return -1;
2318     if (from > delta)
2319         from = delta;
2320
2321     const char *end = haystack;
2322     haystack += from;
2323     const uint ol_minus_1 = ol - 1;
2324     const char *n = needle + ol_minus_1;
2325     const char *h = haystack + ol_minus_1;
2326     uint hashNeedle = 0, hashHaystack = 0;
2327     int idx;
2328     for (idx = 0; idx < ol; ++idx) {
2329         hashNeedle = ((hashNeedle<<1) + *(n-idx));
2330         hashHaystack = ((hashHaystack<<1) + *(h-idx));
2331     }
2332     hashHaystack -= *haystack;
2333     while (haystack >= end) {
2334         hashHaystack += *haystack;
2335         if (hashHaystack == hashNeedle && memcmp(needle, haystack, ol) == 0)
2336             return haystack - end;
2337         --haystack;
2338         REHASH(*(haystack + ol));
2339     }
2340     return -1;
2341
2342 }
2343
2344 /*!
2345     \fn int QByteArray::lastIndexOf(const QByteArray &ba, int from) const
2346
2347     Returns the index position of the last occurrence of the byte
2348     array \a ba in this byte array, searching backward from index
2349     position \a from. If \a from is -1 (the default), the search
2350     starts at the last byte. Returns -1 if \a ba could not be found.
2351
2352     Example:
2353     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 23
2354
2355     \sa indexOf(), contains(), count()
2356 */
2357
2358 int QByteArray::lastIndexOf(const QByteArray &ba, int from) const
2359 {
2360     const int ol = ba.d->size;
2361     if (ol == 1)
2362         return lastIndexOf(*ba.d->data(), from);
2363
2364     return lastIndexOfHelper(d->data(), d->size, ba.d->data(), ol, from);
2365 }
2366
2367 /*! \fn int QByteArray::lastIndexOf(const QString &str, int from) const
2368
2369     \overload
2370
2371     Returns the index position of the last occurrence of the string \a
2372     str in the byte array, searching backward from index position \a
2373     from. If \a from is -1 (the default), the search starts at the
2374     last (size() - 1) byte. Returns -1 if \a str could not be found.
2375
2376     The Unicode data is converted into 8-bit characters using
2377     QString::toAscii().
2378
2379     If the QString contains non-ASCII Unicode characters, using this
2380     function can lead to loss of information. You can disable this
2381     function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2382     applications. You then need to call QString::toAscii() (or
2383     QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2384     explicitly if you want to convert the data to \c{const char *}.
2385 */
2386
2387 /*! \fn int QByteArray::lastIndexOf(const char *str, int from) const
2388     \overload
2389
2390     Returns the index position of the last occurrence of the string \a
2391     str in the byte array, searching backward from index position \a
2392     from. If \a from is -1 (the default), the search starts at the
2393     last (size() - 1) byte. Returns -1 if \a str could not be found.
2394 */
2395 int QByteArray::lastIndexOf(const char *str, int from) const
2396 {
2397     const int ol = qstrlen(str);
2398     if (ol == 1)
2399         return lastIndexOf(*str, from);
2400
2401     return lastIndexOfHelper(d->data(), d->size, str, ol, from);
2402 }
2403
2404 /*!
2405     \overload
2406
2407     Returns the index position of the last occurrence of character \a
2408     ch in the byte array, searching backward from index position \a
2409     from. If \a from is -1 (the default), the search starts at the
2410     last (size() - 1) byte. Returns -1 if \a ch could not be found.
2411
2412     Example:
2413     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 24
2414
2415     \sa indexOf(), contains()
2416 */
2417
2418 int QByteArray::lastIndexOf(char ch, int from) const
2419 {
2420     if (from < 0)
2421         from += d->size;
2422     else if (from > d->size)
2423         from = d->size-1;
2424     if (from >= 0) {
2425         const char *b = d->data();
2426         const char *n = d->data() + from + 1;
2427         while (n-- != b)
2428             if (*n == ch)
2429                 return  n - b;
2430     }
2431     return -1;
2432 }
2433
2434 /*!
2435     Returns the number of (potentially overlapping) occurrences of
2436     byte array \a ba in this byte array.
2437
2438     \sa contains(), indexOf()
2439 */
2440
2441 int QByteArray::count(const QByteArray &ba) const
2442 {
2443     int num = 0;
2444     int i = -1;
2445     if (d->size > 500 && ba.d->size > 5) {
2446         QByteArrayMatcher matcher(ba);
2447         while ((i = matcher.indexIn(*this, i + 1)) != -1)
2448             ++num;
2449     } else {
2450         while ((i = indexOf(ba, i + 1)) != -1)
2451             ++num;
2452     }
2453     return num;
2454 }
2455
2456 /*!
2457     \overload
2458
2459     Returns the number of (potentially overlapping) occurrences of
2460     string \a str in the byte array.
2461 */
2462
2463 int QByteArray::count(const char *str) const
2464 {
2465     return count(fromRawData(str, qstrlen(str)));
2466 }
2467
2468 /*!
2469     \overload
2470
2471     Returns the number of occurrences of character \a ch in the byte
2472     array.
2473
2474     \sa contains(), indexOf()
2475 */
2476
2477 int QByteArray::count(char ch) const
2478 {
2479     int num = 0;
2480     const char *i = d->data() + d->size;
2481     const char *b = d->data();
2482     while (i != b)
2483         if (*--i == ch)
2484             ++num;
2485     return num;
2486 }
2487
2488 /*! \fn int QByteArray::count() const
2489
2490     \overload
2491
2492     Same as size().
2493 */
2494
2495 /*!
2496     Returns true if this byte array starts with byte array \a ba;
2497     otherwise returns false.
2498
2499     Example:
2500     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 25
2501
2502     \sa endsWith(), left()
2503 */
2504 bool QByteArray::startsWith(const QByteArray &ba) const
2505 {
2506     if (d == ba.d || ba.d->size == 0)
2507         return true;
2508     if (d->size < ba.d->size)
2509         return false;
2510     return memcmp(d->data(), ba.d->data(), ba.d->size) == 0;
2511 }
2512
2513 /*! \overload
2514
2515     Returns true if this byte array starts with string \a str;
2516     otherwise returns false.
2517 */
2518 bool QByteArray::startsWith(const char *str) const
2519 {
2520     if (!str || !*str)
2521         return true;
2522     int len = qstrlen(str);
2523     if (d->size < len)
2524         return false;
2525     return qstrncmp(d->data(), str, len) == 0;
2526 }
2527
2528 /*! \overload
2529
2530     Returns true if this byte array starts with character \a ch;
2531     otherwise returns false.
2532 */
2533 bool QByteArray::startsWith(char ch) const
2534 {
2535     if (d->size == 0)
2536         return false;
2537     return d->data()[0] == ch;
2538 }
2539
2540 /*!
2541     Returns true if this byte array ends with byte array \a ba;
2542     otherwise returns false.
2543
2544     Example:
2545     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 26
2546
2547     \sa startsWith(), right()
2548 */
2549 bool QByteArray::endsWith(const QByteArray &ba) const
2550 {
2551     if (d == ba.d || ba.d->size == 0)
2552         return true;
2553     if (d->size < ba.d->size)
2554         return false;
2555     return memcmp(d->data() + d->size - ba.d->size, ba.d->data(), ba.d->size) == 0;
2556 }
2557
2558 /*! \overload
2559
2560     Returns true if this byte array ends with string \a str; otherwise
2561     returns false.
2562 */
2563 bool QByteArray::endsWith(const char *str) const
2564 {
2565     if (!str || !*str)
2566         return true;
2567     int len = qstrlen(str);
2568     if (d->size < len)
2569         return false;
2570     return qstrncmp(d->data() + d->size - len, str, len) == 0;
2571 }
2572
2573 /*! \overload
2574
2575     Returns true if this byte array ends with character \a ch;
2576     otherwise returns false.
2577 */
2578 bool QByteArray::endsWith(char ch) const
2579 {
2580     if (d->size == 0)
2581         return false;
2582     return d->data()[d->size - 1] == ch;
2583 }
2584
2585 /*!
2586     Returns a byte array that contains the leftmost \a len bytes of
2587     this byte array.
2588
2589     The entire byte array is returned if \a len is greater than
2590     size().
2591
2592     Example:
2593     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 27
2594
2595     \sa right(), mid(), startsWith(), truncate()
2596 */
2597
2598 QByteArray QByteArray::left(int len)  const
2599 {
2600     if (len >= d->size)
2601         return *this;
2602     if (len < 0)
2603         len = 0;
2604     return QByteArray(d->data(), len);
2605 }
2606
2607 /*!
2608     Returns a byte array that contains the rightmost \a len bytes of
2609     this byte array.
2610
2611     The entire byte array is returned if \a len is greater than
2612     size().
2613
2614     Example:
2615     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 28
2616
2617     \sa endsWith(), left(), mid()
2618 */
2619
2620 QByteArray QByteArray::right(int len) const
2621 {
2622     if (len >= d->size)
2623         return *this;
2624     if (len < 0)
2625         len = 0;
2626     return QByteArray(d->data() + d->size - len, len);
2627 }
2628
2629 /*!
2630     Returns a byte array containing \a len bytes from this byte array,
2631     starting at position \a pos.
2632
2633     If \a len is -1 (the default), or \a pos + \a len >= size(),
2634     returns a byte array containing all bytes starting at position \a
2635     pos until the end of the byte array.
2636
2637     Example:
2638     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 29
2639
2640     \sa left(), right()
2641 */
2642
2643 QByteArray QByteArray::mid(int pos, int len) const
2644 {
2645     if (d == &shared_null.ba || d == &shared_empty.ba || pos > d->size)
2646         return QByteArray();
2647     if (len < 0)
2648         len = d->size - pos;
2649     if (pos < 0) {
2650         len += pos;
2651         pos = 0;
2652     }
2653     if (len + pos > d->size)
2654         len = d->size - pos;
2655     if (pos == 0 && len == d->size)
2656         return *this;
2657     return QByteArray(d->data() + pos, len);
2658 }
2659
2660 /*!
2661     Returns a lowercase copy of the byte array. The bytearray is
2662     interpreted as a Latin-1 encoded string.
2663
2664     Example:
2665     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 30
2666
2667     \sa toUpper(), {8-bit Character Comparisons}
2668 */
2669 QByteArray QByteArray::toLower() const
2670 {
2671     QByteArray s(*this);
2672     register uchar *p = reinterpret_cast<uchar *>(s.data());
2673     if (p) {
2674         while (*p) {
2675             *p = QChar::toLower((ushort)*p);
2676             p++;
2677         }
2678     }
2679     return s;
2680 }
2681
2682 /*!
2683     Returns an uppercase copy of the byte array. The bytearray is
2684     interpreted as a Latin-1 encoded string.
2685
2686     Example:
2687     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 31
2688
2689     \sa toLower(), {8-bit Character Comparisons}
2690 */
2691
2692 QByteArray QByteArray::toUpper() const
2693 {
2694     QByteArray s(*this);
2695     register uchar *p = reinterpret_cast<uchar *>(s.data());
2696     if (p) {
2697         while (*p) {
2698             *p = QChar::toUpper((ushort)*p);
2699             p++;
2700         }
2701     }
2702     return s;
2703 }
2704
2705 /*! \fn void QByteArray::clear()
2706
2707     Clears the contents of the byte array and makes it empty.
2708
2709     \sa resize(), isEmpty()
2710 */
2711
2712 void QByteArray::clear()
2713 {
2714     if (!d->ref.deref())
2715         free(d);
2716     d = const_cast<Data *>(&shared_null.ba);
2717     d->ref.ref();
2718 }
2719
2720 #if !defined(QT_NO_DATASTREAM) || (defined(QT_BOOTSTRAPPED) && !defined(QT_BUILD_QMAKE))
2721
2722 /*! \relates QByteArray
2723
2724     Writes byte array \a ba to the stream \a out and returns a reference
2725     to the stream.
2726
2727     \sa {Serializing Qt Data Types}
2728 */
2729
2730 QDataStream &operator<<(QDataStream &out, const QByteArray &ba)
2731 {
2732     if (ba.isNull() && out.version() >= 6) {
2733         out << (quint32)0xffffffff;
2734         return out;
2735     }
2736     return out.writeBytes(ba, ba.size());
2737 }
2738
2739 /*! \relates QByteArray
2740
2741     Reads a byte array into \a ba from the stream \a in and returns a
2742     reference to the stream.
2743
2744     \sa {Serializing Qt Data Types}
2745 */
2746
2747 QDataStream &operator>>(QDataStream &in, QByteArray &ba)
2748 {
2749     ba.clear();
2750     quint32 len;
2751     in >> len;
2752     if (len == 0xffffffff)
2753         return in;
2754
2755     const quint32 Step = 1024 * 1024;
2756     quint32 allocated = 0;
2757
2758     do {
2759         int blockSize = qMin(Step, len - allocated);
2760         ba.resize(allocated + blockSize);
2761         if (in.readRawData(ba.data() + allocated, blockSize) != blockSize) {
2762             ba.clear();
2763             in.setStatus(QDataStream::ReadPastEnd);
2764             return in;
2765         }
2766         allocated += blockSize;
2767     } while (allocated < len);
2768
2769     return in;
2770 }
2771 #endif // QT_NO_DATASTREAM
2772
2773 /*! \fn bool QByteArray::operator==(const QString &str) const
2774
2775     Returns true if this byte array is equal to string \a str;
2776     otherwise returns false.
2777
2778     The Unicode data is converted into 8-bit characters using
2779     QString::toAscii().
2780
2781     The comparison is case sensitive.
2782
2783     You can disable this operator by defining \c
2784     QT_NO_CAST_FROM_ASCII when you compile your applications. You
2785     then need to call QString::fromAscii(), QString::fromLatin1(),
2786     QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2787     you want to convert the byte array to a QString before doing the
2788     comparison.
2789 */
2790
2791 /*! \fn bool QByteArray::operator!=(const QString &str) const
2792
2793     Returns true if this byte array is not 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 lexically less than string \a
2812     str; 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 greater than string
2830     \a 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 less than or equal
2848     to string \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 greater than or equal to string
2866     \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 operator==(const QByteArray &a1, const QByteArray &a2)
2882     \relates QByteArray
2883
2884     \overload
2885
2886     Returns true if byte array \a a1 is equal to byte array \a a2;
2887     otherwise returns false.
2888 */
2889
2890 /*! \fn bool operator==(const QByteArray &a1, const char *a2)
2891     \relates QByteArray
2892
2893     \overload
2894
2895     Returns true if byte array \a a1 is equal to string \a a2;
2896     otherwise returns false.
2897 */
2898
2899 /*! \fn bool operator==(const char *a1, const QByteArray &a2)
2900     \relates QByteArray
2901
2902     \overload
2903
2904     Returns true if string \a a1 is equal to byte array \a a2;
2905     otherwise returns false.
2906 */
2907
2908 /*! \fn bool operator!=(const QByteArray &a1, const QByteArray &a2)
2909     \relates QByteArray
2910
2911     \overload
2912
2913     Returns true if byte array \a a1 is not equal to byte array \a a2;
2914     otherwise returns false.
2915 */
2916
2917 /*! \fn bool operator!=(const QByteArray &a1, const char *a2)
2918     \relates QByteArray
2919
2920     \overload
2921
2922     Returns true if byte array \a a1 is not equal to string \a a2;
2923     otherwise returns false.
2924 */
2925
2926 /*! \fn bool operator!=(const char *a1, const QByteArray &a2)
2927     \relates QByteArray
2928
2929     \overload
2930
2931     Returns true if string \a a1 is not equal to byte array \a a2;
2932     otherwise returns false.
2933 */
2934
2935 /*! \fn bool operator<(const QByteArray &a1, const QByteArray &a2)
2936     \relates QByteArray
2937
2938     \overload
2939
2940     Returns true if byte array \a a1 is lexically less than byte array
2941     \a a2; otherwise returns false.
2942 */
2943
2944 /*! \fn inline bool operator<(const QByteArray &a1, const char *a2)
2945     \relates QByteArray
2946
2947     \overload
2948
2949     Returns true if byte array \a a1 is lexically less than string
2950     \a a2; otherwise returns false.
2951 */
2952
2953 /*! \fn bool operator<(const char *a1, const QByteArray &a2)
2954     \relates QByteArray
2955
2956     \overload
2957
2958     Returns true if string \a a1 is lexically less than byte array
2959     \a a2; otherwise returns false.
2960 */
2961
2962 /*! \fn bool operator<=(const QByteArray &a1, const QByteArray &a2)
2963     \relates QByteArray
2964
2965     \overload
2966
2967     Returns true if byte array \a a1 is lexically less than or equal
2968     to byte array \a a2; otherwise returns false.
2969 */
2970
2971 /*! \fn bool operator<=(const QByteArray &a1, const char *a2)
2972     \relates QByteArray
2973
2974     \overload
2975
2976     Returns true if byte array \a a1 is lexically less than or equal
2977     to string \a a2; otherwise returns false.
2978 */
2979
2980 /*! \fn bool operator<=(const char *a1, const QByteArray &a2)
2981     \relates QByteArray
2982
2983     \overload
2984
2985     Returns true if string \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 QByteArray &a2)
2990     \relates QByteArray
2991
2992     \overload
2993
2994     Returns true if byte array \a a1 is lexically greater than byte
2995     array \a a2; otherwise returns false.
2996 */
2997
2998 /*! \fn bool operator>(const QByteArray &a1, const char *a2)
2999     \relates QByteArray
3000
3001     \overload
3002
3003     Returns true if byte array \a a1 is lexically greater than string
3004     \a a2; otherwise returns false.
3005 */
3006
3007 /*! \fn bool operator>(const char *a1, const QByteArray &a2)
3008     \relates QByteArray
3009
3010     \overload
3011
3012     Returns true if string \a a1 is lexically greater than byte array
3013     \a a2; otherwise returns false.
3014 */
3015
3016 /*! \fn bool operator>=(const QByteArray &a1, const QByteArray &a2)
3017     \relates QByteArray
3018
3019     \overload
3020
3021     Returns true if byte array \a a1 is lexically greater than or
3022     equal to byte array \a a2; otherwise returns false.
3023 */
3024
3025 /*! \fn bool operator>=(const QByteArray &a1, const char *a2)
3026     \relates QByteArray
3027
3028     \overload
3029
3030     Returns true if byte array \a a1 is lexically greater than or
3031     equal to string \a a2; otherwise returns false.
3032 */
3033
3034 /*! \fn bool operator>=(const char *a1, const QByteArray &a2)
3035     \relates QByteArray
3036
3037     \overload
3038
3039     Returns true if string \a a1 is lexically greater than or
3040     equal to byte array \a a2; otherwise returns false.
3041 */
3042
3043 /*! \fn const QByteArray operator+(const QByteArray &a1, const QByteArray &a2)
3044     \relates QByteArray
3045
3046     Returns a byte array that is the result of concatenating byte
3047     array \a a1 and byte array \a a2.
3048
3049     \sa QByteArray::operator+=()
3050 */
3051
3052 /*! \fn const QByteArray operator+(const QByteArray &a1, const char *a2)
3053     \relates QByteArray
3054
3055     \overload
3056
3057     Returns a byte array that is the result of concatenating byte
3058     array \a a1 and string \a a2.
3059 */
3060
3061 /*! \fn const QByteArray operator+(const QByteArray &a1, char a2)
3062     \relates QByteArray
3063
3064     \overload
3065
3066     Returns a byte array that is the result of concatenating byte
3067     array \a a1 and character \a a2.
3068 */
3069
3070 /*! \fn const QByteArray operator+(const char *a1, const QByteArray &a2)
3071     \relates QByteArray
3072
3073     \overload
3074
3075     Returns a byte array that is the result of concatenating string
3076     \a a1 and byte array \a a2.
3077 */
3078
3079 /*! \fn const QByteArray operator+(char a1, const QByteArray &a2)
3080     \relates QByteArray
3081
3082     \overload
3083
3084     Returns a byte array that is the result of concatenating character
3085     \a a1 and byte array \a a2.
3086 */
3087
3088 /*!
3089     Returns a byte array that has whitespace removed from the start
3090     and the end, and which has each sequence of internal whitespace
3091     replaced with a single space.
3092
3093     Whitespace means any character for which the standard C++
3094     isspace() function returns true. This includes the ASCII
3095     characters '\\t', '\\n', '\\v', '\\f', '\\r', and ' '.
3096
3097     Example:
3098     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 32
3099
3100     \sa trimmed()
3101 */
3102 QByteArray QByteArray::simplified() const
3103 {
3104     if (d->size == 0)
3105         return *this;
3106     QByteArray result(d->size, Qt::Uninitialized);
3107     const char *from = d->data();
3108     const char *fromend = from + d->size;
3109     int outc=0;
3110     char *to = result.d->data();
3111     for (;;) {
3112         while (from!=fromend && isspace(uchar(*from)))
3113             from++;
3114         while (from!=fromend && !isspace(uchar(*from)))
3115             to[outc++] = *from++;
3116         if (from!=fromend)
3117             to[outc++] = ' ';
3118         else
3119             break;
3120     }
3121     if (outc > 0 && to[outc-1] == ' ')
3122         outc--;
3123     result.resize(outc);
3124     return result;
3125 }
3126
3127 /*!
3128     Returns a byte array that has whitespace removed from the start
3129     and the end.
3130
3131     Whitespace means any character for which the standard C++
3132     isspace() function returns true. This includes the ASCII
3133     characters '\\t', '\\n', '\\v', '\\f', '\\r', and ' '.
3134
3135     Example:
3136     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 33
3137
3138     Unlike simplified(), trimmed() leaves internal whitespace alone.
3139
3140     \sa simplified()
3141 */
3142 QByteArray QByteArray::trimmed() const
3143 {
3144     if (d->size == 0)
3145         return *this;
3146     const char *s = d->data();
3147     if (!isspace(uchar(*s)) && !isspace(uchar(s[d->size-1])))
3148         return *this;
3149     int start = 0;
3150     int end = d->size - 1;
3151     while (start<=end && isspace(uchar(s[start])))  // skip white space from start
3152         start++;
3153     if (start <= end) {                          // only white space
3154         while (end && isspace(uchar(s[end])))           // skip white space from end
3155             end--;
3156     }
3157     int l = end - start + 1;
3158     if (l <= 0) {
3159         return QByteArray(const_cast<Data *>(&shared_empty.ba), 0, 0);
3160     }
3161     return QByteArray(s+start, l);
3162 }
3163
3164 /*!
3165     Returns a byte array of size \a width that contains this byte
3166     array padded by the \a fill character.
3167
3168     If \a truncate is false and the size() of the byte array is more
3169     than \a width, then the returned byte array is a copy of this byte
3170     array.
3171
3172     If \a truncate is true and the size() of the byte array is more
3173     than \a width, then any bytes in a copy of the byte array
3174     after position \a width are removed, and the copy is returned.
3175
3176     Example:
3177     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 34
3178
3179     \sa rightJustified()
3180 */
3181
3182 QByteArray QByteArray::leftJustified(int width, char fill, bool truncate) const
3183 {
3184     QByteArray result;
3185     int len = d->size;
3186     int padlen = width - len;
3187     if (padlen > 0) {
3188         result.resize(len+padlen);
3189         if (len)
3190             memcpy(result.d->data(), d->data(), len);
3191         memset(result.d->data()+len, fill, padlen);
3192     } else {
3193         if (truncate)
3194             result = left(width);
3195         else
3196             result = *this;
3197     }
3198     return result;
3199 }
3200
3201 /*!
3202     Returns a byte array of size \a width that contains the \a fill
3203     character followed by this byte array.
3204
3205     If \a truncate is false and the size of the byte array is more
3206     than \a width, then the returned byte array is a copy of this byte
3207     array.
3208
3209     If \a truncate is true and the size of the byte array is more
3210     than \a width, then the resulting byte array is truncated at
3211     position \a width.
3212
3213     Example:
3214     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 35
3215
3216     \sa leftJustified()
3217 */
3218
3219 QByteArray QByteArray::rightJustified(int width, char fill, bool truncate) const
3220 {
3221     QByteArray result;
3222     int len = d->size;
3223     int padlen = width - len;
3224     if (padlen > 0) {
3225         result.resize(len+padlen);
3226         if (len)
3227             memcpy(result.d->data()+padlen, data(), len);
3228         memset(result.d->data(), fill, padlen);
3229     } else {
3230         if (truncate)
3231             result = left(width);
3232         else
3233             result = *this;
3234     }
3235     return result;
3236 }
3237
3238 bool QByteArray::isNull() const { return d == &shared_null.ba; }
3239
3240
3241 /*!
3242     Returns the byte array converted to a \c {long long} using base \a
3243     base, which is 10 by default and must be between 2 and 36, or 0.
3244
3245     If \a base is 0, the base is determined automatically using the
3246     following rules: If the byte array begins with "0x", it is assumed to
3247     be hexadecimal; if it begins with "0", it is assumed to be octal;
3248     otherwise it is assumed to be decimal.
3249
3250     Returns 0 if the conversion fails.
3251
3252     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3253     false; otherwise *\a{ok} is set to true.
3254
3255     \note The conversion of the number is performed in the default C locale,
3256     irrespective of the user's locale.
3257
3258     \sa number()
3259 */
3260
3261 qlonglong QByteArray::toLongLong(bool *ok, int base) const
3262 {
3263 #if defined(QT_CHECK_RANGE)
3264     if (base != 0 && (base < 2 || base > 36)) {
3265         qWarning("QByteArray::toLongLong: Invalid base %d", base);
3266         base = 10;
3267     }
3268 #endif
3269
3270     return QLocalePrivate::bytearrayToLongLong(nulTerminated().constData(), base, ok);
3271 }
3272
3273 /*!
3274     Returns the byte array converted to an \c {unsigned long long}
3275     using base \a base, which is 10 by default and must be between 2
3276     and 36, or 0.
3277
3278     If \a base is 0, the base is determined automatically using the
3279     following rules: If the byte array begins with "0x", it is assumed to
3280     be hexadecimal; if it begins with "0", it is assumed to be octal;
3281     otherwise it is assumed to be decimal.
3282
3283     Returns 0 if the conversion fails.
3284
3285     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3286     false; otherwise *\a{ok} is set to true.
3287
3288     \note The conversion of the number is performed in the default C locale,
3289     irrespective of the user's locale.
3290
3291     \sa number()
3292 */
3293
3294 qulonglong QByteArray::toULongLong(bool *ok, int base) const
3295 {
3296 #if defined(QT_CHECK_RANGE)
3297     if (base != 0 && (base < 2 || base > 36)) {
3298         qWarning("QByteArray::toULongLong: Invalid base %d", base);
3299         base = 10;
3300     }
3301 #endif
3302
3303     return QLocalePrivate::bytearrayToUnsLongLong(nulTerminated().constData(), base, ok);
3304 }
3305
3306
3307 /*!
3308     Returns the byte array converted to an \c int using base \a
3309     base, which is 10 by default and must be between 2 and 36, or 0.
3310
3311     If \a base is 0, the base is determined automatically using the
3312     following rules: If the byte array begins with "0x", it is assumed to
3313     be hexadecimal; if it begins with "0", it is assumed to be octal;
3314     otherwise it is assumed to be decimal.
3315
3316     Returns 0 if the conversion fails.
3317
3318     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3319     false; otherwise *\a{ok} is set to true.
3320
3321     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 36
3322
3323     \note The conversion of the number is performed in the default C locale,
3324     irrespective of the user's locale.
3325
3326     \sa number()
3327 */
3328
3329 int QByteArray::toInt(bool *ok, int base) const
3330 {
3331     qlonglong v = toLongLong(ok, base);
3332     if (v < INT_MIN || v > INT_MAX) {
3333         if (ok)
3334             *ok = false;
3335         v = 0;
3336     }
3337     return int(v);
3338 }
3339
3340 /*!
3341     Returns the byte array converted to an \c {unsigned int} using base \a
3342     base, which is 10 by default and must be between 2 and 36, or 0.
3343
3344     If \a base is 0, the base is determined automatically using the
3345     following rules: If the byte array begins with "0x", it is assumed to
3346     be hexadecimal; if it begins with "0", it is assumed to be octal;
3347     otherwise it is assumed to be decimal.
3348
3349     Returns 0 if the conversion fails.
3350
3351     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3352     false; otherwise *\a{ok} is set to true.
3353
3354     \note The conversion of the number is performed in the default C locale,
3355     irrespective of the user's locale.
3356
3357     \sa number()
3358 */
3359
3360 uint QByteArray::toUInt(bool *ok, int base) const
3361 {
3362     qulonglong v = toULongLong(ok, base);
3363     if (v > UINT_MAX) {
3364         if (ok)
3365             *ok = false;
3366         v = 0;
3367     }
3368     return uint(v);
3369 }
3370
3371 /*!
3372     \since 4.1
3373
3374     Returns the byte array converted to a \c long int using base \a
3375     base, which is 10 by default and must be between 2 and 36, or 0.
3376
3377     If \a base is 0, the base is determined automatically using the
3378     following rules: If the byte array begins with "0x", it is assumed to
3379     be hexadecimal; if it begins with "0", it is assumed to be octal;
3380     otherwise it is assumed to be decimal.
3381
3382     Returns 0 if the conversion fails.
3383
3384     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3385     false; otherwise *\a{ok} is set to true.
3386
3387     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 37
3388
3389     \note The conversion of the number is performed in the default C locale,
3390     irrespective of the user's locale.
3391
3392     \sa number()
3393 */
3394 long QByteArray::toLong(bool *ok, int base) const
3395 {
3396     qlonglong v = toLongLong(ok, base);
3397     if (v < LONG_MIN || v > LONG_MAX) {
3398         if (ok)
3399             *ok = false;
3400         v = 0;
3401     }
3402     return long(v);
3403 }
3404
3405 /*!
3406     \since 4.1
3407
3408     Returns the byte array converted to an \c {unsigned long int} using base \a
3409     base, which is 10 by default and must be between 2 and 36, or 0.
3410
3411     If \a base is 0, the base is determined automatically using the
3412     following rules: If the byte array begins with "0x", it is assumed to
3413     be hexadecimal; if it begins with "0", it is assumed to be octal;
3414     otherwise it is assumed to be decimal.
3415
3416     Returns 0 if the conversion fails.
3417
3418     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3419     false; otherwise *\a{ok} is set to true.
3420
3421     \note The conversion of the number is performed in the default C locale,
3422     irrespective of the user's locale.
3423
3424     \sa number()
3425 */
3426 ulong QByteArray::toULong(bool *ok, int base) const
3427 {
3428     qulonglong v = toULongLong(ok, base);
3429     if (v > ULONG_MAX) {
3430         if (ok)
3431             *ok = false;
3432         v = 0;
3433     }
3434     return ulong(v);
3435 }
3436
3437 /*!
3438     Returns the byte array converted to a \c short using base \a
3439     base, which is 10 by default and must be between 2 and 36, or 0.
3440
3441     If \a base is 0, the base is determined automatically using the
3442     following rules: If the byte array begins with "0x", it is assumed to
3443     be hexadecimal; if it begins with "0", it is assumed to be octal;
3444     otherwise it is assumed to be decimal.
3445
3446     Returns 0 if the conversion fails.
3447
3448     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3449     false; otherwise *\a{ok} is set to true.
3450
3451     \note The conversion of the number is performed in the default C locale,
3452     irrespective of the user's locale.
3453
3454     \sa number()
3455 */
3456
3457 short QByteArray::toShort(bool *ok, int base) const
3458 {
3459     qlonglong v = toLongLong(ok, base);
3460     if (v < SHRT_MIN || v > SHRT_MAX) {
3461         if (ok)
3462             *ok = false;
3463         v = 0;
3464     }
3465     return short(v);
3466 }
3467
3468 /*!
3469     Returns the byte array converted to an \c {unsigned short} using base \a
3470     base, which is 10 by default and must be between 2 and 36, or 0.
3471
3472     If \a base is 0, the base is determined automatically using the
3473     following rules: If the byte array begins with "0x", it is assumed to
3474     be hexadecimal; if it begins with "0", it is assumed to be octal;
3475     otherwise it is assumed to be decimal.
3476
3477     Returns 0 if the conversion fails.
3478
3479     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3480     false; otherwise *\a{ok} is set to true.
3481
3482     \note The conversion of the number is performed in the default C locale,
3483     irrespective of the user's locale.
3484
3485     \sa number()
3486 */
3487
3488 ushort QByteArray::toUShort(bool *ok, int base) const
3489 {
3490     qulonglong v = toULongLong(ok, base);
3491     if (v > USHRT_MAX) {
3492         if (ok)
3493             *ok = false;
3494         v = 0;
3495     }
3496     return ushort(v);
3497 }
3498
3499
3500 /*!
3501     Returns the byte array converted to a \c double value.
3502
3503     Returns 0.0 if the conversion fails.
3504
3505     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3506     false; otherwise *\a{ok} is set to true.
3507
3508     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 38
3509
3510     \note The conversion of the number is performed in the default C locale,
3511     irrespective of the user's locale.
3512
3513     \sa number()
3514 */
3515
3516 double QByteArray::toDouble(bool *ok) const
3517 {
3518     return QLocalePrivate::bytearrayToDouble(nulTerminated().constData(), ok);
3519 }
3520
3521 /*!
3522     Returns the byte array converted to a \c float value.
3523
3524     Returns 0.0 if the conversion fails.
3525
3526     If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3527     false; otherwise *\a{ok} is set to true.
3528
3529     \note The conversion of the number is performed in the default C locale,
3530     irrespective of the user's locale.
3531
3532     \sa number()
3533 */
3534
3535 float QByteArray::toFloat(bool *ok) const
3536 {
3537     return float(toDouble(ok));
3538 }
3539
3540 /*!
3541     Returns a copy of the byte array, encoded as Base64.
3542
3543     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 39
3544
3545     The algorithm used to encode Base64-encoded data is defined in \l{RFC 2045}.
3546
3547     \sa fromBase64()
3548 */
3549 QByteArray QByteArray::toBase64() const
3550 {
3551     const char alphabet[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
3552                             "ghijklmn" "opqrstuv" "wxyz0123" "456789+/";
3553     const char padchar = '=';
3554     int padlen = 0;
3555
3556     QByteArray tmp((d->size * 4) / 3 + 3, Qt::Uninitialized);
3557
3558     int i = 0;
3559     char *out = tmp.data();
3560     while (i < d->size) {
3561         int chunk = 0;
3562         chunk |= int(uchar(d->data()[i++])) << 16;
3563         if (i == d->size) {
3564             padlen = 2;
3565         } else {
3566             chunk |= int(uchar(d->data()[i++])) << 8;
3567             if (i == d->size) padlen = 1;
3568             else chunk |= int(uchar(d->data()[i++]));
3569         }
3570
3571         int j = (chunk & 0x00fc0000) >> 18;
3572         int k = (chunk & 0x0003f000) >> 12;
3573         int l = (chunk & 0x00000fc0) >> 6;
3574         int m = (chunk & 0x0000003f);
3575         *out++ = alphabet[j];
3576         *out++ = alphabet[k];
3577         if (padlen > 1) *out++ = padchar;
3578         else *out++ = alphabet[l];
3579         if (padlen > 0) *out++ = padchar;
3580         else *out++ = alphabet[m];
3581     }
3582
3583     tmp.truncate(out - tmp.data());
3584     return tmp;
3585 }
3586
3587 /*! 
3588     \fn QByteArray &QByteArray::setNum(int n, int base)
3589
3590     Sets the byte array to the printed value of \a n in base \a base (10
3591     by default) and returns a reference to the byte array. The \a base can
3592     be any value between 2 and 36.
3593
3594     Example:
3595     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 40
3596
3597     \note The format of the number is not localized; the default C locale
3598     is used irrespective of the user's locale.
3599
3600     \sa number(), toInt()
3601 */
3602
3603 /*! 
3604     \fn QByteArray &QByteArray::setNum(uint n, int base)
3605     \overload
3606
3607     \sa toUInt()
3608 */
3609
3610 /*! 
3611     \fn QByteArray &QByteArray::setNum(short n, int base)
3612     \overload
3613
3614     \sa toShort()
3615 */
3616
3617 /*! 
3618     \fn QByteArray &QByteArray::setNum(ushort n, int base)
3619     \overload
3620
3621     \sa toUShort()
3622 */
3623
3624 /*!
3625     \overload
3626
3627     \sa toLongLong()
3628 */
3629
3630 QByteArray &QByteArray::setNum(qlonglong n, int base)
3631 {
3632 #if defined(QT_CHECK_RANGE)
3633     if (base < 2 || base > 36) {
3634         qWarning("QByteArray::setNum: Invalid base %d", base);
3635         base = 10;
3636     }
3637 #endif
3638     QLocale locale(QLocale::C);
3639     *this = locale.d()->longLongToString(n, -1, base).toLatin1();
3640     return *this;
3641 }
3642
3643 /*!
3644     \overload
3645
3646     \sa toULongLong()
3647 */
3648
3649 QByteArray &QByteArray::setNum(qulonglong n, int base)
3650 {
3651 #if defined(QT_CHECK_RANGE)
3652     if (base < 2 || base > 36) {
3653         qWarning("QByteArray::setNum: Invalid base %d", base);
3654         base = 10;
3655     }
3656 #endif
3657     QLocale locale(QLocale::C);
3658     *this = locale.d()->unsLongLongToString(n, -1, base).toLatin1();
3659     return *this;
3660 }
3661
3662 /*! 
3663     \overload
3664
3665     Sets the byte array to the printed value of \a n, formatted in format
3666     \a f with precision \a prec, and returns a reference to the
3667     byte array.
3668
3669     The format \a f can be any of the following:
3670
3671     \table
3672     \header \i Format \i Meaning
3673     \row \i \c e \i format as [-]9.9e[+|-]999
3674     \row \i \c E \i format as [-]9.9E[+|-]999
3675     \row \i \c f \i format as [-]9.9
3676     \row \i \c g \i use \c e or \c f format, whichever is the most concise
3677     \row \i \c G \i use \c E or \c f format, whichever is the most concise
3678     \endtable
3679
3680     With 'e', 'E', and 'f', \a prec is the number of digits after the
3681     decimal point. With 'g' and 'G', \a prec is the maximum number of
3682     significant digits (trailing zeroes are omitted).
3683
3684     \note The format of the number is not localized; the default C locale
3685     is used irrespective of the user's locale.
3686
3687     \sa toDouble()
3688 */
3689
3690 QByteArray &QByteArray::setNum(double n, char f, int prec)
3691 {
3692     QLocalePrivate::DoubleForm form = QLocalePrivate::DFDecimal;
3693     uint flags = 0;
3694
3695     if (qIsUpper(f))
3696         flags = QLocalePrivate::CapitalEorX;
3697     f = qToLower(f);
3698
3699     switch (f) {
3700         case 'f':
3701             form = QLocalePrivate::DFDecimal;
3702             break;
3703         case 'e':
3704             form = QLocalePrivate::DFExponent;
3705             break;
3706         case 'g':
3707             form = QLocalePrivate::DFSignificantDigits;
3708             break;
3709         default:
3710 #if defined(QT_CHECK_RANGE)
3711             qWarning("QByteArray::setNum: Invalid format char '%c'", f);
3712 #endif
3713             break;
3714     }
3715
3716     QLocale locale(QLocale::C);
3717     *this = locale.d()->doubleToString(n, prec, form, -1, flags).toLatin1();
3718     return *this;
3719 }
3720
3721 /*! 
3722     \fn QByteArray &QByteArray::setNum(float n, char f, int prec)
3723     \overload
3724
3725     Sets the byte array to the printed value of \a n, formatted in format
3726     \a f with precision \a prec, and returns a reference to the
3727     byte array.
3728
3729     \note The format of the number is not localized; the default C locale
3730     is used irrespective of the user's locale.
3731
3732     \sa toFloat()
3733 */
3734
3735 /*!
3736     Returns a byte array containing the string equivalent of the
3737     number \a n to base \a base (10 by default). The \a base can be
3738     any value between 2 and 36.
3739
3740     Example:
3741     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 41
3742
3743     \note The format of the number is not localized; the default C locale
3744     is used irrespective of the user's locale.
3745
3746     \sa setNum(), toInt()
3747 */
3748 QByteArray QByteArray::number(int n, int base)
3749 {
3750     QByteArray s;
3751     s.setNum(n, base);
3752     return s;
3753 }
3754
3755 /*!
3756     \overload
3757
3758     \sa toUInt()
3759 */
3760 QByteArray QByteArray::number(uint n, int base)
3761 {
3762     QByteArray s;
3763     s.setNum(n, base);
3764     return s;
3765 }
3766
3767 /*!
3768     \overload
3769
3770     \sa toLongLong()
3771 */
3772 QByteArray QByteArray::number(qlonglong n, int base)
3773 {
3774     QByteArray s;
3775     s.setNum(n, base);
3776     return s;
3777 }
3778
3779 /*!
3780     \overload
3781
3782     \sa toULongLong()
3783 */
3784 QByteArray QByteArray::number(qulonglong n, int base)
3785 {
3786     QByteArray s;
3787     s.setNum(n, base);
3788     return s;
3789 }
3790
3791 /*! 
3792     \overload
3793
3794     Returns a byte array that contains the printed value of \a n,
3795     formatted in format \a f with precision \a prec.
3796
3797     Argument \a n is formatted according to the \a f format specified,
3798     which is \c g by default, and can be any of the following:
3799
3800     \table
3801     \header \i Format \i Meaning
3802     \row \i \c e \i format as [-]9.9e[+|-]999
3803     \row \i \c E \i format as [-]9.9E[+|-]999
3804     \row \i \c f \i format as [-]9.9
3805     \row \i \c g \i use \c e or \c f format, whichever is the most concise
3806     \row \i \c G \i use \c E or \c f format, whichever is the most concise
3807     \endtable
3808
3809     With 'e', 'E', and 'f', \a prec is the number of digits after the
3810     decimal point. With 'g' and 'G', \a prec is the maximum number of
3811     significant digits (trailing zeroes are omitted).
3812
3813     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 42
3814
3815     \note The format of the number is not localized; the default C locale
3816     is used irrespective of the user's locale.
3817
3818     \sa toDouble()
3819 */
3820 QByteArray QByteArray::number(double n, char f, int prec)
3821 {
3822     QByteArray s;
3823     s.setNum(n, f, prec);
3824     return s;
3825 }
3826
3827 /*!
3828     Constructs a QByteArray that uses the first \a size bytes of the
3829     \a data array. The bytes are \e not copied. The QByteArray will
3830     contain the \a data pointer. The caller guarantees that \a data
3831     will not be deleted or modified as long as this QByteArray and any
3832     copies of it exist that have not been modified. In other words,
3833     because QByteArray is an \l{implicitly shared} class and the
3834     instance returned by this function contains the \a data pointer,
3835     the caller must not delete \a data or modify it directly as long
3836     as the returned QByteArray and any copies exist. However,
3837     QByteArray does not take ownership of \a data, so the QByteArray
3838     destructor will never delete the raw \a data, even when the
3839     last QByteArray referring to \a data is destroyed.
3840
3841     A subsequent attempt to modify the contents of the returned
3842     QByteArray or any copy made from it will cause it to create a deep
3843     copy of the \a data array before doing the modification. This
3844     ensures that the raw \a data array itself will never be modified
3845     by QByteArray.
3846
3847     Here is an example of how to read data using a QDataStream on raw
3848     data in memory without copying the raw data into a QByteArray:
3849
3850     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 43
3851
3852     \warning A byte array created with fromRawData() is \e not
3853     null-terminated, unless the raw data contains a 0 character at
3854     position \a size. While that does not matter for QDataStream or
3855     functions like indexOf(), passing the byte array to a function
3856     accepting a \c{const char *} expected to be '\\0'-terminated will
3857     fail.
3858
3859     \sa setRawData(), data(), constData()
3860 */
3861
3862 QByteArray QByteArray::fromRawData(const char *data, int size)
3863 {
3864     Data *x;
3865     if (!data) {
3866         x = const_cast<Data *>(&shared_null.ba);
3867     } else if (!size) {
3868         x = const_cast<Data *>(&shared_empty.ba);
3869     } else {
3870         x = static_cast<Data *>(malloc(sizeof(Data) + 1));
3871         Q_CHECK_PTR(x);
3872         x->ref.initializeOwned();
3873         x->size = size;
3874         x->alloc = 0;
3875         x->capacityReserved = false;
3876         x->offset = data - (x->d + sizeof(qptrdiff));
3877     }
3878     return QByteArray(x, 0, 0);
3879 }
3880
3881 /*!
3882     \since 4.7
3883
3884     Resets the QByteArray to use the first \a size bytes of the
3885     \a data array. The bytes are \e not copied. The QByteArray will
3886     contain the \a data pointer. The caller guarantees that \a data
3887     will not be deleted or modified as long as this QByteArray and any
3888     copies of it exist that have not been modified.
3889
3890     This function can be used instead of fromRawData() to re-use
3891     existings QByteArray objects to save memory re-allocations.
3892
3893     \sa fromRawData(), data(), constData()
3894 */
3895 QByteArray &QByteArray::setRawData(const char *data, uint size)
3896 {
3897     if (d->ref.isShared() || d->alloc) {
3898         *this = fromRawData(data, size);
3899     } else {
3900         if (data) {
3901             d->size = size;
3902             d->offset = data - (d->d + sizeof(qptrdiff));
3903         } else {
3904             d->offset = 0;
3905             d->size = 0;
3906             *d->data() = 0;
3907         }
3908     }
3909     return *this;
3910 }
3911
3912 /*!
3913     Returns a decoded copy of the Base64 array \a base64. Input is not checked
3914     for validity; invalid characters in the input are skipped, enabling the
3915     decoding process to continue with subsequent characters.
3916
3917     For example:
3918
3919     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 44
3920
3921     The algorithm used to decode Base64-encoded data is defined in \l{RFC 2045}.
3922
3923     \sa toBase64()
3924 */
3925 QByteArray QByteArray::fromBase64(const QByteArray &base64)
3926 {
3927     unsigned int buf = 0;
3928     int nbits = 0;
3929     QByteArray tmp((base64.size() * 3) / 4, Qt::Uninitialized);
3930
3931     int offset = 0;
3932     for (int i = 0; i < base64.size(); ++i) {
3933         int ch = base64.at(i);
3934         int d;
3935
3936         if (ch >= 'A' && ch <= 'Z')
3937             d = ch - 'A';
3938         else if (ch >= 'a' && ch <= 'z')
3939             d = ch - 'a' + 26;
3940         else if (ch >= '0' && ch <= '9')
3941             d = ch - '0' + 52;
3942         else if (ch == '+')
3943             d = 62;
3944         else if (ch == '/')
3945             d = 63;
3946         else
3947             d = -1;
3948
3949         if (d != -1) {
3950             buf = (buf << 6) | d;
3951             nbits += 6;
3952             if (nbits >= 8) {
3953                 nbits -= 8;
3954                 tmp[offset++] = buf >> nbits;
3955                 buf &= (1 << nbits) - 1;
3956             }
3957         }
3958     }
3959
3960     tmp.truncate(offset);
3961     return tmp;
3962 }
3963
3964 /*!
3965     Returns a decoded copy of the hex encoded array \a hexEncoded. Input is not checked
3966     for validity; invalid characters in the input are skipped, enabling the
3967     decoding process to continue with subsequent characters.
3968
3969     For example:
3970
3971     \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 45
3972
3973     \sa toHex()
3974 */
3975 QByteArray QByteArray::fromHex(const QByteArray &hexEncoded)
3976 {
3977     QByteArray res((hexEncoded.size() + 1)/ 2, Qt::Uninitialized);
3978     uchar *result = (uchar *)res.data() + res.size();
3979
3980     bool odd_digit = true;
3981     for (int i = hexEncoded.size() - 1; i >= 0; --i) {
3982         int ch = hexEncoded.at(i);
3983         int tmp;
3984         if (ch >= '0' && ch <= '9')
3985             tmp = ch - '0';
3986         else if (ch >= 'a' && ch <= 'f')
3987             tmp = ch - 'a' + 10;
3988         else if (ch >= 'A' && ch <= 'F')
3989             tmp = ch - 'A' + 10;
3990         else
3991             continue;
3992         if (odd_digit) {
3993             --result;
3994             *result = tmp;
3995             odd_digit = false;
3996         } else {
3997             *result |= tmp << 4;
3998             odd_digit = true;
3999         }
4000     }
4001
4002     res.remove(0, result - (const uchar *)res.constData());
4003     return res;
4004 }
4005
4006 /*!
4007     Returns a hex encoded copy of the byte array. The hex encoding uses the numbers 0-9 and
4008     the letters a-f.
4009
4010     \sa fromHex()
4011 */
4012 QByteArray QByteArray::toHex() const
4013 {
4014     QByteArray hex(d->size * 2, Qt::Uninitialized);
4015     char *hexData = hex.data();
4016     const uchar *data = (const uchar *)d->data();
4017     for (int i = 0; i < d->size; ++i) {
4018         int j = (data[i] >> 4) & 0xf;
4019         if (j <= 9)
4020             hexData[i*2] = (j + '0');
4021          else
4022             hexData[i*2] = (j + 'a' - 10);
4023         j = data[i] & 0xf;
4024         if (j <= 9)
4025             hexData[i*2+1] = (j + '0');
4026          else
4027             hexData[i*2+1] = (j + 'a' - 10);
4028     }
4029     return hex;
4030 }
4031
4032 static void q_fromPercentEncoding(QByteArray *ba, char percent)
4033 {
4034     if (ba->isEmpty())
4035         return;
4036
4037     char *data = ba->data();
4038     const char *inputPtr = data;
4039
4040     int i = 0;
4041     int len = ba->count();
4042     int outlen = 0;
4043     int a, b;
4044     char c;
4045     while (i < len) {
4046         c = inputPtr[i];
4047         if (c == percent && i + 2 < len) {
4048             a = inputPtr[++i];
4049             b = inputPtr[++i];
4050
4051             if (a >= '0' && a <= '9') a -= '0';
4052             else if (a >= 'a' && a <= 'f') a = a - 'a' + 10;
4053             else if (a >= 'A' && a <= 'F') a = a - 'A' + 10;
4054
4055             if (b >= '0' && b <= '9') b -= '0';
4056             else if (b >= 'a' && b <= 'f') b  = b - 'a' + 10;
4057             else if (b >= 'A' && b <= 'F') b  = b - 'A' + 10;
4058
4059             *data++ = (char)((a << 4) | b);
4060         } else {
4061             *data++ = c;
4062         }
4063
4064         ++i;
4065         ++outlen;
4066     }
4067
4068     if (outlen != len)
4069         ba->truncate(outlen);
4070 }
4071
4072 void q_fromPercentEncoding(QByteArray *ba)
4073 {
4074     q_fromPercentEncoding(ba, '%');
4075 }
4076
4077 /*!
4078     \since 4.4
4079
4080     Returns a decoded copy of the URI/URL-style percent-encoded \a input.
4081     The \a percent parameter allows you to replace the '%' character for
4082     another (for instance, '_' or '=').
4083
4084     For example:
4085     \code
4086         QByteArray text = QByteArray::fromPercentEncoding("Qt%20is%20great%33");
4087         text.data();            // returns "Qt is great!"
4088     \endcode
4089
4090     \sa toPercentEncoding(), QUrl::fromPercentEncoding()
4091 */
4092 QByteArray QByteArray::fromPercentEncoding(const QByteArray &input, char percent)
4093 {
4094     if (input.isNull())
4095         return QByteArray();       // preserve null
4096     if (input.isEmpty())
4097         return QByteArray(input.data(), 0);
4098
4099     QByteArray tmp = input;
4100     q_fromPercentEncoding(&tmp, percent);
4101     return tmp;
4102 }
4103
4104 static inline bool q_strchr(const char str[], char chr)
4105 {
4106     if (!str) return false;
4107
4108     const char *ptr = str;
4109     char c;
4110     while ((c = *ptr++))
4111         if (c == chr)
4112             return true;
4113     return false;
4114 }
4115
4116 static inline char toHexHelper(char c)
4117 {
4118     static const char hexnumbers[] = "0123456789ABCDEF";
4119     return hexnumbers[c & 0xf];
4120 }
4121
4122 static void q_toPercentEncoding(QByteArray *ba, const char *dontEncode, const char *alsoEncode, char percent)
4123 {
4124     if (ba->isEmpty())
4125         return;
4126
4127     QByteArray input = *ba;
4128     int len = input.count();
4129     const char *inputData = input.constData();
4130     char *output = 0;
4131     int length = 0;
4132
4133     for (int i = 0; i < len; ++i) {
4134         unsigned char c = *inputData++;
4135         if (((c >= 0x61 && c <= 0x7A) // ALPHA
4136              || (c >= 0x41 && c <= 0x5A) // ALPHA
4137              || (c >= 0x30 && c <= 0x39) // DIGIT
4138              || c == 0x2D // -
4139              || c == 0x2E // .
4140              || c == 0x5F // _
4141              || c == 0x7E // ~
4142              || q_strchr(dontEncode, c))
4143             && !q_strchr(alsoEncode, c)) {
4144             if (output)
4145                 output[length] = c;
4146             ++length;
4147         } else {
4148             if (!output) {
4149                 // detach now
4150                 ba->resize(len*3); // worst case
4151                 output = ba->data();
4152             }
4153             output[length++] = percent;
4154             output[length++] = toHexHelper((c & 0xf0) >> 4);
4155             output[length++] = toHexHelper(c & 0xf);
4156         }
4157     }
4158     if (output)
4159         ba->truncate(length);
4160 }
4161
4162 void q_toPercentEncoding(QByteArray *ba, const char *exclude, const char *include)
4163 {
4164     q_toPercentEncoding(ba, exclude, include, '%');
4165 }
4166
4167 void q_normalizePercentEncoding(QByteArray *ba, const char *exclude)
4168 {
4169     q_fromPercentEncoding(ba, '%');
4170     q_toPercentEncoding(ba, exclude, 0, '%');
4171 }
4172
4173 /*!
4174     \since 4.4
4175
4176     Returns a URI/URL-style percent-encoded copy of this byte array. The
4177     \a percent parameter allows you to override the default '%'
4178     character for another.
4179
4180     By default, this function will encode all characters that are not
4181     one of the following:
4182
4183         ALPHA ("a" to "z" and "A" to "Z") / DIGIT (0 to 9) / "-" / "." / "_" / "~"
4184
4185     To prevent characters from being encoded pass them to \a
4186     exclude. To force characters to be encoded pass them to \a
4187     include. The \a percent character is always encoded.
4188
4189     Example:
4190
4191     \code
4192          QByteArray text = "{a fishy string?}";
4193          QByteArray ba = text.toPercentEncoding("{}", "s");
4194          qDebug(ba.constData());
4195          // prints "{a fi%73hy %73tring%3F}"
4196     \endcode
4197
4198     The hex encoding uses the numbers 0-9 and the uppercase letters A-F.
4199
4200     \sa fromPercentEncoding(), QUrl::toPercentEncoding()
4201 */
4202 QByteArray QByteArray::toPercentEncoding(const QByteArray &exclude, const QByteArray &include,
4203                                          char percent) const
4204 {
4205     if (isNull())
4206         return QByteArray();    // preserve null
4207     if (isEmpty())
4208         return QByteArray(data(), 0);
4209
4210     QByteArray include2 = include;
4211     if (percent != '%')                        // the default
4212         if ((percent >= 0x61 && percent <= 0x7A) // ALPHA
4213             || (percent >= 0x41 && percent <= 0x5A) // ALPHA
4214             || (percent >= 0x30 && percent <= 0x39) // DIGIT
4215             || percent == 0x2D // -
4216             || percent == 0x2E // .
4217             || percent == 0x5F // _
4218             || percent == 0x7E) // ~
4219         include2 += percent;
4220
4221     QByteArray result = *this;
4222     q_toPercentEncoding(&result, exclude.nulTerminated().constData(), include2.nulTerminated().constData(), percent);
4223
4224     return result;
4225 }
4226
4227 /*! \typedef QByteArray::ConstIterator
4228     \internal
4229 */
4230
4231 /*! \typedef QByteArray::Iterator
4232     \internal
4233 */
4234
4235 /*! \typedef QByteArray::const_iterator
4236     \internal
4237 */
4238
4239 /*! \typedef QByteArray::iterator
4240     \internal
4241 */
4242
4243 /*! \typedef QByteArray::const_reference
4244     \internal
4245 */
4246
4247 /*! \typedef QByteArray::reference
4248     \internal
4249 */
4250
4251 /*! \typedef QByteArray::value_type
4252   \internal
4253  */
4254
4255 /*!
4256     \fn DataPtr &QByteArray::data_ptr()
4257     \internal
4258 */
4259
4260 /*!
4261     \typedef QByteArray::DataPtr
4262     \internal
4263 */
4264
4265 QT_END_NAMESPACE