1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** All rights reserved.
5 ** Contact: Nokia Corporation (qt-info@nokia.com)
7 ** This file is part of the QtCore module of the Qt Toolkit.
9 ** $QT_BEGIN_LICENSE:LGPL$
10 ** GNU Lesser General Public License Usage
11 ** This file may be used under the terms of the GNU Lesser General Public
12 ** License version 2.1 as published by the Free Software Foundation and
13 ** appearing in the file LICENSE.LGPL included in the packaging of this
14 ** file. Please review the following information to ensure the GNU Lesser
15 ** General Public License version 2.1 requirements will be met:
16 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
18 ** In addition, as a special exception, Nokia gives you certain additional
19 ** rights. These rights are described in the Nokia Qt LGPL Exception
20 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
22 ** GNU General Public License Usage
23 ** Alternatively, this file may be used under the terms of the GNU General
24 ** Public License version 3.0 as published by the Free Software Foundation
25 ** and appearing in the file LICENSE.GPL included in the packaging of this
26 ** file. Please review the following information to ensure the GNU General
27 ** Public License version 3.0 requirements will be met:
28 ** http://www.gnu.org/copyleft/gpl.html.
31 ** Alternatively, this file may be used in accordance with the terms and
32 ** conditions contained in a signed written agreement between you and Nokia.
40 ****************************************************************************/
42 #include "qbytearray.h"
43 #include "qbytearraymatcher.h"
48 #include "qlocale_p.h"
49 #include "qscopedpointer.h"
50 #include <qdatastream.h>
52 #ifndef QT_NO_COMPRESS
60 #define IS_RAW_DATA(d) ((d)->offset != 0)
66 const char *haystack0, int haystackLen, int from,
67 const char *needle0, int needleLen);
70 int qAllocMore(int alloc, int extra)
72 if (alloc == 0 && extra == 0)
74 const int page = 1 << 12;
78 nalloc = (1<<3) + ((alloc >>3) << 3);
80 // don't do anything if the loop will overflow signed int.
81 if (alloc >= INT_MAX/2)
83 nalloc = (alloc < page) ? 1 << 3 : page;
84 while (nalloc < alloc) {
90 return nalloc - extra;
93 /*****************************************************************************
94 Safe and portable C string functions; extensions to standard string.h
95 *****************************************************************************/
97 /*! \relates QByteArray
99 Returns a duplicate string.
101 Allocates space for a copy of \a src, copies it, and returns a
102 pointer to the copy. If \a src is 0, it immediately returns 0.
104 Ownership is passed to the caller, so the returned string must be
105 deleted using \c delete[].
108 char *qstrdup(const char *src)
112 char *dst = new char[strlen(src) + 1];
113 return qstrcpy(dst, src);
116 /*! \relates QByteArray
118 Copies all the characters up to and including the '\\0' from \a
119 src into \a dst and returns a pointer to \a dst. If \a src is 0,
120 it immediately returns 0.
122 This function assumes that \a dst is large enough to hold the
128 char *qstrcpy(char *dst, const char *src)
132 #if defined(_MSC_VER) && _MSC_VER >= 1400
133 int len = qstrlen(src);
134 // This is actually not secure!!! It will be fixed
135 // properly in a later release!
136 if (len >= 0 && strcpy_s(dst, len+1, src) == 0)
140 return strcpy(dst, src);
144 /*! \relates QByteArray
146 A safe \c strncpy() function.
148 Copies at most \a len bytes from \a src (stopping at \a len or the
149 terminating '\\0' whichever comes first) into \a dst and returns a
150 pointer to \a dst. Guarantees that \a dst is '\\0'-terminated. If
151 \a src or \a dst is 0, returns 0 immediately.
153 This function assumes that \a dst is at least \a len characters
156 \note When compiling with Visual C++ compiler version 14.00
157 (Visual C++ 2005) or later, internally the function strncpy_s
163 char *qstrncpy(char *dst, const char *src, uint len)
167 #if defined(_MSC_VER) && _MSC_VER >= 1400
168 strncpy_s(dst, len, src, len-1);
170 strncpy(dst, src, len);
177 /*! \fn uint qstrlen(const char *str)
180 A safe \c strlen() function.
182 Returns the number of characters that precede the terminating '\\0',
188 /*! \fn uint qstrnlen(const char *str, uint maxlen)
192 A safe \c strnlen() function.
194 Returns the number of characters that precede the terminating '\\0', but
195 at most \a maxlen. If \a str is 0, returns 0.
203 A safe \c strcmp() function.
205 Compares \a str1 and \a str2. Returns a negative value if \a str1
206 is less than \a str2, 0 if \a str1 is equal to \a str2 or a
207 positive value if \a str1 is greater than \a str2.
209 Special case 1: Returns 0 if \a str1 and \a str2 are both 0.
211 Special case 2: Returns an arbitrary non-zero value if \a str1 is 0
212 or \a str2 is 0 (but not both).
214 \sa qstrncmp(), qstricmp(), qstrnicmp(), {8-bit Character Comparisons}
216 int qstrcmp(const char *str1, const char *str2)
218 return (str1 && str2) ? strcmp(str1, str2)
219 : (str1 ? 1 : (str2 ? -1 : 0));
222 /*! \fn int qstrncmp(const char *str1, const char *str2, uint len);
226 A safe \c strncmp() function.
228 Compares at most \a len bytes of \a str1 and \a str2.
230 Returns a negative value if \a str1 is less than \a str2, 0 if \a
231 str1 is equal to \a str2 or a positive value if \a str1 is greater
234 Special case 1: Returns 0 if \a str1 and \a str2 are both 0.
236 Special case 2: Returns a random non-zero value if \a str1 is 0
237 or \a str2 is 0 (but not both).
239 \sa qstrcmp(), qstricmp(), qstrnicmp(), {8-bit Character Comparisons}
242 /*! \relates QByteArray
244 A safe \c stricmp() function.
246 Compares \a str1 and \a str2 ignoring the case of the
247 characters. The encoding of the strings is assumed to be Latin-1.
249 Returns a negative value if \a str1 is less than \a str2, 0 if \a
250 str1 is equal to \a str2 or a positive value if \a str1 is greater
253 Special case 1: Returns 0 if \a str1 and \a str2 are both 0.
255 Special case 2: Returns a random non-zero value if \a str1 is 0
256 or \a str2 is 0 (but not both).
258 \sa qstrcmp(), qstrncmp(), qstrnicmp(), {8-bit Character Comparisons}
261 int qstricmp(const char *str1, const char *str2)
263 register const uchar *s1 = reinterpret_cast<const uchar *>(str1);
264 register const uchar *s2 = reinterpret_cast<const uchar *>(str2);
268 return s1 ? 1 : (s2 ? -1 : 0);
269 for (; !(res = (c = QChar::toLower((ushort)*s1)) - QChar::toLower((ushort)*s2)); s1++, s2++)
270 if (!c) // strings are equal
275 /*! \relates QByteArray
277 A safe \c strnicmp() function.
279 Compares at most \a len bytes of \a str1 and \a str2 ignoring the
280 case of the characters. The encoding of the strings is assumed to
283 Returns a negative value if \a str1 is less than \a str2, 0 if \a str1
284 is equal to \a str2 or a positive value if \a str1 is greater than \a
287 Special case 1: Returns 0 if \a str1 and \a str2 are both 0.
289 Special case 2: Returns a random non-zero value if \a str1 is 0
290 or \a str2 is 0 (but not both).
292 \sa qstrcmp(), qstrncmp(), qstricmp(), {8-bit Character Comparisons}
295 int qstrnicmp(const char *str1, const char *str2, uint len)
297 register const uchar *s1 = reinterpret_cast<const uchar *>(str1);
298 register const uchar *s2 = reinterpret_cast<const uchar *>(str2);
302 return s1 ? 1 : (s2 ? -1 : 0);
303 for (; len--; s1++, s2++) {
304 if ((res = (c = QChar::toLower((ushort)*s1)) - QChar::toLower((ushort)*s2)))
306 if (!c) // strings are equal
315 int qstrcmp(const QByteArray &str1, const char *str2)
318 return str1.isEmpty() ? 0 : +1;
320 const char *str1data = str1.constData();
321 const char *str1end = str1data + str1.length();
322 for ( ; str1data < str1end && *str2; ++str1data, ++str2) {
323 register int diff = int(uchar(*str1data)) - uchar(*str2);
325 // found a difference
331 // not the null, so we stopped because str1 is shorter
333 if (str1data < str1end)
334 // we haven't reached the end, so str1 must be longer
342 int qstrcmp(const QByteArray &str1, const QByteArray &str2)
344 int l1 = str1.length();
345 int l2 = str2.length();
346 int ret = memcmp(str1, str2, qMin(l1, l2));
350 // they matched qMin(l1, l2) bytes
351 // so the longer one is lexically after the shorter one
355 // the CRC table below is created by the following piece of code
357 static void createCRC16Table() // build CRC16 lookup table
359 register unsigned int i;
360 register unsigned int j;
361 unsigned short crc_tbl[16];
362 unsigned int v0, v1, v2, v3;
363 for (i = 0; i < 16; i++) {
370 #define SET_BIT(x, b, v) (x) |= (v) << (b)
385 printf("static const quint16 crc_tbl[16] = {\n");
386 for (int i = 0; i < 16; i +=4)
387 printf(" 0x%04x, 0x%04x, 0x%04x, 0x%04x,\n", crc_tbl[i], crc_tbl[i+1], crc_tbl[i+2], crc_tbl[i+3]);
392 static const quint16 crc_tbl[16] = {
393 0x0000, 0x1081, 0x2102, 0x3183,
394 0x4204, 0x5285, 0x6306, 0x7387,
395 0x8408, 0x9489, 0xa50a, 0xb58b,
396 0xc60c, 0xd68d, 0xe70e, 0xf78f
402 Returns the CRC-16 checksum of the first \a len bytes of \a data.
404 The checksum is independent of the byte order (endianness).
406 \note This function is a 16-bit cache conserving (16 entry table)
407 implementation of the CRC-16-CCITT algorithm.
410 quint16 qChecksum(const char *data, uint len)
412 register quint16 crc = 0xffff;
414 const uchar *p = reinterpret_cast<const uchar *>(data);
417 crc = ((crc >> 4) & 0x0fff) ^ crc_tbl[((crc ^ c) & 15)];
419 crc = ((crc >> 4) & 0x0fff) ^ crc_tbl[((crc ^ c) & 15)];
421 return ~crc & 0xffff;
425 \fn QByteArray qCompress(const QByteArray& data, int compressionLevel)
429 Compresses the \a data byte array and returns the compressed data
432 The \a compressionLevel parameter specifies how much compression
433 should be used. Valid values are between 0 and 9, with 9
434 corresponding to the greatest compression (i.e. smaller compressed
435 data) at the cost of using a slower algorithm. Smaller values (8,
436 7, ..., 1) provide successively less compression at slightly
437 faster speeds. The value 0 corresponds to no compression at all.
438 The default value is -1, which specifies zlib's default
444 /*! \relates QByteArray
448 Compresses the first \a nbytes of \a data and returns the
449 compressed data in a new byte array.
452 #ifndef QT_NO_COMPRESS
453 QByteArray qCompress(const uchar* data, int nbytes, int compressionLevel)
456 return QByteArray(4, '\0');
459 qWarning("qCompress: Data is null");
462 if (compressionLevel < -1 || compressionLevel > 9)
463 compressionLevel = -1;
465 ulong len = nbytes + nbytes / 100 + 13;
469 bazip.resize(len + 4);
470 res = ::compress2((uchar*)bazip.data()+4, &len, (uchar*)data, nbytes, compressionLevel);
474 bazip.resize(len + 4);
475 bazip[0] = (nbytes & 0xff000000) >> 24;
476 bazip[1] = (nbytes & 0x00ff0000) >> 16;
477 bazip[2] = (nbytes & 0x0000ff00) >> 8;
478 bazip[3] = (nbytes & 0x000000ff);
481 qWarning("qCompress: Z_MEM_ERROR: Not enough memory");
488 } while (res == Z_BUF_ERROR);
495 \fn QByteArray qUncompress(const QByteArray &data)
499 Uncompresses the \a data byte array and returns a new byte array
500 with the uncompressed data.
502 Returns an empty QByteArray if the input data was corrupt.
504 This function will uncompress data compressed with qCompress()
505 from this and any earlier Qt version, back to Qt 3.1 when this
508 \bold{Note:} If you want to use this function to uncompress external
509 data that was compressed using zlib, you first need to prepend a four
510 byte header to the byte array containing the data. The header must
511 contain the expected length (in bytes) of the uncompressed data,
512 expressed as an unsigned, big-endian, 32-bit integer.
517 /*! \relates QByteArray
521 Uncompresses the first \a nbytes of \a data and returns a new byte
522 array with the uncompressed data.
525 #ifndef QT_NO_COMPRESS
526 QByteArray qUncompress(const uchar* data, int nbytes)
529 qWarning("qUncompress: Data is null");
533 if (nbytes < 4 || (data[0]!=0 || data[1]!=0 || data[2]!=0 || data[3]!=0))
534 qWarning("qUncompress: Input data is corrupted");
537 ulong expectedSize = (data[0] << 24) | (data[1] << 16) |
538 (data[2] << 8) | (data[3] );
539 ulong len = qMax(expectedSize, 1ul);
540 QScopedPointer<QByteArray::Data, QScopedPointerPodDeleter> d;
544 if (len >= (1u << 31u) - sizeof(QByteArray::Data)) {
545 //QByteArray does not support that huge size anyway.
546 qWarning("qUncompress: Input data is corrupted");
549 QByteArray::Data *p = static_cast<QByteArray::Data *>(qRealloc(d.data(), sizeof(QByteArray::Data) + alloc + 1));
551 // we are not allowed to crash here when compiling with QT_NO_EXCEPTIONS
552 qWarning("qUncompress: could not allocate enough memory to uncompress data");
555 d.take(); // realloc was successful
559 int res = ::uncompress((uchar*)d->data(), &len,
560 (uchar*)data+4, nbytes-4);
565 if (len >= (1u << 31u) - sizeof(QByteArray::Data)) {
566 //QByteArray does not support that huge size anyway.
567 qWarning("qUncompress: Input data is corrupted");
570 QByteArray::Data *p = static_cast<QByteArray::Data *>(qRealloc(d.data(), sizeof(QByteArray::Data) + len + 1));
572 // we are not allowed to crash here when compiling with QT_NO_EXCEPTIONS
573 qWarning("qUncompress: could not allocate enough memory to uncompress data");
576 d.take(); // realloc was successful
582 d->capacityReserved = false;
586 return QByteArray(d.take(), 0, 0);
589 qWarning("qUncompress: Z_MEM_ERROR: Not enough memory");
597 qWarning("qUncompress: Z_DATA_ERROR: Input data is corrupted");
604 static inline bool qIsUpper(char c)
606 return c >= 'A' && c <= 'Z';
609 static inline char qToLower(char c)
611 if (c >= 'A' && c <= 'Z')
612 return c - 'A' + 'a';
617 const QConstByteArrayData<1> QByteArray::shared_null = { { Q_REFCOUNT_INITIALIZER(-1),
618 0, 0, 0, { 0 } }, { 0 } };
619 const QConstByteArrayData<1> QByteArray::shared_empty = { { Q_REFCOUNT_INITIALIZER(-1),
620 0, 0, 0, { 0 } }, { 0 } };
624 \brief The QByteArray class provides an array of bytes.
628 \ingroup string-processing
632 QByteArray can be used to store both raw bytes (including '\\0's)
633 and traditional 8-bit '\\0'-terminated strings. Using QByteArray
634 is much more convenient than using \c{const char *}. Behind the
635 scenes, it always ensures that the data is followed by a '\\0'
636 terminator, and uses \l{implicit sharing} (copy-on-write) to
637 reduce memory usage and avoid needless copying of data.
639 In addition to QByteArray, Qt also provides the QString class to
640 store string data. For most purposes, QString is the class you
641 want to use. It stores 16-bit Unicode characters, making it easy
642 to store non-ASCII/non-Latin-1 characters in your application.
643 Furthermore, QString is used throughout in the Qt API. The two
644 main cases where QByteArray is appropriate are when you need to
645 store raw binary data, and when memory conservation is critical
646 (e.g., with Qt for Embedded Linux).
648 One way to initialize a QByteArray is simply to pass a \c{const
649 char *} to its constructor. For example, the following code
650 creates a byte array of size 5 containing the data "Hello":
652 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 0
654 Although the size() is 5, the byte array also maintains an extra
655 '\\0' character at the end so that if a function is used that
656 asks for a pointer to the underlying data (e.g. a call to
657 data()), the data pointed to is guaranteed to be
660 QByteArray makes a deep copy of the \c{const char *} data, so you
661 can modify it later without experiencing side effects. (If for
662 performance reasons you don't want to take a deep copy of the
663 character data, use QByteArray::fromRawData() instead.)
665 Another approach is to set the size of the array using resize()
666 and to initialize the data byte per byte. QByteArray uses 0-based
667 indexes, just like C++ arrays. To access the byte at a particular
668 index position, you can use operator[](). On non-const byte
669 arrays, operator[]() returns a reference to a byte that can be
670 used on the left side of an assignment. For example:
672 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 1
674 For read-only access, an alternative syntax is to use at():
676 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 2
678 at() can be faster than operator[](), because it never causes a
679 \l{deep copy} to occur.
681 To extract many bytes at a time, use left(), right(), or mid().
683 A QByteArray can embed '\\0' bytes. The size() function always
684 returns the size of the whole array, including embedded '\\0'
685 bytes. If you want to obtain the length of the data up to and
686 excluding the first '\\0' character, call qstrlen() on the byte
689 After a call to resize(), newly allocated bytes have undefined
690 values. To set all the bytes to a particular value, call fill().
692 To obtain a pointer to the actual character data, call data() or
693 constData(). These functions return a pointer to the beginning of the data.
694 The pointer is guaranteed to remain valid until a non-const function is
695 called on the QByteArray. It is also guaranteed that the data ends with a
696 '\\0' byte unless the QByteArray was created from a \l{fromRawData()}{raw
697 data}. This '\\0' byte is automatically provided by QByteArray and is not
700 QByteArray provides the following basic functions for modifying
701 the byte data: append(), prepend(), insert(), replace(), and
702 remove(). For example:
704 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 3
706 The replace() and remove() functions' first two arguments are the
707 position from which to start erasing and the number of bytes that
710 When you append() data to a non-empty array, the array will be
711 reallocated and the new data copied to it. You can avoid this
712 behavior by calling reserve(), which preallocates a certain amount
713 of memory. You can also call capacity() to find out how much
714 memory QByteArray actually allocated. Data appended to an empty
717 A frequent requirement is to remove whitespace characters from a
718 byte array ('\\n', '\\t', ' ', etc.). If you want to remove
719 whitespace from both ends of a QByteArray, use trimmed(). If you
720 want to remove whitespace from both ends and replace multiple
721 consecutive whitespaces with a single space character within the
722 byte array, use simplified().
724 If you want to find all occurrences of a particular character or
725 substring in a QByteArray, use indexOf() or lastIndexOf(). The
726 former searches forward starting from a given index position, the
727 latter searches backward. Both return the index position of the
728 character or substring if they find it; otherwise, they return -1.
729 For example, here's a typical loop that finds all occurrences of a
730 particular substring:
732 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 4
734 If you simply want to check whether a QByteArray contains a
735 particular character or substring, use contains(). If you want to
736 find out how many times a particular character or substring
737 occurs in the byte array, use count(). If you want to replace all
738 occurrences of a particular value with another, use one of the
739 two-parameter replace() overloads.
741 QByteArrays can be compared using overloaded operators such as
742 operator<(), operator<=(), operator==(), operator>=(), and so on.
743 The comparison is based exclusively on the numeric values
744 of the characters and is very fast, but is not what a human would
745 expect. QString::localeAwareCompare() is a better choice for
746 sorting user-interface strings.
748 For historical reasons, QByteArray distinguishes between a null
749 byte array and an empty byte array. A \e null byte array is a
750 byte array that is initialized using QByteArray's default
751 constructor or by passing (const char *)0 to the constructor. An
752 \e empty byte array is any byte array with size 0. A null byte
753 array is always empty, but an empty byte array isn't necessarily
756 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 5
758 All functions except isNull() treat null byte arrays the same as
759 empty byte arrays. For example, data() returns a pointer to a
760 '\\0' character for a null byte array (\e not a null pointer),
761 and QByteArray() compares equal to QByteArray(""). We recommend
762 that you always use isEmpty() and avoid isNull().
764 \section1 Notes on Locale
766 \section2 Number-String Conversions
768 Functions that perform conversions between numeric data types and
769 strings are performed in the C locale, irrespective of the user's
770 locale settings. Use QString to perform locale-aware conversions
771 between numbers and strings.
773 \section2 8-bit Character Comparisons
775 In QByteArray, the notion of uppercase and lowercase and of which
776 character is greater than or less than another character is
777 locale dependent. This affects functions that support a case
778 insensitive option or that compare or lowercase or uppercase
779 their arguments. Case insensitive operations and comparisons will
780 be accurate if both strings contain only ASCII characters. (If \c
781 $LC_CTYPE is set, most Unix systems do "the right thing".)
782 Functions that this affects include contains(), indexOf(),
783 lastIndexOf(), operator<(), operator<=(), operator>(),
784 operator>=(), toLower() and toUpper().
786 This issue does not apply to QStrings since they represent
787 characters using Unicode.
789 \sa QString, QBitArray
792 /*! \fn QByteArray::iterator QByteArray::begin()
797 /*! \fn QByteArray::const_iterator QByteArray::begin() const
802 /*! \fn QByteArray::const_iterator QByteArray::constBegin() const
807 /*! \fn QByteArray::iterator QByteArray::end()
812 /*! \fn QByteArray::const_iterator QByteArray::end() const
817 /*! \fn QByteArray::const_iterator QByteArray::constEnd() const
822 /*! \fn void QByteArray::push_back(const QByteArray &other)
824 This function is provided for STL compatibility. It is equivalent
828 /*! \fn void QByteArray::push_back(const char *str)
832 Same as append(\a str).
835 /*! \fn void QByteArray::push_back(char ch)
839 Same as append(\a ch).
842 /*! \fn void QByteArray::push_front(const QByteArray &other)
844 This function is provided for STL compatibility. It is equivalent
845 to prepend(\a other).
848 /*! \fn void QByteArray::push_front(const char *str)
852 Same as prepend(\a str).
855 /*! \fn void QByteArray::push_front(char ch)
859 Same as prepend(\a ch).
862 /*! \fn QByteArray::QByteArray(const QByteArray &other)
864 Constructs a copy of \a other.
866 This operation takes \l{constant time}, because QByteArray is
867 \l{implicitly shared}. This makes returning a QByteArray from a
868 function very fast. If a shared instance is modified, it will be
869 copied (copy-on-write), taking \l{linear time}.
874 /*! \fn QByteArray::~QByteArray()
875 Destroys the byte array.
879 Assigns \a other to this byte array and returns a reference to
882 QByteArray &QByteArray::operator=(const QByteArray & other)
895 Assigns \a str to this byte array.
898 QByteArray &QByteArray::operator=(const char *str)
902 x = const_cast<Data *>(&shared_null.ba);
904 x = const_cast<Data *>(&shared_empty.ba);
906 int len = qstrlen(str);
907 if (d->ref != 1 || len > int(d->alloc) || (len < d->size && len < int(d->alloc) >> 1))
910 memcpy(x->data(), str, len + 1); // include null terminator
920 /*! \fn void QByteArray::swap(QByteArray &other)
923 Swaps byte array \a other with this byte array. This operation is very
924 fast and never fails.
927 /*! \fn int QByteArray::size() const
929 Returns the number of bytes in this byte array.
931 The last byte in the byte array is at position size() - 1. In addition,
932 QByteArray ensures that the byte at position size() is always '\\0', so
933 that you can use the return value of data() and constData() as arguments to
934 functions that expect '\\0'-terminated strings. If the QByteArray object
935 was created from a \l{fromRawData()}{raw data} that didn't include the
936 trailing null-termination character then QByteArray doesn't add it
937 automaticall unless the \l{deep copy} is created.
940 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 6
942 \sa isEmpty(), resize()
945 /*! \fn bool QByteArray::isEmpty() const
947 Returns true if the byte array has size 0; otherwise returns false.
950 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 7
955 /*! \fn int QByteArray::capacity() const
957 Returns the maximum number of bytes that can be stored in the
958 byte array without forcing a reallocation.
960 The sole purpose of this function is to provide a means of fine
961 tuning QByteArray's memory usage. In general, you will rarely
962 ever need to call this function. If you want to know how many
963 bytes are in the byte array, call size().
965 \sa reserve(), squeeze()
968 /*! \fn void QByteArray::reserve(int size)
970 Attempts to allocate memory for at least \a size bytes. If you
971 know in advance how large the byte array will be, you can call
972 this function, and if you call resize() often you are likely to
973 get better performance. If \a size is an underestimate, the worst
974 that will happen is that the QByteArray will be a bit slower.
976 The sole purpose of this function is to provide a means of fine
977 tuning QByteArray's memory usage. In general, you will rarely
978 ever need to call this function. If you want to change the size
979 of the byte array, call resize().
981 \sa squeeze(), capacity()
984 /*! \fn void QByteArray::squeeze()
986 Releases any memory not required to store the array's data.
988 The sole purpose of this function is to provide a means of fine
989 tuning QByteArray's memory usage. In general, you will rarely
990 ever need to call this function.
992 \sa reserve(), capacity()
995 /*! \fn QByteArray::operator const char *() const
996 \fn QByteArray::operator const void *() const
998 Returns a pointer to the data stored in the byte array. The
999 pointer can be used to access the bytes that compose the array.
1000 The data is '\\0'-terminated. The pointer remains valid as long
1001 as the array isn't reallocated or destroyed.
1003 This operator is mostly useful to pass a byte array to a function
1004 that accepts a \c{const char *}.
1006 You can disable this operator by defining \c
1007 QT_NO_CAST_FROM_BYTEARRAY when you compile your applications.
1009 Note: A QByteArray can store any byte values including '\\0's,
1010 but most functions that take \c{char *} arguments assume that the
1011 data ends at the first '\\0' they encounter.
1017 \macro QT_NO_CAST_FROM_BYTEARRAY
1020 Disables automatic conversions from QByteArray to
1021 const char * or const void *.
1023 \sa QT_NO_CAST_TO_ASCII, QT_NO_CAST_FROM_ASCII
1026 /*! \fn char *QByteArray::data()
1028 Returns a pointer to the data stored in the byte array. The
1029 pointer can be used to access and modify the bytes that compose
1030 the array. The data is '\\0'-terminated, i.e. the number of
1031 bytes in the returned character string is size() + 1 for the
1035 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 8
1037 The pointer remains valid as long as the byte array isn't
1038 reallocated or destroyed. For read-only access, constData() is
1039 faster because it never causes a \l{deep copy} to occur.
1041 This function is mostly useful to pass a byte array to a function
1042 that accepts a \c{const char *}.
1044 The following example makes a copy of the char* returned by
1045 data(), but it will corrupt the heap and cause a crash because it
1046 does not allocate a byte for the '\\0' at the end:
1048 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 46
1050 This one allocates the correct amount of space:
1052 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 47
1054 Note: A QByteArray can store any byte values including '\\0's,
1055 but most functions that take \c{char *} arguments assume that the
1056 data ends at the first '\\0' they encounter.
1058 \sa constData(), operator[]()
1061 /*! \fn const char *QByteArray::data() const
1066 /*! \fn const char *QByteArray::constData() const
1068 Returns a pointer to the data stored in the byte array. The pointer can be
1069 used to access the bytes that compose the array. The data is
1070 '\\0'-terminated unless the QByteArray object was created from raw data.
1071 The pointer remains valid as long as the byte array isn't reallocated or
1074 This function is mostly useful to pass a byte array to a function
1075 that accepts a \c{const char *}.
1077 Note: A QByteArray can store any byte values including '\\0's,
1078 but most functions that take \c{char *} arguments assume that the
1079 data ends at the first '\\0' they encounter.
1081 \sa data(), operator[](), fromRawData()
1084 /*! \fn void QByteArray::detach()
1089 /*! \fn bool QByteArray::isDetached() const
1094 /*! \fn bool QByteArray::isSharedWith(const QByteArray &other) const
1099 /*! \fn char QByteArray::at(int i) const
1101 Returns the character at index position \a i in the byte array.
1103 \a i must be a valid index position in the byte array (i.e., 0 <=
1109 /*! \fn QByteRef QByteArray::operator[](int i)
1111 Returns the byte at index position \a i as a modifiable reference.
1113 If an assignment is made beyond the end of the byte array, the
1114 array is extended with resize() before the assignment takes
1118 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 9
1120 The return value is of type QByteRef, a helper class for
1121 QByteArray. When you get an object of type QByteRef, you can use
1122 it as if it were a char &. If you assign to it, the assignment
1123 will apply to the character in the QByteArray from which you got
1129 /*! \fn char QByteArray::operator[](int i) const
1136 /*! \fn QByteRef QByteArray::operator[](uint i)
1141 /*! \fn char QByteArray::operator[](uint i) const
1146 /*! \fn QBool QByteArray::contains(const QByteArray &ba) const
1148 Returns true if the byte array contains an occurrence of the byte
1149 array \a ba; otherwise returns false.
1151 \sa indexOf(), count()
1154 /*! \fn QBool QByteArray::contains(const char *str) const
1158 Returns true if the byte array contains the string \a str;
1159 otherwise returns false.
1162 /*! \fn QBool QByteArray::contains(char ch) const
1166 Returns true if the byte array contains the character \a ch;
1167 otherwise returns false.
1172 Truncates the byte array at index position \a pos.
1174 If \a pos is beyond the end of the array, nothing happens.
1177 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 10
1179 \sa chop(), resize(), left()
1181 void QByteArray::truncate(int pos)
1189 Removes \a n bytes from the end of the byte array.
1191 If \a n is greater than size(), the result is an empty byte
1195 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 11
1197 \sa truncate(), resize(), left()
1200 void QByteArray::chop(int n)
1203 resize(d->size - n);
1207 /*! \fn QByteArray &QByteArray::operator+=(const QByteArray &ba)
1209 Appends the byte array \a ba onto the end of this byte array and
1210 returns a reference to this byte array.
1213 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 12
1215 Note: QByteArray is an \l{implicitly shared} class. Consequently,
1216 if \e this is an empty QByteArray, then \e this will just share
1217 the data held in \a ba. In this case, no copying of data is done,
1218 taking \l{constant time}. If a shared instance is modified, it will
1219 be copied (copy-on-write), taking \l{linear time}.
1221 If \e this is not an empty QByteArray, a deep copy of the data is
1222 performed, taking \l{linear time}.
1224 This operation typically does not suffer from allocation overhead,
1225 because QByteArray preallocates extra space at the end of the data
1226 so that it may grow without reallocating for each append operation.
1228 \sa append(), prepend()
1231 /*! \fn QByteArray &QByteArray::operator+=(const QString &str)
1235 Appends the string \a str onto the end of this byte array and
1236 returns a reference to this byte array. The Unicode data is
1237 converted into 8-bit characters using QString::toAscii().
1239 If the QString contains non-ASCII Unicode characters, using this
1240 operator can lead to loss of information. You can disable this
1241 operator by defining \c QT_NO_CAST_TO_ASCII when you compile your
1242 applications. You then need to call QString::toAscii() (or
1243 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
1244 explicitly if you want to convert the data to \c{const char *}.
1247 /*! \fn QByteArray &QByteArray::operator+=(const char *str)
1251 Appends the string \a str onto the end of this byte array and
1252 returns a reference to this byte array.
1255 /*! \fn QByteArray &QByteArray::operator+=(char ch)
1259 Appends the character \a ch onto the end of this byte array and
1260 returns a reference to this byte array.
1263 /*! \fn int QByteArray::length() const
1268 /*! \fn bool QByteArray::isNull() const
1270 Returns true if this byte array is null; otherwise returns false.
1273 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 13
1275 Qt makes a distinction between null byte arrays and empty byte
1276 arrays for historical reasons. For most applications, what
1277 matters is whether or not a byte array contains any data,
1278 and this can be determined using isEmpty().
1283 /*! \fn QByteArray::QByteArray()
1285 Constructs an empty byte array.
1290 /*! \fn QByteArray::QByteArray(const char *str)
1292 Constructs a byte array initialized with the string \a str.
1294 QByteArray makes a deep copy of the string data.
1297 QByteArray::QByteArray(const char *str)
1300 d = const_cast<Data *>(&shared_null.ba);
1302 d = const_cast<Data *>(&shared_empty.ba);
1304 int len = qstrlen(str);
1305 d = static_cast<Data *>(qMalloc(sizeof(Data) + len + 1));
1310 d->capacityReserved = false;
1312 memcpy(d->data(), str, len+1); // include null terminator
1317 Constructs a byte array containing the first \a size bytes of
1320 If \a data is 0, a null byte array is constructed.
1322 QByteArray makes a deep copy of the string data.
1327 QByteArray::QByteArray(const char *data, int size)
1330 d = const_cast<Data *>(&shared_null.ba);
1331 } else if (size <= 0) {
1332 d = const_cast<Data *>(&shared_empty.ba);
1334 d = static_cast<Data *>(qMalloc(sizeof(Data) + size + 1));
1339 d->capacityReserved = false;
1341 memcpy(d->data(), data, size);
1342 d->data()[size] = '\0';
1347 Constructs a byte array of size \a size with every byte set to
1353 QByteArray::QByteArray(int size, char ch)
1356 d = const_cast<Data *>(&shared_null.ba);
1358 d = static_cast<Data *>(qMalloc(sizeof(Data) + size + 1));
1363 d->capacityReserved = false;
1365 memset(d->data(), ch, size);
1366 d->data()[size] = '\0';
1373 Constructs a byte array of size \a size with uninitialized contents.
1376 QByteArray::QByteArray(int size, Qt::Initialization)
1378 d = static_cast<Data *>(qMalloc(sizeof(Data) + size + 1));
1383 d->capacityReserved = false;
1385 d->data()[size] = '\0';
1389 Sets the size of the byte array to \a size bytes.
1391 If \a size is greater than the current size, the byte array is
1392 extended to make it \a size bytes with the extra bytes added to
1393 the end. The new bytes are uninitialized.
1395 If \a size is less than the current size, bytes are removed from
1398 \sa size(), truncate()
1401 void QByteArray::resize(int size)
1406 if (d->offset && d->ref == 1 && size < d->size) {
1411 if (size == 0 && !d->capacityReserved) {
1412 Data *x = const_cast<Data *>(&shared_empty.ba);
1413 if (!d->ref.deref())
1416 } else if (d == &shared_null.ba || d == &shared_empty.ba) {
1418 // Optimize the idiom:
1422 // which is used in place of the Qt 3 idiom:
1423 // QByteArray a(sz);
1425 Data *x = static_cast<Data *>(qMalloc(sizeof(Data) + size + 1));
1430 x->capacityReserved = false;
1432 x->data()[size] = '\0';
1435 if (d->ref != 1 || size > int(d->alloc)
1436 || (!d->capacityReserved && size < d->size && size < int(d->alloc) >> 1))
1437 realloc(qAllocMore(size, sizeof(Data)));
1438 if (int(d->alloc) >= size) {
1440 d->data()[size] = '\0';
1446 Sets every byte in the byte array to character \a ch. If \a size
1447 is different from -1 (the default), the byte array is resized to
1448 size \a size beforehand.
1451 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 14
1456 QByteArray &QByteArray::fill(char ch, int size)
1458 resize(size < 0 ? d->size : size);
1460 memset(d->data(), ch, d->size);
1464 void QByteArray::realloc(int alloc)
1466 if (d->ref != 1 || d->offset) {
1467 Data *x = static_cast<Data *>(qMalloc(sizeof(Data) + alloc + 1));
1470 x->size = qMin(alloc, d->size);
1472 x->capacityReserved = d->capacityReserved;
1474 ::memcpy(x->data(), d->data(), x->size);
1475 x->data()[x->size] = '\0';
1476 if (!d->ref.deref())
1480 Data *x = static_cast<Data *>(qRealloc(d, sizeof(Data) + alloc + 1));
1488 void QByteArray::expand(int i)
1490 resize(qMax(i + 1, d->size));
1495 Return a QByteArray that is sure to be NUL-terminated.
1497 By default, all QByteArray have an extra NUL at the end,
1498 guaranteeing that assumption. However, if QByteArray::fromRawData
1499 is used, then the NUL is there only if the user put it there. We
1502 QByteArray QByteArray::nulTerminated() const
1504 // is this fromRawData?
1506 return *this; // no, then we're sure we're zero terminated
1508 QByteArray copy(*this);
1514 Prepends the byte array \a ba to this byte array and returns a
1515 reference to this byte array.
1518 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 15
1520 This is the same as insert(0, \a ba).
1522 Note: QByteArray is an \l{implicitly shared} class. Consequently,
1523 if \e this is an empty QByteArray, then \e this will just share
1524 the data held in \a ba. In this case, no copying of data is done,
1525 taking \l{constant time}. If a shared instance is modified, it will
1526 be copied (copy-on-write), taking \l{linear time}.
1528 If \e this is not an empty QByteArray, a deep copy of the data is
1529 performed, taking \l{linear time}.
1531 \sa append(), insert()
1534 QByteArray &QByteArray::prepend(const QByteArray &ba)
1536 if ((d == &shared_null.ba || d == &shared_empty.ba) && !IS_RAW_DATA(ba.d)) {
1538 } else if (ba.d != &shared_null.ba) {
1539 QByteArray tmp = *this;
1549 Prepends the string \a str to this byte array.
1552 QByteArray &QByteArray::prepend(const char *str)
1554 return prepend(str, qstrlen(str));
1561 Prepends \a len bytes of the string \a str to this byte array.
1564 QByteArray &QByteArray::prepend(const char *str, int len)
1567 if (d->ref != 1 || d->size + len > int(d->alloc))
1568 realloc(qAllocMore(d->size + len, sizeof(Data)));
1569 memmove(d->data()+len, d->data(), d->size);
1570 memcpy(d->data(), str, len);
1572 d->data()[d->size] = '\0';
1580 Prepends the character \a ch to this byte array.
1583 QByteArray &QByteArray::prepend(char ch)
1585 if (d->ref != 1 || d->size + 1 > int(d->alloc))
1586 realloc(qAllocMore(d->size + 1, sizeof(Data)));
1587 memmove(d->data()+1, d->data(), d->size);
1590 d->data()[d->size] = '\0';
1595 Appends the byte array \a ba onto the end of this byte array.
1598 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 16
1600 This is the same as insert(size(), \a ba).
1602 Note: QByteArray is an \l{implicitly shared} class. Consequently,
1603 if \e this is an empty QByteArray, then \e this will just share
1604 the data held in \a ba. In this case, no copying of data is done,
1605 taking \l{constant time}. If a shared instance is modified, it will
1606 be copied (copy-on-write), taking \l{linear time}.
1608 If \e this is not an empty QByteArray, a deep copy of the data is
1609 performed, taking \l{linear time}.
1611 This operation typically does not suffer from allocation overhead,
1612 because QByteArray preallocates extra space at the end of the data
1613 so that it may grow without reallocating for each append operation.
1615 \sa operator+=(), prepend(), insert()
1618 QByteArray &QByteArray::append(const QByteArray &ba)
1620 if ((d == &shared_null.ba || d == &shared_empty.ba) && !IS_RAW_DATA(ba.d)) {
1622 } else if (ba.d != &shared_null.ba) {
1623 if (d->ref != 1 || d->size + ba.d->size > int(d->alloc))
1624 realloc(qAllocMore(d->size + ba.d->size, sizeof(Data)));
1625 memcpy(d->data() + d->size, ba.d->data(), ba.d->size);
1626 d->size += ba.d->size;
1627 d->data()[d->size] = '\0';
1632 /*! \fn QByteArray &QByteArray::append(const QString &str)
1636 Appends the string \a str to this byte array. The Unicode data is
1637 converted into 8-bit characters using QString::toAscii().
1639 If the QString contains non-ASCII Unicode characters, using this
1640 function can lead to loss of information. You can disable this
1641 function by defining \c QT_NO_CAST_TO_ASCII when you compile your
1642 applications. You then need to call QString::toAscii() (or
1643 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
1644 explicitly if you want to convert the data to \c{const char *}.
1650 Appends the string \a str to this byte array.
1653 QByteArray& QByteArray::append(const char *str)
1656 int len = qstrlen(str);
1657 if (d->ref != 1 || d->size + len > int(d->alloc))
1658 realloc(qAllocMore(d->size + len, sizeof(Data)));
1659 memcpy(d->data() + d->size, str, len + 1); // include null terminator
1668 Appends the first \a len characters of the string \a str to this byte
1669 array and returns a reference to this byte array.
1671 If \a len is negative, the length of the string will be determined
1672 automatically using qstrlen(). If \a len is zero or \a str is
1673 null, nothing is appended to the byte array. Ensure that \a len is
1674 \e not longer than \a str.
1677 QByteArray &QByteArray::append(const char *str, int len)
1682 if (d->ref != 1 || d->size + len > int(d->alloc))
1683 realloc(qAllocMore(d->size + len, sizeof(Data)));
1684 memcpy(d->data() + d->size, str, len); // include null terminator
1686 d->data()[d->size] = '\0';
1694 Appends the character \a ch to this byte array.
1697 QByteArray& QByteArray::append(char ch)
1699 if (d->ref != 1 || d->size + 1 > int(d->alloc))
1700 realloc(qAllocMore(d->size + 1, sizeof(Data)));
1701 d->data()[d->size++] = ch;
1702 d->data()[d->size] = '\0';
1708 Inserts \a len bytes from the array \a arr at position \a pos and returns a
1709 reference the modified byte array.
1711 static inline QByteArray &qbytearray_insert(QByteArray *ba,
1712 int pos, const char *arr, int len)
1716 if (pos < 0 || len <= 0 || arr == 0)
1719 int oldsize = ba->size();
1720 ba->resize(qMax(pos, oldsize) + len);
1721 char *dst = ba->data();
1723 ::memset(dst + oldsize, 0x20, pos - oldsize);
1725 ::memmove(dst + pos + len, dst + pos, oldsize - pos);
1726 memcpy(dst + pos, arr, len);
1731 Inserts the byte array \a ba at index position \a i and returns a
1732 reference to this byte array.
1735 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 17
1737 \sa append(), prepend(), replace(), remove()
1740 QByteArray &QByteArray::insert(int i, const QByteArray &ba)
1742 QByteArray copy(ba);
1743 return qbytearray_insert(this, i, copy.d->data(), copy.d->size);
1747 \fn QByteArray &QByteArray::insert(int i, const QString &str)
1751 Inserts the string \a str at index position \a i in the byte
1752 array. The Unicode data is converted into 8-bit characters using
1755 If \a i is greater than size(), the array is first extended using
1758 If the QString contains non-ASCII Unicode characters, using this
1759 function can lead to loss of information. You can disable this
1760 function by defining \c QT_NO_CAST_TO_ASCII when you compile your
1761 applications. You then need to call QString::toAscii() (or
1762 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
1763 explicitly if you want to convert the data to \c{const char *}.
1769 Inserts the string \a str at position \a i in the byte array.
1771 If \a i is greater than size(), the array is first extended using
1775 QByteArray &QByteArray::insert(int i, const char *str)
1777 return qbytearray_insert(this, i, str, qstrlen(str));
1784 Inserts \a len bytes of the string \a str at position
1785 \a i in the byte array.
1787 If \a i is greater than size(), the array is first extended using
1791 QByteArray &QByteArray::insert(int i, const char *str, int len)
1793 return qbytearray_insert(this, i, str, len);
1799 Inserts character \a ch at index position \a i in the byte array.
1800 If \a i is greater than size(), the array is first extended using
1804 QByteArray &QByteArray::insert(int i, char ch)
1806 return qbytearray_insert(this, i, &ch, 1);
1810 Removes \a len bytes from the array, starting at index position \a
1811 pos, and returns a reference to the array.
1813 If \a pos is out of range, nothing happens. If \a pos is valid,
1814 but \a pos + \a len is larger than the size of the array, the
1815 array is truncated at position \a pos.
1818 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 18
1820 \sa insert(), replace()
1823 QByteArray &QByteArray::remove(int pos, int len)
1825 if (len <= 0 || pos >= d->size || pos < 0)
1828 if (pos + len >= d->size) {
1831 memmove(d->data() + pos, d->data() + pos + len, d->size - pos - len);
1832 resize(d->size - len);
1838 Replaces \a len bytes from index position \a pos with the byte
1839 array \a after, and returns a reference to this byte array.
1842 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 19
1844 \sa insert(), remove()
1847 QByteArray &QByteArray::replace(int pos, int len, const QByteArray &after)
1849 if (len == after.d->size && (pos + len <= d->size)) {
1851 memmove(d->data() + pos, after.d->data(), len*sizeof(char));
1854 QByteArray copy(after);
1857 return insert(pos, copy);
1861 /*! \fn QByteArray &QByteArray::replace(int pos, int len, const char *after)
1865 Replaces \a len bytes from index position \a pos with the zero terminated
1868 Notice: this can change the length of the byte array.
1870 QByteArray &QByteArray::replace(int pos, int len, const char *after)
1872 return replace(pos,len,after,qstrlen(after));
1875 /*! \fn QByteArray &QByteArray::replace(int pos, int len, const char *after, int alen)
1879 Replaces \a len bytes from index position \a pos with \a alen bytes
1880 from the string \a after. \a after is allowed to have '\0' characters.
1884 QByteArray &QByteArray::replace(int pos, int len, const char *after, int alen)
1886 if (len == alen && (pos + len <= d->size)) {
1888 memcpy(d->data() + pos, after, len*sizeof(char));
1892 return qbytearray_insert(this, pos, after, alen);
1896 // ### optimize all other replace method, by offering
1897 // QByteArray::replace(const char *before, int blen, const char *after, int alen)
1902 Replaces every occurrence of the byte array \a before with the
1903 byte array \a after.
1906 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 20
1909 QByteArray &QByteArray::replace(const QByteArray &before, const QByteArray &after)
1911 if (isNull() || before.d == after.d)
1914 QByteArray aft = after;
1918 return replace(before.constData(), before.size(), aft.constData(), aft.size());
1922 \fn QByteArray &QByteArray::replace(const char *before, const QByteArray &after)
1925 Replaces every occurrence of the string \a before with the
1926 byte array \a after.
1929 QByteArray &QByteArray::replace(const char *c, const QByteArray &after)
1931 QByteArray aft = after;
1935 return replace(c, qstrlen(c), aft.constData(), aft.size());
1939 \fn QByteArray &QByteArray::replace(const char *before, int bsize, const char *after, int asize)
1942 Replaces every occurrence of the string \a before with the string \a after.
1943 Since the sizes of the strings are given by \a bsize and \a asize, they
1944 may contain zero characters and do not need to be zero-terminated.
1947 QByteArray &QByteArray::replace(const char *before, int bsize, const char *after, int asize)
1949 if (isNull() || (before == after && bsize == asize))
1952 // protect against before or after being part of this
1953 const char *a = after;
1954 const char *b = before;
1955 if (after >= d->data() && after < d->data() + d->size) {
1956 char *copy = (char *)malloc(asize);
1958 memcpy(copy, after, asize);
1961 if (before >= d->data() && before < d->data() + d->size) {
1962 char *copy = (char *)malloc(bsize);
1964 memcpy(copy, before, bsize);
1968 QByteArrayMatcher matcher(before, bsize);
1973 if (bsize == asize) {
1975 while ((index = matcher.indexIn(*this, index)) != -1) {
1976 memcpy(d + index, after, asize);
1980 } else if (asize < bsize) {
1984 while ((index = matcher.indexIn(*this, index)) != -1) {
1986 int msize = index - movestart;
1988 memmove(d + to, d + movestart, msize);
1995 memcpy(d + to, after, asize);
2003 int msize = len - movestart;
2005 memmove(d + to, d + movestart, msize);
2006 resize(len - num*(bsize-asize));
2009 // the most complex case. We don't want to lose performance by doing repeated
2010 // copies and reallocs of the string.
2011 while (index != -1) {
2015 index = matcher.indexIn(*this, index);
2018 indices[pos++] = index;
2020 // avoid infinite loop
2027 // we have a table of replacement positions, use them for fast replacing
2028 int adjust = pos*(asize-bsize);
2029 // index has to be adjusted in case we get back into the loop above.
2032 int newlen = len + adjust;
2038 d = this->d->data();
2042 int movestart = indices[pos] + bsize;
2043 int insertstart = indices[pos] + pos*(asize-bsize);
2044 int moveto = insertstart + asize;
2045 memmove(d + moveto, d + movestart, (moveend - movestart));
2047 memcpy(d + insertstart, after, asize);
2048 moveend = movestart - bsize;
2064 \fn QByteArray &QByteArray::replace(const QByteArray &before, const char *after)
2067 Replaces every occurrence of the byte array \a before with the
2071 /*! \fn QByteArray &QByteArray::replace(const QString &before, const QByteArray &after)
2075 Replaces every occurrence of the string \a before with the byte
2076 array \a after. The Unicode data is converted into 8-bit
2077 characters using QString::toAscii().
2079 If the QString contains non-ASCII Unicode characters, using this
2080 function can lead to loss of information. You can disable this
2081 function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2082 applications. You then need to call QString::toAscii() (or
2083 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2084 explicitly if you want to convert the data to \c{const char *}.
2087 /*! \fn QByteArray &QByteArray::replace(const QString &before, const char *after)
2090 Replaces every occurrence of the string \a before with the string
2094 /*! \fn QByteArray &QByteArray::replace(const char *before, const char *after)
2098 Replaces every occurrence of the string \a before with the string
2105 Replaces every occurrence of the character \a before with the
2106 byte array \a after.
2109 QByteArray &QByteArray::replace(char before, const QByteArray &after)
2111 char b[2] = { before, '\0' };
2112 QByteArray cb = fromRawData(b, 1);
2113 return replace(cb, after);
2116 /*! \fn QByteArray &QByteArray::replace(char before, const QString &after)
2120 Replaces every occurrence of the character \a before with the
2121 string \a after. The Unicode data is converted into 8-bit
2122 characters using QString::toAscii().
2124 If the QString contains non-ASCII Unicode characters, using this
2125 function can lead to loss of information. You can disable this
2126 function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2127 applications. You then need to call QString::toAscii() (or
2128 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2129 explicitly if you want to convert the data to \c{const char *}.
2132 /*! \fn QByteArray &QByteArray::replace(char before, const char *after)
2136 Replaces every occurrence of the character \a before with the
2143 Replaces every occurrence of the character \a before with the
2147 QByteArray &QByteArray::replace(char before, char after)
2151 char *e = i + d->size;
2160 Splits the byte array into subarrays wherever \a sep occurs, and
2161 returns the list of those arrays. If \a sep does not match
2162 anywhere in the byte array, split() returns a single-element list
2163 containing this byte array.
2166 QList<QByteArray> QByteArray::split(char sep) const
2168 QList<QByteArray> list;
2171 while ((end = indexOf(sep, start)) != -1) {
2172 list.append(mid(start, end - start));
2175 list.append(mid(start));
2182 Returns a copy of this byte array repeated the specified number of \a times.
2184 If \a times is less than 1, an empty byte array is returned.
2189 QByteArray ba("ab");
2190 ba.repeated(4); // returns "abababab"
2193 QByteArray QByteArray::repeated(int times) const
2201 return QByteArray();
2204 const int resultSize = times * d->size;
2207 result.reserve(resultSize);
2208 if (int(result.d->alloc) != resultSize)
2209 return QByteArray(); // not enough memory
2211 memcpy(result.d->data(), d->data(), d->size);
2213 int sizeSoFar = d->size;
2214 char *end = result.d->data() + sizeSoFar;
2216 const int halfResultSize = resultSize >> 1;
2217 while (sizeSoFar <= halfResultSize) {
2218 memcpy(end, result.d->data(), sizeSoFar);
2222 memcpy(end, result.d->data(), resultSize - sizeSoFar);
2223 result.d->data()[resultSize] = '\0';
2224 result.d->size = resultSize;
2229 if (ol_minus_1 < sizeof(uint) * CHAR_BIT) \
2230 hashHaystack -= (a) << ol_minus_1; \
2234 Returns the index position of the first occurrence of the byte
2235 array \a ba in this byte array, searching forward from index
2236 position \a from. Returns -1 if \a ba could not be found.
2239 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 21
2241 \sa lastIndexOf(), contains(), count()
2244 int QByteArray::indexOf(const QByteArray &ba, int from) const
2246 const int ol = ba.d->size;
2250 return indexOf(*ba.d->data(), from);
2252 const int l = d->size;
2253 if (from > d->size || ol + from > l)
2256 return qFindByteArray(d->data(), d->size, from, ba.d->data(), ol);
2259 /*! \fn int QByteArray::indexOf(const QString &str, int from) const
2263 Returns the index position of the first occurrence of the string
2264 \a str in the byte array, searching forward from index position
2265 \a from. Returns -1 if \a str could not be found.
2267 The Unicode data is converted into 8-bit characters using
2270 If the QString contains non-ASCII Unicode characters, using this
2271 function can lead to loss of information. You can disable this
2272 function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2273 applications. You then need to call QString::toAscii() (or
2274 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2275 explicitly if you want to convert the data to \c{const char *}.
2278 /*! \fn int QByteArray::indexOf(const char *str, int from) const
2282 Returns the index position of the first occurrence of the string
2283 \a str in the byte array, searching forward from index position \a
2284 from. Returns -1 if \a str could not be found.
2286 int QByteArray::indexOf(const char *c, int from) const
2288 const int ol = qstrlen(c);
2290 return indexOf(*c, from);
2292 const int l = d->size;
2293 if (from > d->size || ol + from > l)
2298 return qFindByteArray(d->data(), d->size, from, c, ol);
2304 Returns the index position of the first occurrence of the
2305 character \a ch in the byte array, searching forward from index
2306 position \a from. Returns -1 if \a ch could not be found.
2309 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 22
2311 \sa lastIndexOf(), contains()
2314 int QByteArray::indexOf(char ch, int from) const
2317 from = qMax(from + d->size, 0);
2318 if (from < d->size) {
2319 const char *n = d->data() + from - 1;
2320 const char *e = d->data() + d->size;
2323 return n - d->data();
2329 static int lastIndexOfHelper(const char *haystack, int l, const char *needle, int ol, int from)
2334 if (from < 0 || from > l)
2339 const char *end = haystack;
2341 const uint ol_minus_1 = ol - 1;
2342 const char *n = needle + ol_minus_1;
2343 const char *h = haystack + ol_minus_1;
2344 uint hashNeedle = 0, hashHaystack = 0;
2346 for (idx = 0; idx < ol; ++idx) {
2347 hashNeedle = ((hashNeedle<<1) + *(n-idx));
2348 hashHaystack = ((hashHaystack<<1) + *(h-idx));
2350 hashHaystack -= *haystack;
2351 while (haystack >= end) {
2352 hashHaystack += *haystack;
2353 if (hashHaystack == hashNeedle && memcmp(needle, haystack, ol) == 0)
2354 return haystack - end;
2356 REHASH(*(haystack + ol));
2363 \fn int QByteArray::lastIndexOf(const QByteArray &ba, int from) const
2365 Returns the index position of the last occurrence of the byte
2366 array \a ba in this byte array, searching backward from index
2367 position \a from. If \a from is -1 (the default), the search
2368 starts at the last byte. Returns -1 if \a ba could not be found.
2371 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 23
2373 \sa indexOf(), contains(), count()
2376 int QByteArray::lastIndexOf(const QByteArray &ba, int from) const
2378 const int ol = ba.d->size;
2380 return lastIndexOf(*ba.d->data(), from);
2382 return lastIndexOfHelper(d->data(), d->size, ba.d->data(), ol, from);
2385 /*! \fn int QByteArray::lastIndexOf(const QString &str, int from) const
2389 Returns the index position of the last occurrence of the string \a
2390 str in the byte array, searching backward from index position \a
2391 from. If \a from is -1 (the default), the search starts at the
2392 last (size() - 1) byte. Returns -1 if \a str could not be found.
2394 The Unicode data is converted into 8-bit characters using
2397 If the QString contains non-ASCII Unicode characters, using this
2398 function can lead to loss of information. You can disable this
2399 function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2400 applications. You then need to call QString::toAscii() (or
2401 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2402 explicitly if you want to convert the data to \c{const char *}.
2405 /*! \fn int QByteArray::lastIndexOf(const char *str, int from) const
2408 Returns the index position of the last occurrence of the string \a
2409 str in the byte array, searching backward from index position \a
2410 from. If \a from is -1 (the default), the search starts at the
2411 last (size() - 1) byte. Returns -1 if \a str could not be found.
2413 int QByteArray::lastIndexOf(const char *str, int from) const
2415 const int ol = qstrlen(str);
2417 return lastIndexOf(*str, from);
2419 return lastIndexOfHelper(d->data(), d->size, str, ol, from);
2425 Returns the index position of the last occurrence of character \a
2426 ch in the byte array, searching backward from index position \a
2427 from. If \a from is -1 (the default), the search starts at the
2428 last (size() - 1) byte. Returns -1 if \a ch could not be found.
2431 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 24
2433 \sa indexOf(), contains()
2436 int QByteArray::lastIndexOf(char ch, int from) const
2440 else if (from > d->size)
2443 const char *b = d->data();
2444 const char *n = d->data() + from + 1;
2453 Returns the number of (potentially overlapping) occurrences of
2454 byte array \a ba in this byte array.
2456 \sa contains(), indexOf()
2459 int QByteArray::count(const QByteArray &ba) const
2463 if (d->size > 500 && ba.d->size > 5) {
2464 QByteArrayMatcher matcher(ba);
2465 while ((i = matcher.indexIn(*this, i + 1)) != -1)
2468 while ((i = indexOf(ba, i + 1)) != -1)
2477 Returns the number of (potentially overlapping) occurrences of
2478 string \a str in the byte array.
2481 int QByteArray::count(const char *str) const
2483 return count(fromRawData(str, qstrlen(str)));
2489 Returns the number of occurrences of character \a ch in the byte
2492 \sa contains(), indexOf()
2495 int QByteArray::count(char ch) const
2498 const char *i = d->data() + d->size;
2499 const char *b = d->data();
2506 /*! \fn int QByteArray::count() const
2514 Returns true if this byte array starts with byte array \a ba;
2515 otherwise returns false.
2518 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 25
2520 \sa endsWith(), left()
2522 bool QByteArray::startsWith(const QByteArray &ba) const
2524 if (d == ba.d || ba.d->size == 0)
2526 if (d->size < ba.d->size)
2528 return memcmp(d->data(), ba.d->data(), ba.d->size) == 0;
2533 Returns true if this byte array starts with string \a str;
2534 otherwise returns false.
2536 bool QByteArray::startsWith(const char *str) const
2540 int len = qstrlen(str);
2543 return qstrncmp(d->data(), str, len) == 0;
2548 Returns true if this byte array starts with character \a ch;
2549 otherwise returns false.
2551 bool QByteArray::startsWith(char ch) const
2555 return d->data()[0] == ch;
2559 Returns true if this byte array ends with byte array \a ba;
2560 otherwise returns false.
2563 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 26
2565 \sa startsWith(), right()
2567 bool QByteArray::endsWith(const QByteArray &ba) const
2569 if (d == ba.d || ba.d->size == 0)
2571 if (d->size < ba.d->size)
2573 return memcmp(d->data() + d->size - ba.d->size, ba.d->data(), ba.d->size) == 0;
2578 Returns true if this byte array ends with string \a str; otherwise
2581 bool QByteArray::endsWith(const char *str) const
2585 int len = qstrlen(str);
2588 return qstrncmp(d->data() + d->size - len, str, len) == 0;
2593 Returns true if this byte array ends with character \a ch;
2594 otherwise returns false.
2596 bool QByteArray::endsWith(char ch) const
2600 return d->data()[d->size - 1] == ch;
2604 Returns a byte array that contains the leftmost \a len bytes of
2607 The entire byte array is returned if \a len is greater than
2611 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 27
2613 \sa right(), mid(), startsWith(), truncate()
2616 QByteArray QByteArray::left(int len) const
2622 return QByteArray(d->data(), len);
2626 Returns a byte array that contains the rightmost \a len bytes of
2629 The entire byte array is returned if \a len is greater than
2633 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 28
2635 \sa endsWith(), left(), mid()
2638 QByteArray QByteArray::right(int len) const
2644 return QByteArray(d->data() + d->size - len, len);
2648 Returns a byte array containing \a len bytes from this byte array,
2649 starting at position \a pos.
2651 If \a len is -1 (the default), or \a pos + \a len >= size(),
2652 returns a byte array containing all bytes starting at position \a
2653 pos until the end of the byte array.
2656 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 29
2661 QByteArray QByteArray::mid(int pos, int len) const
2663 if (d == &shared_null.ba || d == &shared_empty.ba || pos >= d->size)
2664 return QByteArray();
2666 len = d->size - pos;
2671 if (len + pos > d->size)
2672 len = d->size - pos;
2673 if (pos == 0 && len == d->size)
2675 return QByteArray(d->data() + pos, len);
2679 Returns a lowercase copy of the byte array. The bytearray is
2680 interpreted as a Latin-1 encoded string.
2683 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 30
2685 \sa toUpper(), {8-bit Character Comparisons}
2687 QByteArray QByteArray::toLower() const
2689 QByteArray s(*this);
2690 register uchar *p = reinterpret_cast<uchar *>(s.data());
2693 *p = QChar::toLower((ushort)*p);
2701 Returns an uppercase copy of the byte array. The bytearray is
2702 interpreted as a Latin-1 encoded string.
2705 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 31
2707 \sa toLower(), {8-bit Character Comparisons}
2710 QByteArray QByteArray::toUpper() const
2712 QByteArray s(*this);
2713 register uchar *p = reinterpret_cast<uchar *>(s.data());
2716 *p = QChar::toUpper((ushort)*p);
2723 /*! \fn void QByteArray::clear()
2725 Clears the contents of the byte array and makes it empty.
2727 \sa resize(), isEmpty()
2730 void QByteArray::clear()
2732 if (!d->ref.deref())
2734 d = const_cast<Data *>(&shared_null.ba);
2738 #if !defined(QT_NO_DATASTREAM) || (defined(QT_BOOTSTRAPPED) && !defined(QT_BUILD_QMAKE))
2740 /*! \relates QByteArray
2742 Writes byte array \a ba to the stream \a out and returns a reference
2745 \sa {Serializing Qt Data Types}
2748 QDataStream &operator<<(QDataStream &out, const QByteArray &ba)
2750 if (ba.isNull() && out.version() >= 6) {
2751 out << (quint32)0xffffffff;
2754 return out.writeBytes(ba, ba.size());
2757 /*! \relates QByteArray
2759 Reads a byte array into \a ba from the stream \a in and returns a
2760 reference to the stream.
2762 \sa {Serializing Qt Data Types}
2765 QDataStream &operator>>(QDataStream &in, QByteArray &ba)
2770 if (len == 0xffffffff)
2773 const quint32 Step = 1024 * 1024;
2774 quint32 allocated = 0;
2777 int blockSize = qMin(Step, len - allocated);
2778 ba.resize(allocated + blockSize);
2779 if (in.readRawData(ba.data() + allocated, blockSize) != blockSize) {
2781 in.setStatus(QDataStream::ReadPastEnd);
2784 allocated += blockSize;
2785 } while (allocated < len);
2789 #endif // QT_NO_DATASTREAM
2791 /*! \fn bool QByteArray::operator==(const QString &str) const
2793 Returns true if this byte array is equal to string \a str;
2794 otherwise returns false.
2796 The Unicode data is converted into 8-bit characters using
2799 The comparison is case sensitive.
2801 You can disable this operator by defining \c
2802 QT_NO_CAST_FROM_ASCII when you compile your applications. You
2803 then need to call QString::fromAscii(), QString::fromLatin1(),
2804 QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2805 you want to convert the byte array to a QString before doing the
2809 /*! \fn bool QByteArray::operator!=(const QString &str) const
2811 Returns true if this byte array is not equal to string \a str;
2812 otherwise returns false.
2814 The Unicode data is converted into 8-bit characters using
2817 The comparison is case sensitive.
2819 You can disable this operator by defining \c
2820 QT_NO_CAST_FROM_ASCII when you compile your applications. You
2821 then need to call QString::fromAscii(), QString::fromLatin1(),
2822 QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2823 you want to convert the byte array to a QString before doing the
2827 /*! \fn bool QByteArray::operator<(const QString &str) const
2829 Returns true if this byte array is lexically less than string \a
2830 str; otherwise returns false.
2832 The Unicode data is converted into 8-bit characters using
2835 The comparison is case sensitive.
2837 You can disable this operator by defining \c
2838 QT_NO_CAST_FROM_ASCII when you compile your applications. You
2839 then need to call QString::fromAscii(), QString::fromLatin1(),
2840 QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2841 you want to convert the byte array to a QString before doing the
2845 /*! \fn bool QByteArray::operator>(const QString &str) const
2847 Returns true if this byte array is lexically greater than string
2848 \a str; otherwise returns false.
2850 The Unicode data is converted into 8-bit characters using
2853 The comparison is case sensitive.
2855 You can disable this operator by defining \c
2856 QT_NO_CAST_FROM_ASCII when you compile your applications. You
2857 then need to call QString::fromAscii(), QString::fromLatin1(),
2858 QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2859 you want to convert the byte array to a QString before doing the
2863 /*! \fn bool QByteArray::operator<=(const QString &str) const
2865 Returns true if this byte array is lexically less than or equal
2866 to string \a str; otherwise returns false.
2868 The Unicode data is converted into 8-bit characters using
2871 The comparison is case sensitive.
2873 You can disable this operator by defining \c
2874 QT_NO_CAST_FROM_ASCII when you compile your applications. You
2875 then need to call QString::fromAscii(), QString::fromLatin1(),
2876 QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2877 you want to convert the byte array to a QString before doing the
2881 /*! \fn bool QByteArray::operator>=(const QString &str) const
2883 Returns true if this byte array is greater than or equal to string
2884 \a str; otherwise returns false.
2886 The Unicode data is converted into 8-bit characters using
2889 The comparison is case sensitive.
2891 You can disable this operator by defining \c
2892 QT_NO_CAST_FROM_ASCII when you compile your applications. You
2893 then need to call QString::fromAscii(), QString::fromLatin1(),
2894 QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2895 you want to convert the byte array to a QString before doing the
2899 /*! \fn bool operator==(const QByteArray &a1, const QByteArray &a2)
2904 Returns true if byte array \a a1 is equal to byte array \a a2;
2905 otherwise returns false.
2908 /*! \fn bool operator==(const QByteArray &a1, const char *a2)
2913 Returns true if byte array \a a1 is equal to string \a a2;
2914 otherwise returns false.
2917 /*! \fn bool operator==(const char *a1, const QByteArray &a2)
2922 Returns true if string \a a1 is equal to byte array \a a2;
2923 otherwise returns false.
2926 /*! \fn bool operator!=(const QByteArray &a1, const QByteArray &a2)
2931 Returns true if byte array \a a1 is not equal to byte array \a a2;
2932 otherwise returns false.
2935 /*! \fn bool operator!=(const QByteArray &a1, const char *a2)
2940 Returns true if byte array \a a1 is not equal to string \a a2;
2941 otherwise returns false.
2944 /*! \fn bool operator!=(const char *a1, const QByteArray &a2)
2949 Returns true if string \a a1 is not equal to byte array \a a2;
2950 otherwise returns false.
2953 /*! \fn bool operator<(const QByteArray &a1, const QByteArray &a2)
2958 Returns true if byte array \a a1 is lexically less than byte array
2959 \a a2; otherwise returns false.
2962 /*! \fn inline bool operator<(const QByteArray &a1, const char *a2)
2967 Returns true if byte array \a a1 is lexically less than string
2968 \a a2; otherwise returns false.
2971 /*! \fn bool operator<(const char *a1, const QByteArray &a2)
2976 Returns true if string \a a1 is lexically less than byte array
2977 \a a2; otherwise returns false.
2980 /*! \fn bool operator<=(const QByteArray &a1, const QByteArray &a2)
2985 Returns true if byte array \a a1 is lexically less than or equal
2986 to byte array \a a2; otherwise returns false.
2989 /*! \fn bool operator<=(const QByteArray &a1, const char *a2)
2994 Returns true if byte array \a a1 is lexically less than or equal
2995 to string \a a2; otherwise returns false.
2998 /*! \fn bool operator<=(const char *a1, const QByteArray &a2)
3003 Returns true if string \a a1 is lexically less than or equal
3004 to byte array \a a2; otherwise returns false.
3007 /*! \fn bool operator>(const QByteArray &a1, const QByteArray &a2)
3012 Returns true if byte array \a a1 is lexically greater than byte
3013 array \a a2; otherwise returns false.
3016 /*! \fn bool operator>(const QByteArray &a1, const char *a2)
3021 Returns true if byte array \a a1 is lexically greater than string
3022 \a a2; otherwise returns false.
3025 /*! \fn bool operator>(const char *a1, const QByteArray &a2)
3030 Returns true if string \a a1 is lexically greater than byte array
3031 \a a2; otherwise returns false.
3034 /*! \fn bool operator>=(const QByteArray &a1, const QByteArray &a2)
3039 Returns true if byte array \a a1 is lexically greater than or
3040 equal to byte array \a a2; otherwise returns false.
3043 /*! \fn bool operator>=(const QByteArray &a1, const char *a2)
3048 Returns true if byte array \a a1 is lexically greater than or
3049 equal to string \a a2; otherwise returns false.
3052 /*! \fn bool operator>=(const char *a1, const QByteArray &a2)
3057 Returns true if string \a a1 is lexically greater than or
3058 equal to byte array \a a2; otherwise returns false.
3061 /*! \fn const QByteArray operator+(const QByteArray &a1, const QByteArray &a2)
3064 Returns a byte array that is the result of concatenating byte
3065 array \a a1 and byte array \a a2.
3067 \sa QByteArray::operator+=()
3070 /*! \fn const QByteArray operator+(const QByteArray &a1, const char *a2)
3075 Returns a byte array that is the result of concatenating byte
3076 array \a a1 and string \a a2.
3079 /*! \fn const QByteArray operator+(const QByteArray &a1, char a2)
3084 Returns a byte array that is the result of concatenating byte
3085 array \a a1 and character \a a2.
3088 /*! \fn const QByteArray operator+(const char *a1, const QByteArray &a2)
3093 Returns a byte array that is the result of concatenating string
3094 \a a1 and byte array \a a2.
3097 /*! \fn const QByteArray operator+(char a1, const QByteArray &a2)
3102 Returns a byte array that is the result of concatenating character
3103 \a a1 and byte array \a a2.
3107 Returns a byte array that has whitespace removed from the start
3108 and the end, and which has each sequence of internal whitespace
3109 replaced with a single space.
3111 Whitespace means any character for which the standard C++
3112 isspace() function returns true. This includes the ASCII
3113 characters '\\t', '\\n', '\\v', '\\f', '\\r', and ' '.
3116 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 32
3120 QByteArray QByteArray::simplified() const
3124 QByteArray result(d->size, Qt::Uninitialized);
3125 const char *from = d->data();
3126 const char *fromend = from + d->size;
3128 char *to = result.d->data();
3130 while (from!=fromend && isspace(uchar(*from)))
3132 while (from!=fromend && !isspace(uchar(*from)))
3133 to[outc++] = *from++;
3139 if (outc > 0 && to[outc-1] == ' ')
3141 result.resize(outc);
3146 Returns a byte array that has whitespace removed from the start
3149 Whitespace means any character for which the standard C++
3150 isspace() function returns true. This includes the ASCII
3151 characters '\\t', '\\n', '\\v', '\\f', '\\r', and ' '.
3154 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 33
3156 Unlike simplified(), trimmed() leaves internal whitespace alone.
3160 QByteArray QByteArray::trimmed() const
3164 const char *s = d->data();
3165 if (!isspace(uchar(*s)) && !isspace(uchar(s[d->size-1])))
3168 int end = d->size - 1;
3169 while (start<=end && isspace(uchar(s[start]))) // skip white space from start
3171 if (start <= end) { // only white space
3172 while (end && isspace(uchar(s[end]))) // skip white space from end
3175 int l = end - start + 1;
3177 return QByteArray(const_cast<Data *>(&shared_empty.ba), 0, 0);
3179 return QByteArray(s+start, l);
3183 Returns a byte array of size \a width that contains this byte
3184 array padded by the \a fill character.
3186 If \a truncate is false and the size() of the byte array is more
3187 than \a width, then the returned byte array is a copy of this byte
3190 If \a truncate is true and the size() of the byte array is more
3191 than \a width, then any bytes in a copy of the byte array
3192 after position \a width are removed, and the copy is returned.
3195 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 34
3197 \sa rightJustified()
3200 QByteArray QByteArray::leftJustified(int width, char fill, bool truncate) const
3204 int padlen = width - len;
3206 result.resize(len+padlen);
3208 memcpy(result.d->data(), d->data(), len);
3209 memset(result.d->data()+len, fill, padlen);
3212 result = left(width);
3220 Returns a byte array of size \a width that contains the \a fill
3221 character followed by this byte array.
3223 If \a truncate is false and the size of the byte array is more
3224 than \a width, then the returned byte array is a copy of this byte
3227 If \a truncate is true and the size of the byte array is more
3228 than \a width, then the resulting byte array is truncated at
3232 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 35
3237 QByteArray QByteArray::rightJustified(int width, char fill, bool truncate) const
3241 int padlen = width - len;
3243 result.resize(len+padlen);
3245 memcpy(result.d->data()+padlen, data(), len);
3246 memset(result.d->data(), fill, padlen);
3249 result = left(width);
3256 bool QByteArray::isNull() const { return d == &shared_null.ba; }
3260 Returns the byte array converted to a \c {long long} using base \a
3261 base, which is 10 by default and must be between 2 and 36, or 0.
3263 If \a base is 0, the base is determined automatically using the
3264 following rules: If the byte array begins with "0x", it is assumed to
3265 be hexadecimal; if it begins with "0", it is assumed to be octal;
3266 otherwise it is assumed to be decimal.
3268 Returns 0 if the conversion fails.
3270 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3271 false; otherwise *\a{ok} is set to true.
3273 \note The conversion of the number is performed in the default C locale,
3274 irrespective of the user's locale.
3279 qlonglong QByteArray::toLongLong(bool *ok, int base) const
3281 #if defined(QT_CHECK_RANGE)
3282 if (base != 0 && (base < 2 || base > 36)) {
3283 qWarning("QByteArray::toLongLong: Invalid base %d", base);
3288 return QLocalePrivate::bytearrayToLongLong(nulTerminated().constData(), base, ok);
3292 Returns the byte array converted to an \c {unsigned long long}
3293 using base \a base, which is 10 by default and must be between 2
3296 If \a base is 0, the base is determined automatically using the
3297 following rules: If the byte array begins with "0x", it is assumed to
3298 be hexadecimal; if it begins with "0", it is assumed to be octal;
3299 otherwise it is assumed to be decimal.
3301 Returns 0 if the conversion fails.
3303 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3304 false; otherwise *\a{ok} is set to true.
3306 \note The conversion of the number is performed in the default C locale,
3307 irrespective of the user's locale.
3312 qulonglong QByteArray::toULongLong(bool *ok, int base) const
3314 #if defined(QT_CHECK_RANGE)
3315 if (base != 0 && (base < 2 || base > 36)) {
3316 qWarning("QByteArray::toULongLong: Invalid base %d", base);
3321 return QLocalePrivate::bytearrayToUnsLongLong(nulTerminated().constData(), base, ok);
3326 Returns the byte array converted to an \c int using base \a
3327 base, which is 10 by default and must be between 2 and 36, or 0.
3329 If \a base is 0, the base is determined automatically using the
3330 following rules: If the byte array begins with "0x", it is assumed to
3331 be hexadecimal; if it begins with "0", it is assumed to be octal;
3332 otherwise it is assumed to be decimal.
3334 Returns 0 if the conversion fails.
3336 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3337 false; otherwise *\a{ok} is set to true.
3339 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 36
3341 \note The conversion of the number is performed in the default C locale,
3342 irrespective of the user's locale.
3347 int QByteArray::toInt(bool *ok, int base) const
3349 qlonglong v = toLongLong(ok, base);
3350 if (v < INT_MIN || v > INT_MAX) {
3359 Returns the byte array converted to an \c {unsigned int} using base \a
3360 base, which is 10 by default and must be between 2 and 36, or 0.
3362 If \a base is 0, the base is determined automatically using the
3363 following rules: If the byte array begins with "0x", it is assumed to
3364 be hexadecimal; if it begins with "0", it is assumed to be octal;
3365 otherwise it is assumed to be decimal.
3367 Returns 0 if the conversion fails.
3369 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3370 false; otherwise *\a{ok} is set to true.
3372 \note The conversion of the number is performed in the default C locale,
3373 irrespective of the user's locale.
3378 uint QByteArray::toUInt(bool *ok, int base) const
3380 qulonglong v = toULongLong(ok, base);
3392 Returns the byte array converted to a \c long int using base \a
3393 base, which is 10 by default and must be between 2 and 36, or 0.
3395 If \a base is 0, the base is determined automatically using the
3396 following rules: If the byte array begins with "0x", it is assumed to
3397 be hexadecimal; if it begins with "0", it is assumed to be octal;
3398 otherwise it is assumed to be decimal.
3400 Returns 0 if the conversion fails.
3402 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3403 false; otherwise *\a{ok} is set to true.
3405 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 37
3407 \note The conversion of the number is performed in the default C locale,
3408 irrespective of the user's locale.
3412 long QByteArray::toLong(bool *ok, int base) const
3414 qlonglong v = toLongLong(ok, base);
3415 if (v < LONG_MIN || v > LONG_MAX) {
3426 Returns the byte array converted to an \c {unsigned long int} using base \a
3427 base, which is 10 by default and must be between 2 and 36, or 0.
3429 If \a base is 0, the base is determined automatically using the
3430 following rules: If the byte array begins with "0x", it is assumed to
3431 be hexadecimal; if it begins with "0", it is assumed to be octal;
3432 otherwise it is assumed to be decimal.
3434 Returns 0 if the conversion fails.
3436 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3437 false; otherwise *\a{ok} is set to true.
3439 \note The conversion of the number is performed in the default C locale,
3440 irrespective of the user's locale.
3444 ulong QByteArray::toULong(bool *ok, int base) const
3446 qulonglong v = toULongLong(ok, base);
3447 if (v > ULONG_MAX) {
3456 Returns the byte array converted to a \c short using base \a
3457 base, which is 10 by default and must be between 2 and 36, or 0.
3459 If \a base is 0, the base is determined automatically using the
3460 following rules: If the byte array begins with "0x", it is assumed to
3461 be hexadecimal; if it begins with "0", it is assumed to be octal;
3462 otherwise it is assumed to be decimal.
3464 Returns 0 if the conversion fails.
3466 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3467 false; otherwise *\a{ok} is set to true.
3469 \note The conversion of the number is performed in the default C locale,
3470 irrespective of the user's locale.
3475 short QByteArray::toShort(bool *ok, int base) const
3477 qlonglong v = toLongLong(ok, base);
3478 if (v < SHRT_MIN || v > SHRT_MAX) {
3487 Returns the byte array converted to an \c {unsigned short} using base \a
3488 base, which is 10 by default and must be between 2 and 36, or 0.
3490 If \a base is 0, the base is determined automatically using the
3491 following rules: If the byte array begins with "0x", it is assumed to
3492 be hexadecimal; if it begins with "0", it is assumed to be octal;
3493 otherwise it is assumed to be decimal.
3495 Returns 0 if the conversion fails.
3497 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3498 false; otherwise *\a{ok} is set to true.
3500 \note The conversion of the number is performed in the default C locale,
3501 irrespective of the user's locale.
3506 ushort QByteArray::toUShort(bool *ok, int base) const
3508 qulonglong v = toULongLong(ok, base);
3509 if (v > USHRT_MAX) {
3519 Returns the byte array converted to a \c double value.
3521 Returns 0.0 if the conversion fails.
3523 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3524 false; otherwise *\a{ok} is set to true.
3526 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 38
3528 \note The conversion of the number is performed in the default C locale,
3529 irrespective of the user's locale.
3534 double QByteArray::toDouble(bool *ok) const
3536 return QLocalePrivate::bytearrayToDouble(nulTerminated().constData(), ok);
3540 Returns the byte array converted to a \c float value.
3542 Returns 0.0 if the conversion fails.
3544 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3545 false; otherwise *\a{ok} is set to true.
3547 \note The conversion of the number is performed in the default C locale,
3548 irrespective of the user's locale.
3553 float QByteArray::toFloat(bool *ok) const
3555 return float(toDouble(ok));
3559 Returns a copy of the byte array, encoded as Base64.
3561 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 39
3563 The algorithm used to encode Base64-encoded data is defined in \l{RFC 2045}.
3567 QByteArray QByteArray::toBase64() const
3569 const char alphabet[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
3570 "ghijklmn" "opqrstuv" "wxyz0123" "456789+/";
3571 const char padchar = '=';
3574 QByteArray tmp((d->size * 4) / 3 + 3, Qt::Uninitialized);
3577 char *out = tmp.data();
3578 while (i < d->size) {
3580 chunk |= int(uchar(d->data()[i++])) << 16;
3584 chunk |= int(uchar(d->data()[i++])) << 8;
3585 if (i == d->size) padlen = 1;
3586 else chunk |= int(uchar(d->data()[i++]));
3589 int j = (chunk & 0x00fc0000) >> 18;
3590 int k = (chunk & 0x0003f000) >> 12;
3591 int l = (chunk & 0x00000fc0) >> 6;
3592 int m = (chunk & 0x0000003f);
3593 *out++ = alphabet[j];
3594 *out++ = alphabet[k];
3595 if (padlen > 1) *out++ = padchar;
3596 else *out++ = alphabet[l];
3597 if (padlen > 0) *out++ = padchar;
3598 else *out++ = alphabet[m];
3601 tmp.truncate(out - tmp.data());
3606 \fn QByteArray &QByteArray::setNum(int n, int base)
3608 Sets the byte array to the printed value of \a n in base \a base (10
3609 by default) and returns a reference to the byte array. The \a base can
3610 be any value between 2 and 36.
3613 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 40
3615 \note The format of the number is not localized; the default C locale
3616 is used irrespective of the user's locale.
3618 \sa number(), toInt()
3622 \fn QByteArray &QByteArray::setNum(uint n, int base)
3629 \fn QByteArray &QByteArray::setNum(short n, int base)
3636 \fn QByteArray &QByteArray::setNum(ushort n, int base)
3648 QByteArray &QByteArray::setNum(qlonglong n, int base)
3650 #if defined(QT_CHECK_RANGE)
3651 if (base < 2 || base > 36) {
3652 qWarning("QByteArray::setNum: Invalid base %d", base);
3656 QLocale locale(QLocale::C);
3657 *this = locale.d()->longLongToString(n, -1, base).toLatin1();
3667 QByteArray &QByteArray::setNum(qulonglong n, int base)
3669 #if defined(QT_CHECK_RANGE)
3670 if (base < 2 || base > 36) {
3671 qWarning("QByteArray::setNum: Invalid base %d", base);
3675 QLocale locale(QLocale::C);
3676 *this = locale.d()->unsLongLongToString(n, -1, base).toLatin1();
3683 Sets the byte array to the printed value of \a n, formatted in format
3684 \a f with precision \a prec, and returns a reference to the
3687 The format \a f can be any of the following:
3690 \header \i Format \i Meaning
3691 \row \i \c e \i format as [-]9.9e[+|-]999
3692 \row \i \c E \i format as [-]9.9E[+|-]999
3693 \row \i \c f \i format as [-]9.9
3694 \row \i \c g \i use \c e or \c f format, whichever is the most concise
3695 \row \i \c G \i use \c E or \c f format, whichever is the most concise
3698 With 'e', 'E', and 'f', \a prec is the number of digits after the
3699 decimal point. With 'g' and 'G', \a prec is the maximum number of
3700 significant digits (trailing zeroes are omitted).
3702 \note The format of the number is not localized; the default C locale
3703 is used irrespective of the user's locale.
3708 QByteArray &QByteArray::setNum(double n, char f, int prec)
3710 QLocalePrivate::DoubleForm form = QLocalePrivate::DFDecimal;
3714 flags = QLocalePrivate::CapitalEorX;
3719 form = QLocalePrivate::DFDecimal;
3722 form = QLocalePrivate::DFExponent;
3725 form = QLocalePrivate::DFSignificantDigits;
3728 #if defined(QT_CHECK_RANGE)
3729 qWarning("QByteArray::setNum: Invalid format char '%c'", f);
3734 QLocale locale(QLocale::C);
3735 *this = locale.d()->doubleToString(n, prec, form, -1, flags).toLatin1();
3740 \fn QByteArray &QByteArray::setNum(float n, char f, int prec)
3743 Sets the byte array to the printed value of \a n, formatted in format
3744 \a f with precision \a prec, and returns a reference to the
3747 \note The format of the number is not localized; the default C locale
3748 is used irrespective of the user's locale.
3754 Returns a byte array containing the string equivalent of the
3755 number \a n to base \a base (10 by default). The \a base can be
3756 any value between 2 and 36.
3759 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 41
3761 \note The format of the number is not localized; the default C locale
3762 is used irrespective of the user's locale.
3764 \sa setNum(), toInt()
3766 QByteArray QByteArray::number(int n, int base)
3778 QByteArray QByteArray::number(uint n, int base)
3790 QByteArray QByteArray::number(qlonglong n, int base)
3802 QByteArray QByteArray::number(qulonglong n, int base)
3812 Returns a byte array that contains the printed value of \a n,
3813 formatted in format \a f with precision \a prec.
3815 Argument \a n is formatted according to the \a f format specified,
3816 which is \c g by default, and can be any of the following:
3819 \header \i Format \i Meaning
3820 \row \i \c e \i format as [-]9.9e[+|-]999
3821 \row \i \c E \i format as [-]9.9E[+|-]999
3822 \row \i \c f \i format as [-]9.9
3823 \row \i \c g \i use \c e or \c f format, whichever is the most concise
3824 \row \i \c G \i use \c E or \c f format, whichever is the most concise
3827 With 'e', 'E', and 'f', \a prec is the number of digits after the
3828 decimal point. With 'g' and 'G', \a prec is the maximum number of
3829 significant digits (trailing zeroes are omitted).
3831 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 42
3833 \note The format of the number is not localized; the default C locale
3834 is used irrespective of the user's locale.
3838 QByteArray QByteArray::number(double n, char f, int prec)
3841 s.setNum(n, f, prec);
3846 Constructs a QByteArray that uses the first \a size bytes of the
3847 \a data array. The bytes are \e not copied. The QByteArray will
3848 contain the \a data pointer. The caller guarantees that \a data
3849 will not be deleted or modified as long as this QByteArray and any
3850 copies of it exist that have not been modified. In other words,
3851 because QByteArray is an \l{implicitly shared} class and the
3852 instance returned by this function contains the \a data pointer,
3853 the caller must not delete \a data or modify it directly as long
3854 as the returned QByteArray and any copies exist. However,
3855 QByteArray does not take ownership of \a data, so the QByteArray
3856 destructor will never delete the raw \a data, even when the
3857 last QByteArray referring to \a data is destroyed.
3859 A subsequent attempt to modify the contents of the returned
3860 QByteArray or any copy made from it will cause it to create a deep
3861 copy of the \a data array before doing the modification. This
3862 ensures that the raw \a data array itself will never be modified
3865 Here is an example of how to read data using a QDataStream on raw
3866 data in memory without copying the raw data into a QByteArray:
3868 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 43
3870 \warning A byte array created with fromRawData() is \e not
3871 null-terminated, unless the raw data contains a 0 character at
3872 position \a size. While that does not matter for QDataStream or
3873 functions like indexOf(), passing the byte array to a function
3874 accepting a \c{const char *} expected to be '\\0'-terminated will
3877 \sa setRawData(), data(), constData()
3880 QByteArray QByteArray::fromRawData(const char *data, int size)
3884 x = const_cast<Data *>(&shared_null.ba);
3886 x = const_cast<Data *>(&shared_empty.ba);
3888 x = static_cast<Data *>(qMalloc(sizeof(Data) + 1));
3893 x->capacityReserved = false;
3894 x->offset = data - (x->d + sizeof(qptrdiff));
3896 return QByteArray(x, 0, 0);
3902 Resets the QByteArray to use the first \a size bytes of the
3903 \a data array. The bytes are \e not copied. The QByteArray will
3904 contain the \a data pointer. The caller guarantees that \a data
3905 will not be deleted or modified as long as this QByteArray and any
3906 copies of it exist that have not been modified.
3908 This function can be used instead of fromRawData() to re-use
3909 existings QByteArray objects to save memory re-allocations.
3911 \sa fromRawData(), data(), constData()
3913 QByteArray &QByteArray::setRawData(const char *data, uint size)
3915 if (d->ref != 1 || d->alloc) {
3916 *this = fromRawData(data, size);
3920 d->offset = data - (d->d + sizeof(qptrdiff));
3931 Returns a decoded copy of the Base64 array \a base64. Input is not checked
3932 for validity; invalid characters in the input are skipped, enabling the
3933 decoding process to continue with subsequent characters.
3937 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 44
3939 The algorithm used to decode Base64-encoded data is defined in \l{RFC 2045}.
3943 QByteArray QByteArray::fromBase64(const QByteArray &base64)
3945 unsigned int buf = 0;
3947 QByteArray tmp((base64.size() * 3) / 4, Qt::Uninitialized);
3950 for (int i = 0; i < base64.size(); ++i) {
3951 int ch = base64.at(i);
3954 if (ch >= 'A' && ch <= 'Z')
3956 else if (ch >= 'a' && ch <= 'z')
3958 else if (ch >= '0' && ch <= '9')
3968 buf = (buf << 6) | d;
3972 tmp[offset++] = buf >> nbits;
3973 buf &= (1 << nbits) - 1;
3978 tmp.truncate(offset);
3983 Returns a decoded copy of the hex encoded array \a hexEncoded. Input is not checked
3984 for validity; invalid characters in the input are skipped, enabling the
3985 decoding process to continue with subsequent characters.
3989 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 45
3993 QByteArray QByteArray::fromHex(const QByteArray &hexEncoded)
3995 QByteArray res((hexEncoded.size() + 1)/ 2, Qt::Uninitialized);
3996 uchar *result = (uchar *)res.data() + res.size();
3998 bool odd_digit = true;
3999 for (int i = hexEncoded.size() - 1; i >= 0; --i) {
4000 int ch = hexEncoded.at(i);
4002 if (ch >= '0' && ch <= '9')
4004 else if (ch >= 'a' && ch <= 'f')
4005 tmp = ch - 'a' + 10;
4006 else if (ch >= 'A' && ch <= 'F')
4007 tmp = ch - 'A' + 10;
4015 *result |= tmp << 4;
4020 res.remove(0, result - (const uchar *)res.constData());
4025 Returns a hex encoded copy of the byte array. The hex encoding uses the numbers 0-9 and
4030 QByteArray QByteArray::toHex() const
4032 QByteArray hex(d->size * 2, Qt::Uninitialized);
4033 char *hexData = hex.data();
4034 const uchar *data = (const uchar *)d->data();
4035 for (int i = 0; i < d->size; ++i) {
4036 int j = (data[i] >> 4) & 0xf;
4038 hexData[i*2] = (j + '0');
4040 hexData[i*2] = (j + 'a' - 10);
4043 hexData[i*2+1] = (j + '0');
4045 hexData[i*2+1] = (j + 'a' - 10);
4050 static void q_fromPercentEncoding(QByteArray *ba, char percent)
4055 char *data = ba->data();
4056 const char *inputPtr = data;
4059 int len = ba->count();
4065 if (c == percent && i + 2 < len) {
4069 if (a >= '0' && a <= '9') a -= '0';
4070 else if (a >= 'a' && a <= 'f') a = a - 'a' + 10;
4071 else if (a >= 'A' && a <= 'F') a = a - 'A' + 10;
4073 if (b >= '0' && b <= '9') b -= '0';
4074 else if (b >= 'a' && b <= 'f') b = b - 'a' + 10;
4075 else if (b >= 'A' && b <= 'F') b = b - 'A' + 10;
4077 *data++ = (char)((a << 4) | b);
4087 ba->truncate(outlen);
4090 void q_fromPercentEncoding(QByteArray *ba)
4092 q_fromPercentEncoding(ba, '%');
4098 Returns a decoded copy of the URI/URL-style percent-encoded \a input.
4099 The \a percent parameter allows you to replace the '%' character for
4100 another (for instance, '_' or '=').
4104 QByteArray text = QByteArray::fromPercentEncoding("Qt%20is%20great%33");
4105 text.data(); // returns "Qt is great!"
4108 \sa toPercentEncoding(), QUrl::fromPercentEncoding()
4110 QByteArray QByteArray::fromPercentEncoding(const QByteArray &input, char percent)
4113 return QByteArray(); // preserve null
4114 if (input.isEmpty())
4115 return QByteArray(input.data(), 0);
4117 QByteArray tmp = input;
4118 q_fromPercentEncoding(&tmp, percent);
4122 static inline bool q_strchr(const char str[], char chr)
4124 if (!str) return false;
4126 const char *ptr = str;
4128 while ((c = *ptr++))
4134 static inline char toHexHelper(char c)
4136 static const char hexnumbers[] = "0123456789ABCDEF";
4137 return hexnumbers[c & 0xf];
4140 static void q_toPercentEncoding(QByteArray *ba, const char *dontEncode, const char *alsoEncode, char percent)
4145 QByteArray input = *ba;
4146 int len = input.count();
4147 const char *inputData = input.constData();
4151 for (int i = 0; i < len; ++i) {
4152 unsigned char c = *inputData++;
4153 if (((c >= 0x61 && c <= 0x7A) // ALPHA
4154 || (c >= 0x41 && c <= 0x5A) // ALPHA
4155 || (c >= 0x30 && c <= 0x39) // DIGIT
4160 || q_strchr(dontEncode, c))
4161 && !q_strchr(alsoEncode, c)) {
4168 ba->resize(len*3); // worst case
4169 output = ba->data();
4171 output[length++] = percent;
4172 output[length++] = toHexHelper((c & 0xf0) >> 4);
4173 output[length++] = toHexHelper(c & 0xf);
4177 ba->truncate(length);
4180 void q_toPercentEncoding(QByteArray *ba, const char *exclude, const char *include)
4182 q_toPercentEncoding(ba, exclude, include, '%');
4185 void q_normalizePercentEncoding(QByteArray *ba, const char *exclude)
4187 q_fromPercentEncoding(ba, '%');
4188 q_toPercentEncoding(ba, exclude, 0, '%');
4194 Returns a URI/URL-style percent-encoded copy of this byte array. The
4195 \a percent parameter allows you to override the default '%'
4196 character for another.
4198 By default, this function will encode all characters that are not
4199 one of the following:
4201 ALPHA ("a" to "z" and "A" to "Z") / DIGIT (0 to 9) / "-" / "." / "_" / "~"
4203 To prevent characters from being encoded pass them to \a
4204 exclude. To force characters to be encoded pass them to \a
4205 include. The \a percent character is always encoded.
4210 QByteArray text = "{a fishy string?}";
4211 QByteArray ba = text.toPercentEncoding("{}", "s");
4212 qDebug(ba.constData());
4213 // prints "{a fi%73hy %73tring%3F}"
4216 The hex encoding uses the numbers 0-9 and the uppercase letters A-F.
4218 \sa fromPercentEncoding(), QUrl::toPercentEncoding()
4220 QByteArray QByteArray::toPercentEncoding(const QByteArray &exclude, const QByteArray &include,
4224 return QByteArray(); // preserve null
4226 return QByteArray(data(), 0);
4228 QByteArray include2 = include;
4229 if (percent != '%') // the default
4230 if ((percent >= 0x61 && percent <= 0x7A) // ALPHA
4231 || (percent >= 0x41 && percent <= 0x5A) // ALPHA
4232 || (percent >= 0x30 && percent <= 0x39) // DIGIT
4233 || percent == 0x2D // -
4234 || percent == 0x2E // .
4235 || percent == 0x5F // _
4236 || percent == 0x7E) // ~
4237 include2 += percent;
4239 QByteArray result = *this;
4240 q_toPercentEncoding(&result, exclude.nulTerminated().constData(), include2.nulTerminated().constData(), percent);
4245 /*! \typedef QByteArray::ConstIterator
4249 /*! \typedef QByteArray::Iterator
4253 /*! \typedef QByteArray::const_iterator
4257 /*! \typedef QByteArray::iterator
4261 /*! \typedef QByteArray::const_reference
4265 /*! \typedef QByteArray::reference
4269 /*! \typedef QByteArray::value_type
4274 \fn DataPtr &QByteArray::data_ptr()
4279 \typedef QByteArray::DataPtr