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