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