source: trunk/src/corelib/tools/qbytearray.cpp@ 883

Last change on this file since 883 was 846, checked in by Dmitry A. Kuminov, 14 years ago

trunk: Merged in qt 4.7.2 sources from branches/vendor/nokia/qt.

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