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