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

Last change on this file since 561 was 561, checked in by Dmitry A. Kuminov, 15 years ago

trunk: Merged in qt 4.6.1 sources.

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