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

Last change on this file since 467 was 2, checked in by Dmitry A. Kuminov, 16 years ago

Initially imported qt-all-opensource-src-4.5.1 from Trolltech.

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