1 /****************************************************************************
3 ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/
6 ** This file is part of the QtCore module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** GNU Lesser General Public License Usage
10 ** This file may be used under the terms of the GNU Lesser General Public
11 ** License version 2.1 as published by the Free Software Foundation and
12 ** appearing in the file LICENSE.LGPL included in the packaging of this
13 ** file. Please review the following information to ensure the GNU Lesser
14 ** General Public License version 2.1 requirements will be met:
15 ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
17 ** In addition, as a special exception, Nokia gives you certain additional
18 ** rights. These rights are described in the Nokia Qt LGPL Exception
19 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
21 ** GNU General Public License Usage
22 ** Alternatively, this file may be used under the terms of the GNU General
23 ** Public License version 3.0 as published by the Free Software Foundation
24 ** and appearing in the file LICENSE.GPL included in the packaging of this
25 ** file. Please review the following information to ensure the GNU General
26 ** Public License version 3.0 requirements will be met:
27 ** http://www.gnu.org/copyleft/gpl.html.
30 ** Alternatively, this file may be used in accordance with the terms and
31 ** 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 *>(::realloc(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 *>(::realloc(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
579 d->ref.initializeOwned();
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 QStaticByteArrayData<1> QByteArray::shared_null = { { Q_REFCOUNT_INITIALIZE_STATIC,
618 0, 0, 0, { 0 } }, { 0 } };
619 const QStaticByteArrayData<1> QByteArray::shared_empty = { { Q_REFCOUNT_INITIALIZE_STATIC,
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.isShared() || 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 bool 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 bool QByteArray::contains(const char *str) const
1158 Returns true if the byte array contains the string \a str;
1159 otherwise returns false.
1162 /*! \fn bool 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.
1291 Constructs a byte array containing the first \a size bytes of
1294 If \a data is 0, a null byte array is constructed.
1296 If \a size is negative, \a data is assumed to point to a nul-terminated
1297 string and its length is determined dynamically. The terminating
1298 nul-character is not considered part of the byte array.
1300 QByteArray makes a deep copy of the string data.
1305 QByteArray::QByteArray(const char *data, int size)
1308 d = const_cast<Data *>(&shared_null.ba);
1311 size = strlen(data);
1313 d = const_cast<Data *>(&shared_empty.ba);
1315 d = static_cast<Data *>(malloc(sizeof(Data) + size + 1));
1317 d->ref.initializeOwned();
1320 d->capacityReserved = false;
1322 memcpy(d->data(), data, size);
1323 d->data()[size] = '\0';
1329 Constructs a byte array of size \a size with every byte set to
1335 QByteArray::QByteArray(int size, char ch)
1338 d = const_cast<Data *>(&shared_null.ba);
1340 d = static_cast<Data *>(malloc(sizeof(Data) + size + 1));
1342 d->ref.initializeOwned();
1345 d->capacityReserved = false;
1347 memset(d->data(), ch, size);
1348 d->data()[size] = '\0';
1355 Constructs a byte array of size \a size with uninitialized contents.
1358 QByteArray::QByteArray(int size, Qt::Initialization)
1360 d = static_cast<Data *>(malloc(sizeof(Data) + size + 1));
1362 d->ref.initializeOwned();
1365 d->capacityReserved = false;
1367 d->data()[size] = '\0';
1371 Sets the size of the byte array to \a size bytes.
1373 If \a size is greater than the current size, the byte array is
1374 extended to make it \a size bytes with the extra bytes added to
1375 the end. The new bytes are uninitialized.
1377 If \a size is less than the current size, bytes are removed from
1380 \sa size(), truncate()
1383 void QByteArray::resize(int size)
1388 if (d->offset && !d->ref.isShared() && size < d->size) {
1393 if (size == 0 && !d->capacityReserved) {
1394 Data *x = const_cast<Data *>(&shared_empty.ba);
1395 if (!d->ref.deref())
1398 } else if (d == &shared_null.ba || d == &shared_empty.ba) {
1400 // Optimize the idiom:
1404 // which is used in place of the Qt 3 idiom:
1405 // QByteArray a(sz);
1407 Data *x = static_cast<Data *>(malloc(sizeof(Data) + size + 1));
1409 x->ref.initializeOwned();
1412 x->capacityReserved = false;
1414 x->data()[size] = '\0';
1417 if (d->ref.isShared() || size > int(d->alloc)
1418 || (!d->capacityReserved && size < d->size && size < int(d->alloc) >> 1))
1419 realloc(qAllocMore(size, sizeof(Data)));
1420 if (int(d->alloc) >= size) {
1422 d->data()[size] = '\0';
1428 Sets every byte in the byte array to character \a ch. If \a size
1429 is different from -1 (the default), the byte array is resized to
1430 size \a size beforehand.
1433 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 14
1438 QByteArray &QByteArray::fill(char ch, int size)
1440 resize(size < 0 ? d->size : size);
1442 memset(d->data(), ch, d->size);
1446 void QByteArray::realloc(int alloc)
1448 if (d->ref.isShared() || d->offset) {
1449 Data *x = static_cast<Data *>(malloc(sizeof(Data) + alloc + 1));
1451 x->ref.initializeOwned();
1452 x->size = qMin(alloc, d->size);
1454 x->capacityReserved = d->capacityReserved;
1456 ::memcpy(x->data(), d->data(), x->size);
1457 x->data()[x->size] = '\0';
1458 if (!d->ref.deref())
1462 Data *x = static_cast<Data *>(::realloc(d, sizeof(Data) + alloc + 1));
1470 void QByteArray::expand(int i)
1472 resize(qMax(i + 1, d->size));
1477 Return a QByteArray that is sure to be NUL-terminated.
1479 By default, all QByteArray have an extra NUL at the end,
1480 guaranteeing that assumption. However, if QByteArray::fromRawData
1481 is used, then the NUL is there only if the user put it there. We
1484 QByteArray QByteArray::nulTerminated() const
1486 // is this fromRawData?
1488 return *this; // no, then we're sure we're zero terminated
1490 QByteArray copy(*this);
1496 Prepends the byte array \a ba to this byte array and returns a
1497 reference to this byte array.
1500 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 15
1502 This is the same as insert(0, \a ba).
1504 Note: QByteArray is an \l{implicitly shared} class. Consequently,
1505 if \e this is an empty QByteArray, then \e this will just share
1506 the data held in \a ba. In this case, no copying of data is done,
1507 taking \l{constant time}. If a shared instance is modified, it will
1508 be copied (copy-on-write), taking \l{linear time}.
1510 If \e this is not an empty QByteArray, a deep copy of the data is
1511 performed, taking \l{linear time}.
1513 \sa append(), insert()
1516 QByteArray &QByteArray::prepend(const QByteArray &ba)
1518 if ((d == &shared_null.ba || d == &shared_empty.ba) && !IS_RAW_DATA(ba.d)) {
1520 } else if (ba.d != &shared_null.ba) {
1521 QByteArray tmp = *this;
1531 Prepends the string \a str to this byte array.
1534 QByteArray &QByteArray::prepend(const char *str)
1536 return prepend(str, qstrlen(str));
1543 Prepends \a len bytes of the string \a str to this byte array.
1546 QByteArray &QByteArray::prepend(const char *str, int len)
1549 if (d->ref.isShared() || d->size + len > int(d->alloc))
1550 realloc(qAllocMore(d->size + len, sizeof(Data)));
1551 memmove(d->data()+len, d->data(), d->size);
1552 memcpy(d->data(), str, len);
1554 d->data()[d->size] = '\0';
1562 Prepends the character \a ch to this byte array.
1565 QByteArray &QByteArray::prepend(char ch)
1567 if (d->ref.isShared() || d->size + 1 > int(d->alloc))
1568 realloc(qAllocMore(d->size + 1, sizeof(Data)));
1569 memmove(d->data()+1, d->data(), d->size);
1572 d->data()[d->size] = '\0';
1577 Appends the byte array \a ba onto the end of this byte array.
1580 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 16
1582 This is the same as insert(size(), \a ba).
1584 Note: QByteArray is an \l{implicitly shared} class. Consequently,
1585 if \e this is an empty QByteArray, then \e this will just share
1586 the data held in \a ba. In this case, no copying of data is done,
1587 taking \l{constant time}. If a shared instance is modified, it will
1588 be copied (copy-on-write), taking \l{linear time}.
1590 If \e this is not an empty QByteArray, a deep copy of the data is
1591 performed, taking \l{linear time}.
1593 This operation typically does not suffer from allocation overhead,
1594 because QByteArray preallocates extra space at the end of the data
1595 so that it may grow without reallocating for each append operation.
1597 \sa operator+=(), prepend(), insert()
1600 QByteArray &QByteArray::append(const QByteArray &ba)
1602 if ((d == &shared_null.ba || d == &shared_empty.ba) && !IS_RAW_DATA(ba.d)) {
1604 } else if (ba.d != &shared_null.ba) {
1605 if (d->ref.isShared() || d->size + ba.d->size > int(d->alloc))
1606 realloc(qAllocMore(d->size + ba.d->size, sizeof(Data)));
1607 memcpy(d->data() + d->size, ba.d->data(), ba.d->size);
1608 d->size += ba.d->size;
1609 d->data()[d->size] = '\0';
1614 /*! \fn QByteArray &QByteArray::append(const QString &str)
1618 Appends the string \a str to this byte array. The Unicode data is
1619 converted into 8-bit characters using QString::toAscii().
1621 If the QString contains non-ASCII Unicode characters, using this
1622 function can lead to loss of information. You can disable this
1623 function by defining \c QT_NO_CAST_TO_ASCII when you compile your
1624 applications. You then need to call QString::toAscii() (or
1625 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
1626 explicitly if you want to convert the data to \c{const char *}.
1632 Appends the string \a str to this byte array.
1635 QByteArray& QByteArray::append(const char *str)
1638 int len = qstrlen(str);
1639 if (d->ref.isShared() || d->size + len > int(d->alloc))
1640 realloc(qAllocMore(d->size + len, sizeof(Data)));
1641 memcpy(d->data() + d->size, str, len + 1); // include null terminator
1650 Appends the first \a len characters of the string \a str to this byte
1651 array and returns a reference to this byte array.
1653 If \a len is negative, the length of the string will be determined
1654 automatically using qstrlen(). If \a len is zero or \a str is
1655 null, nothing is appended to the byte array. Ensure that \a len is
1656 \e not longer than \a str.
1659 QByteArray &QByteArray::append(const char *str, int len)
1664 if (d->ref.isShared() || d->size + len > int(d->alloc))
1665 realloc(qAllocMore(d->size + len, sizeof(Data)));
1666 memcpy(d->data() + d->size, str, len); // include null terminator
1668 d->data()[d->size] = '\0';
1676 Appends the character \a ch to this byte array.
1679 QByteArray& QByteArray::append(char ch)
1681 if (d->ref.isShared() || d->size + 1 > int(d->alloc))
1682 realloc(qAllocMore(d->size + 1, sizeof(Data)));
1683 d->data()[d->size++] = ch;
1684 d->data()[d->size] = '\0';
1690 Inserts \a len bytes from the array \a arr at position \a pos and returns a
1691 reference the modified byte array.
1693 static inline QByteArray &qbytearray_insert(QByteArray *ba,
1694 int pos, const char *arr, int len)
1698 if (pos < 0 || len <= 0 || arr == 0)
1701 int oldsize = ba->size();
1702 ba->resize(qMax(pos, oldsize) + len);
1703 char *dst = ba->data();
1705 ::memset(dst + oldsize, 0x20, pos - oldsize);
1707 ::memmove(dst + pos + len, dst + pos, oldsize - pos);
1708 memcpy(dst + pos, arr, len);
1713 Inserts the byte array \a ba at index position \a i and returns a
1714 reference to this byte array.
1717 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 17
1719 \sa append(), prepend(), replace(), remove()
1722 QByteArray &QByteArray::insert(int i, const QByteArray &ba)
1724 QByteArray copy(ba);
1725 return qbytearray_insert(this, i, copy.d->data(), copy.d->size);
1729 \fn QByteArray &QByteArray::insert(int i, const QString &str)
1733 Inserts the string \a str at index position \a i in the byte
1734 array. The Unicode data is converted into 8-bit characters using
1737 If \a i is greater than size(), the array is first extended using
1740 If the QString contains non-ASCII Unicode characters, using this
1741 function can lead to loss of information. You can disable this
1742 function by defining \c QT_NO_CAST_TO_ASCII when you compile your
1743 applications. You then need to call QString::toAscii() (or
1744 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
1745 explicitly if you want to convert the data to \c{const char *}.
1751 Inserts the string \a str at position \a i in the byte array.
1753 If \a i is greater than size(), the array is first extended using
1757 QByteArray &QByteArray::insert(int i, const char *str)
1759 return qbytearray_insert(this, i, str, qstrlen(str));
1766 Inserts \a len bytes of the string \a str at position
1767 \a i in the byte array.
1769 If \a i is greater than size(), the array is first extended using
1773 QByteArray &QByteArray::insert(int i, const char *str, int len)
1775 return qbytearray_insert(this, i, str, len);
1781 Inserts character \a ch at index position \a i in the byte array.
1782 If \a i is greater than size(), the array is first extended using
1786 QByteArray &QByteArray::insert(int i, char ch)
1788 return qbytearray_insert(this, i, &ch, 1);
1792 Removes \a len bytes from the array, starting at index position \a
1793 pos, and returns a reference to the array.
1795 If \a pos is out of range, nothing happens. If \a pos is valid,
1796 but \a pos + \a len is larger than the size of the array, the
1797 array is truncated at position \a pos.
1800 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 18
1802 \sa insert(), replace()
1805 QByteArray &QByteArray::remove(int pos, int len)
1807 if (len <= 0 || pos >= d->size || pos < 0)
1810 if (pos + len >= d->size) {
1813 memmove(d->data() + pos, d->data() + pos + len, d->size - pos - len);
1814 resize(d->size - len);
1820 Replaces \a len bytes from index position \a pos with the byte
1821 array \a after, and returns a reference to this byte array.
1824 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 19
1826 \sa insert(), remove()
1829 QByteArray &QByteArray::replace(int pos, int len, const QByteArray &after)
1831 if (len == after.d->size && (pos + len <= d->size)) {
1833 memmove(d->data() + pos, after.d->data(), len*sizeof(char));
1836 QByteArray copy(after);
1839 return insert(pos, copy);
1843 /*! \fn QByteArray &QByteArray::replace(int pos, int len, const char *after)
1847 Replaces \a len bytes from index position \a pos with the zero terminated
1850 Notice: this can change the length of the byte array.
1852 QByteArray &QByteArray::replace(int pos, int len, const char *after)
1854 return replace(pos,len,after,qstrlen(after));
1857 /*! \fn QByteArray &QByteArray::replace(int pos, int len, const char *after, int alen)
1861 Replaces \a len bytes from index position \a pos with \a alen bytes
1862 from the string \a after. \a after is allowed to have '\0' characters.
1866 QByteArray &QByteArray::replace(int pos, int len, const char *after, int alen)
1868 if (len == alen && (pos + len <= d->size)) {
1870 memcpy(d->data() + pos, after, len*sizeof(char));
1874 return qbytearray_insert(this, pos, after, alen);
1878 // ### optimize all other replace method, by offering
1879 // QByteArray::replace(const char *before, int blen, const char *after, int alen)
1884 Replaces every occurrence of the byte array \a before with the
1885 byte array \a after.
1888 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 20
1891 QByteArray &QByteArray::replace(const QByteArray &before, const QByteArray &after)
1893 if (isNull() || before.d == after.d)
1896 QByteArray aft = after;
1900 return replace(before.constData(), before.size(), aft.constData(), aft.size());
1904 \fn QByteArray &QByteArray::replace(const char *before, const QByteArray &after)
1907 Replaces every occurrence of the string \a before with the
1908 byte array \a after.
1911 QByteArray &QByteArray::replace(const char *c, const QByteArray &after)
1913 QByteArray aft = after;
1917 return replace(c, qstrlen(c), aft.constData(), aft.size());
1921 \fn QByteArray &QByteArray::replace(const char *before, int bsize, const char *after, int asize)
1924 Replaces every occurrence of the string \a before with the string \a after.
1925 Since the sizes of the strings are given by \a bsize and \a asize, they
1926 may contain zero characters and do not need to be zero-terminated.
1929 QByteArray &QByteArray::replace(const char *before, int bsize, const char *after, int asize)
1931 if (isNull() || (before == after && bsize == asize))
1934 // protect against before or after being part of this
1935 const char *a = after;
1936 const char *b = before;
1937 if (after >= d->data() && after < d->data() + d->size) {
1938 char *copy = (char *)malloc(asize);
1940 memcpy(copy, after, asize);
1943 if (before >= d->data() && before < d->data() + d->size) {
1944 char *copy = (char *)malloc(bsize);
1946 memcpy(copy, before, bsize);
1950 QByteArrayMatcher matcher(before, bsize);
1955 if (bsize == asize) {
1957 while ((index = matcher.indexIn(*this, index)) != -1) {
1958 memcpy(d + index, after, asize);
1962 } else if (asize < bsize) {
1966 while ((index = matcher.indexIn(*this, index)) != -1) {
1968 int msize = index - movestart;
1970 memmove(d + to, d + movestart, msize);
1977 memcpy(d + to, after, asize);
1985 int msize = len - movestart;
1987 memmove(d + to, d + movestart, msize);
1988 resize(len - num*(bsize-asize));
1991 // the most complex case. We don't want to lose performance by doing repeated
1992 // copies and reallocs of the string.
1993 while (index != -1) {
1997 index = matcher.indexIn(*this, index);
2000 indices[pos++] = index;
2002 // avoid infinite loop
2009 // we have a table of replacement positions, use them for fast replacing
2010 int adjust = pos*(asize-bsize);
2011 // index has to be adjusted in case we get back into the loop above.
2014 int newlen = len + adjust;
2020 d = this->d->data();
2024 int movestart = indices[pos] + bsize;
2025 int insertstart = indices[pos] + pos*(asize-bsize);
2026 int moveto = insertstart + asize;
2027 memmove(d + moveto, d + movestart, (moveend - movestart));
2029 memcpy(d + insertstart, after, asize);
2030 moveend = movestart - bsize;
2046 \fn QByteArray &QByteArray::replace(const QByteArray &before, const char *after)
2049 Replaces every occurrence of the byte array \a before with the
2053 /*! \fn QByteArray &QByteArray::replace(const QString &before, const QByteArray &after)
2057 Replaces every occurrence of the string \a before with the byte
2058 array \a after. The Unicode data is converted into 8-bit
2059 characters using QString::toAscii().
2061 If the QString contains non-ASCII Unicode characters, using this
2062 function can lead to loss of information. You can disable this
2063 function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2064 applications. You then need to call QString::toAscii() (or
2065 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2066 explicitly if you want to convert the data to \c{const char *}.
2069 /*! \fn QByteArray &QByteArray::replace(const QString &before, const char *after)
2072 Replaces every occurrence of the string \a before with the string
2076 /*! \fn QByteArray &QByteArray::replace(const char *before, const char *after)
2080 Replaces every occurrence of the string \a before with the string
2087 Replaces every occurrence of the character \a before with the
2088 byte array \a after.
2091 QByteArray &QByteArray::replace(char before, const QByteArray &after)
2093 char b[2] = { before, '\0' };
2094 QByteArray cb = fromRawData(b, 1);
2095 return replace(cb, after);
2098 /*! \fn QByteArray &QByteArray::replace(char before, const QString &after)
2102 Replaces every occurrence of the character \a before with the
2103 string \a after. The Unicode data is converted into 8-bit
2104 characters using QString::toAscii().
2106 If the QString contains non-ASCII Unicode characters, using this
2107 function can lead to loss of information. You can disable this
2108 function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2109 applications. You then need to call QString::toAscii() (or
2110 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2111 explicitly if you want to convert the data to \c{const char *}.
2114 /*! \fn QByteArray &QByteArray::replace(char before, const char *after)
2118 Replaces every occurrence of the character \a before with the
2125 Replaces every occurrence of the character \a before with the
2129 QByteArray &QByteArray::replace(char before, char after)
2133 char *e = i + d->size;
2142 Splits the byte array into subarrays wherever \a sep occurs, and
2143 returns the list of those arrays. If \a sep does not match
2144 anywhere in the byte array, split() returns a single-element list
2145 containing this byte array.
2148 QList<QByteArray> QByteArray::split(char sep) const
2150 QList<QByteArray> list;
2153 while ((end = indexOf(sep, start)) != -1) {
2154 list.append(mid(start, end - start));
2157 list.append(mid(start));
2164 Returns a copy of this byte array repeated the specified number of \a times.
2166 If \a times is less than 1, an empty byte array is returned.
2171 QByteArray ba("ab");
2172 ba.repeated(4); // returns "abababab"
2175 QByteArray QByteArray::repeated(int times) const
2183 return QByteArray();
2186 const int resultSize = times * d->size;
2189 result.reserve(resultSize);
2190 if (int(result.d->alloc) != resultSize)
2191 return QByteArray(); // not enough memory
2193 memcpy(result.d->data(), d->data(), d->size);
2195 int sizeSoFar = d->size;
2196 char *end = result.d->data() + sizeSoFar;
2198 const int halfResultSize = resultSize >> 1;
2199 while (sizeSoFar <= halfResultSize) {
2200 memcpy(end, result.d->data(), sizeSoFar);
2204 memcpy(end, result.d->data(), resultSize - sizeSoFar);
2205 result.d->data()[resultSize] = '\0';
2206 result.d->size = resultSize;
2211 if (ol_minus_1 < sizeof(uint) * CHAR_BIT) \
2212 hashHaystack -= (a) << ol_minus_1; \
2216 Returns the index position of the first occurrence of the byte
2217 array \a ba in this byte array, searching forward from index
2218 position \a from. Returns -1 if \a ba could not be found.
2221 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 21
2223 \sa lastIndexOf(), contains(), count()
2226 int QByteArray::indexOf(const QByteArray &ba, int from) const
2228 const int ol = ba.d->size;
2232 return indexOf(*ba.d->data(), from);
2234 const int l = d->size;
2235 if (from > d->size || ol + from > l)
2238 return qFindByteArray(d->data(), d->size, from, ba.d->data(), ol);
2241 /*! \fn int QByteArray::indexOf(const QString &str, int from) const
2245 Returns the index position of the first occurrence of the string
2246 \a str in the byte array, searching forward from index position
2247 \a from. Returns -1 if \a str could not be found.
2249 The Unicode data is converted into 8-bit characters using
2252 If the QString contains non-ASCII Unicode characters, using this
2253 function can lead to loss of information. You can disable this
2254 function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2255 applications. You then need to call QString::toAscii() (or
2256 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2257 explicitly if you want to convert the data to \c{const char *}.
2260 /*! \fn int QByteArray::indexOf(const char *str, int from) const
2264 Returns the index position of the first occurrence of the string
2265 \a str in the byte array, searching forward from index position \a
2266 from. Returns -1 if \a str could not be found.
2268 int QByteArray::indexOf(const char *c, int from) const
2270 const int ol = qstrlen(c);
2272 return indexOf(*c, from);
2274 const int l = d->size;
2275 if (from > d->size || ol + from > l)
2280 return qFindByteArray(d->data(), d->size, from, c, ol);
2286 Returns the index position of the first occurrence of the
2287 character \a ch in the byte array, searching forward from index
2288 position \a from. Returns -1 if \a ch could not be found.
2291 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 22
2293 \sa lastIndexOf(), contains()
2296 int QByteArray::indexOf(char ch, int from) const
2299 from = qMax(from + d->size, 0);
2300 if (from < d->size) {
2301 const char *n = d->data() + from - 1;
2302 const char *e = d->data() + d->size;
2305 return n - d->data();
2311 static int lastIndexOfHelper(const char *haystack, int l, const char *needle, int ol, int from)
2316 if (from < 0 || from > l)
2321 const char *end = haystack;
2323 const uint ol_minus_1 = ol - 1;
2324 const char *n = needle + ol_minus_1;
2325 const char *h = haystack + ol_minus_1;
2326 uint hashNeedle = 0, hashHaystack = 0;
2328 for (idx = 0; idx < ol; ++idx) {
2329 hashNeedle = ((hashNeedle<<1) + *(n-idx));
2330 hashHaystack = ((hashHaystack<<1) + *(h-idx));
2332 hashHaystack -= *haystack;
2333 while (haystack >= end) {
2334 hashHaystack += *haystack;
2335 if (hashHaystack == hashNeedle && memcmp(needle, haystack, ol) == 0)
2336 return haystack - end;
2338 REHASH(*(haystack + ol));
2345 \fn int QByteArray::lastIndexOf(const QByteArray &ba, int from) const
2347 Returns the index position of the last occurrence of the byte
2348 array \a ba in this byte array, searching backward from index
2349 position \a from. If \a from is -1 (the default), the search
2350 starts at the last byte. Returns -1 if \a ba could not be found.
2353 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 23
2355 \sa indexOf(), contains(), count()
2358 int QByteArray::lastIndexOf(const QByteArray &ba, int from) const
2360 const int ol = ba.d->size;
2362 return lastIndexOf(*ba.d->data(), from);
2364 return lastIndexOfHelper(d->data(), d->size, ba.d->data(), ol, from);
2367 /*! \fn int QByteArray::lastIndexOf(const QString &str, int from) const
2371 Returns the index position of the last occurrence of the string \a
2372 str in the byte array, searching backward from index position \a
2373 from. If \a from is -1 (the default), the search starts at the
2374 last (size() - 1) byte. Returns -1 if \a str could not be found.
2376 The Unicode data is converted into 8-bit characters using
2379 If the QString contains non-ASCII Unicode characters, using this
2380 function can lead to loss of information. You can disable this
2381 function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2382 applications. You then need to call QString::toAscii() (or
2383 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2384 explicitly if you want to convert the data to \c{const char *}.
2387 /*! \fn int QByteArray::lastIndexOf(const char *str, int from) const
2390 Returns the index position of the last occurrence of the string \a
2391 str in the byte array, searching backward from index position \a
2392 from. If \a from is -1 (the default), the search starts at the
2393 last (size() - 1) byte. Returns -1 if \a str could not be found.
2395 int QByteArray::lastIndexOf(const char *str, int from) const
2397 const int ol = qstrlen(str);
2399 return lastIndexOf(*str, from);
2401 return lastIndexOfHelper(d->data(), d->size, str, ol, from);
2407 Returns the index position of the last occurrence of character \a
2408 ch in the byte array, searching backward from index position \a
2409 from. If \a from is -1 (the default), the search starts at the
2410 last (size() - 1) byte. Returns -1 if \a ch could not be found.
2413 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 24
2415 \sa indexOf(), contains()
2418 int QByteArray::lastIndexOf(char ch, int from) const
2422 else if (from > d->size)
2425 const char *b = d->data();
2426 const char *n = d->data() + from + 1;
2435 Returns the number of (potentially overlapping) occurrences of
2436 byte array \a ba in this byte array.
2438 \sa contains(), indexOf()
2441 int QByteArray::count(const QByteArray &ba) const
2445 if (d->size > 500 && ba.d->size > 5) {
2446 QByteArrayMatcher matcher(ba);
2447 while ((i = matcher.indexIn(*this, i + 1)) != -1)
2450 while ((i = indexOf(ba, i + 1)) != -1)
2459 Returns the number of (potentially overlapping) occurrences of
2460 string \a str in the byte array.
2463 int QByteArray::count(const char *str) const
2465 return count(fromRawData(str, qstrlen(str)));
2471 Returns the number of occurrences of character \a ch in the byte
2474 \sa contains(), indexOf()
2477 int QByteArray::count(char ch) const
2480 const char *i = d->data() + d->size;
2481 const char *b = d->data();
2488 /*! \fn int QByteArray::count() const
2496 Returns true if this byte array starts with byte array \a ba;
2497 otherwise returns false.
2500 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 25
2502 \sa endsWith(), left()
2504 bool QByteArray::startsWith(const QByteArray &ba) const
2506 if (d == ba.d || ba.d->size == 0)
2508 if (d->size < ba.d->size)
2510 return memcmp(d->data(), ba.d->data(), ba.d->size) == 0;
2515 Returns true if this byte array starts with string \a str;
2516 otherwise returns false.
2518 bool QByteArray::startsWith(const char *str) const
2522 int len = qstrlen(str);
2525 return qstrncmp(d->data(), str, len) == 0;
2530 Returns true if this byte array starts with character \a ch;
2531 otherwise returns false.
2533 bool QByteArray::startsWith(char ch) const
2537 return d->data()[0] == ch;
2541 Returns true if this byte array ends with byte array \a ba;
2542 otherwise returns false.
2545 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 26
2547 \sa startsWith(), right()
2549 bool QByteArray::endsWith(const QByteArray &ba) const
2551 if (d == ba.d || ba.d->size == 0)
2553 if (d->size < ba.d->size)
2555 return memcmp(d->data() + d->size - ba.d->size, ba.d->data(), ba.d->size) == 0;
2560 Returns true if this byte array ends with string \a str; otherwise
2563 bool QByteArray::endsWith(const char *str) const
2567 int len = qstrlen(str);
2570 return qstrncmp(d->data() + d->size - len, str, len) == 0;
2575 Returns true if this byte array ends with character \a ch;
2576 otherwise returns false.
2578 bool QByteArray::endsWith(char ch) const
2582 return d->data()[d->size - 1] == ch;
2586 Returns a byte array that contains the leftmost \a len bytes of
2589 The entire byte array is returned if \a len is greater than
2593 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 27
2595 \sa right(), mid(), startsWith(), truncate()
2598 QByteArray QByteArray::left(int len) const
2604 return QByteArray(d->data(), len);
2608 Returns a byte array that contains the rightmost \a len bytes of
2611 The entire byte array is returned if \a len is greater than
2615 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 28
2617 \sa endsWith(), left(), mid()
2620 QByteArray QByteArray::right(int len) const
2626 return QByteArray(d->data() + d->size - len, len);
2630 Returns a byte array containing \a len bytes from this byte array,
2631 starting at position \a pos.
2633 If \a len is -1 (the default), or \a pos + \a len >= size(),
2634 returns a byte array containing all bytes starting at position \a
2635 pos until the end of the byte array.
2638 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 29
2643 QByteArray QByteArray::mid(int pos, int len) const
2645 if (d == &shared_null.ba || d == &shared_empty.ba || pos > d->size)
2646 return QByteArray();
2648 len = d->size - pos;
2653 if (len + pos > d->size)
2654 len = d->size - pos;
2655 if (pos == 0 && len == d->size)
2657 return QByteArray(d->data() + pos, len);
2661 Returns a lowercase copy of the byte array. The bytearray is
2662 interpreted as a Latin-1 encoded string.
2665 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 30
2667 \sa toUpper(), {8-bit Character Comparisons}
2669 QByteArray QByteArray::toLower() const
2671 QByteArray s(*this);
2672 register uchar *p = reinterpret_cast<uchar *>(s.data());
2675 *p = QChar::toLower((ushort)*p);
2683 Returns an uppercase copy of the byte array. The bytearray is
2684 interpreted as a Latin-1 encoded string.
2687 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 31
2689 \sa toLower(), {8-bit Character Comparisons}
2692 QByteArray QByteArray::toUpper() const
2694 QByteArray s(*this);
2695 register uchar *p = reinterpret_cast<uchar *>(s.data());
2698 *p = QChar::toUpper((ushort)*p);
2705 /*! \fn void QByteArray::clear()
2707 Clears the contents of the byte array and makes it empty.
2709 \sa resize(), isEmpty()
2712 void QByteArray::clear()
2714 if (!d->ref.deref())
2716 d = const_cast<Data *>(&shared_null.ba);
2720 #if !defined(QT_NO_DATASTREAM) || (defined(QT_BOOTSTRAPPED) && !defined(QT_BUILD_QMAKE))
2722 /*! \relates QByteArray
2724 Writes byte array \a ba to the stream \a out and returns a reference
2727 \sa {Serializing Qt Data Types}
2730 QDataStream &operator<<(QDataStream &out, const QByteArray &ba)
2732 if (ba.isNull() && out.version() >= 6) {
2733 out << (quint32)0xffffffff;
2736 return out.writeBytes(ba, ba.size());
2739 /*! \relates QByteArray
2741 Reads a byte array into \a ba from the stream \a in and returns a
2742 reference to the stream.
2744 \sa {Serializing Qt Data Types}
2747 QDataStream &operator>>(QDataStream &in, QByteArray &ba)
2752 if (len == 0xffffffff)
2755 const quint32 Step = 1024 * 1024;
2756 quint32 allocated = 0;
2759 int blockSize = qMin(Step, len - allocated);
2760 ba.resize(allocated + blockSize);
2761 if (in.readRawData(ba.data() + allocated, blockSize) != blockSize) {
2763 in.setStatus(QDataStream::ReadPastEnd);
2766 allocated += blockSize;
2767 } while (allocated < len);
2771 #endif // QT_NO_DATASTREAM
2773 /*! \fn bool QByteArray::operator==(const QString &str) const
2775 Returns true if this byte array is equal to string \a str;
2776 otherwise returns false.
2778 The Unicode data is converted into 8-bit characters using
2781 The comparison is case sensitive.
2783 You can disable this operator by defining \c
2784 QT_NO_CAST_FROM_ASCII when you compile your applications. You
2785 then need to call QString::fromAscii(), QString::fromLatin1(),
2786 QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2787 you want to convert the byte array to a QString before doing the
2791 /*! \fn bool QByteArray::operator!=(const QString &str) const
2793 Returns true if this byte array is not 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 lexically less than string \a
2812 str; 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 greater than string
2830 \a 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 less than or equal
2848 to string \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 greater than or equal to string
2866 \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 operator==(const QByteArray &a1, const QByteArray &a2)
2886 Returns true if byte array \a a1 is equal to byte array \a a2;
2887 otherwise returns false.
2890 /*! \fn bool operator==(const QByteArray &a1, const char *a2)
2895 Returns true if byte array \a a1 is equal to string \a a2;
2896 otherwise returns false.
2899 /*! \fn bool operator==(const char *a1, const QByteArray &a2)
2904 Returns true if string \a a1 is equal to byte array \a a2;
2905 otherwise returns false.
2908 /*! \fn bool operator!=(const QByteArray &a1, const QByteArray &a2)
2913 Returns true if byte array \a a1 is not equal to byte array \a a2;
2914 otherwise returns false.
2917 /*! \fn bool operator!=(const QByteArray &a1, const char *a2)
2922 Returns true if byte array \a a1 is not equal to string \a a2;
2923 otherwise returns false.
2926 /*! \fn bool operator!=(const char *a1, const QByteArray &a2)
2931 Returns true if string \a a1 is not equal to byte array \a a2;
2932 otherwise returns false.
2935 /*! \fn bool operator<(const QByteArray &a1, const QByteArray &a2)
2940 Returns true if byte array \a a1 is lexically less than byte array
2941 \a a2; otherwise returns false.
2944 /*! \fn inline bool operator<(const QByteArray &a1, const char *a2)
2949 Returns true if byte array \a a1 is lexically less than string
2950 \a a2; otherwise returns false.
2953 /*! \fn bool operator<(const char *a1, const QByteArray &a2)
2958 Returns true if string \a a1 is lexically less than byte array
2959 \a a2; otherwise returns false.
2962 /*! \fn bool operator<=(const QByteArray &a1, const QByteArray &a2)
2967 Returns true if byte array \a a1 is lexically less than or equal
2968 to byte array \a a2; otherwise returns false.
2971 /*! \fn bool operator<=(const QByteArray &a1, const char *a2)
2976 Returns true if byte array \a a1 is lexically less than or equal
2977 to string \a a2; otherwise returns false.
2980 /*! \fn bool operator<=(const char *a1, const QByteArray &a2)
2985 Returns true if string \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 QByteArray &a2)
2994 Returns true if byte array \a a1 is lexically greater than byte
2995 array \a a2; otherwise returns false.
2998 /*! \fn bool operator>(const QByteArray &a1, const char *a2)
3003 Returns true if byte array \a a1 is lexically greater than string
3004 \a a2; otherwise returns false.
3007 /*! \fn bool operator>(const char *a1, const QByteArray &a2)
3012 Returns true if string \a a1 is lexically greater than byte array
3013 \a a2; otherwise returns false.
3016 /*! \fn bool operator>=(const QByteArray &a1, const QByteArray &a2)
3021 Returns true if byte array \a a1 is lexically greater than or
3022 equal to byte array \a a2; otherwise returns false.
3025 /*! \fn bool operator>=(const QByteArray &a1, const char *a2)
3030 Returns true if byte array \a a1 is lexically greater than or
3031 equal to string \a a2; otherwise returns false.
3034 /*! \fn bool operator>=(const char *a1, const QByteArray &a2)
3039 Returns true if string \a a1 is lexically greater than or
3040 equal to byte array \a a2; otherwise returns false.
3043 /*! \fn const QByteArray operator+(const QByteArray &a1, const QByteArray &a2)
3046 Returns a byte array that is the result of concatenating byte
3047 array \a a1 and byte array \a a2.
3049 \sa QByteArray::operator+=()
3052 /*! \fn const QByteArray operator+(const QByteArray &a1, const char *a2)
3057 Returns a byte array that is the result of concatenating byte
3058 array \a a1 and string \a a2.
3061 /*! \fn const QByteArray operator+(const QByteArray &a1, char a2)
3066 Returns a byte array that is the result of concatenating byte
3067 array \a a1 and character \a a2.
3070 /*! \fn const QByteArray operator+(const char *a1, const QByteArray &a2)
3075 Returns a byte array that is the result of concatenating string
3076 \a a1 and byte array \a a2.
3079 /*! \fn const QByteArray operator+(char a1, const QByteArray &a2)
3084 Returns a byte array that is the result of concatenating character
3085 \a a1 and byte array \a a2.
3089 Returns a byte array that has whitespace removed from the start
3090 and the end, and which has each sequence of internal whitespace
3091 replaced with a single space.
3093 Whitespace means any character for which the standard C++
3094 isspace() function returns true. This includes the ASCII
3095 characters '\\t', '\\n', '\\v', '\\f', '\\r', and ' '.
3098 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 32
3102 QByteArray QByteArray::simplified() const
3106 QByteArray result(d->size, Qt::Uninitialized);
3107 const char *from = d->data();
3108 const char *fromend = from + d->size;
3110 char *to = result.d->data();
3112 while (from!=fromend && isspace(uchar(*from)))
3114 while (from!=fromend && !isspace(uchar(*from)))
3115 to[outc++] = *from++;
3121 if (outc > 0 && to[outc-1] == ' ')
3123 result.resize(outc);
3128 Returns a byte array that has whitespace removed from the start
3131 Whitespace means any character for which the standard C++
3132 isspace() function returns true. This includes the ASCII
3133 characters '\\t', '\\n', '\\v', '\\f', '\\r', and ' '.
3136 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 33
3138 Unlike simplified(), trimmed() leaves internal whitespace alone.
3142 QByteArray QByteArray::trimmed() const
3146 const char *s = d->data();
3147 if (!isspace(uchar(*s)) && !isspace(uchar(s[d->size-1])))
3150 int end = d->size - 1;
3151 while (start<=end && isspace(uchar(s[start]))) // skip white space from start
3153 if (start <= end) { // only white space
3154 while (end && isspace(uchar(s[end]))) // skip white space from end
3157 int l = end - start + 1;
3159 return QByteArray(const_cast<Data *>(&shared_empty.ba), 0, 0);
3161 return QByteArray(s+start, l);
3165 Returns a byte array of size \a width that contains this byte
3166 array padded by the \a fill character.
3168 If \a truncate is false and the size() of the byte array is more
3169 than \a width, then the returned byte array is a copy of this byte
3172 If \a truncate is true and the size() of the byte array is more
3173 than \a width, then any bytes in a copy of the byte array
3174 after position \a width are removed, and the copy is returned.
3177 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 34
3179 \sa rightJustified()
3182 QByteArray QByteArray::leftJustified(int width, char fill, bool truncate) const
3186 int padlen = width - len;
3188 result.resize(len+padlen);
3190 memcpy(result.d->data(), d->data(), len);
3191 memset(result.d->data()+len, fill, padlen);
3194 result = left(width);
3202 Returns a byte array of size \a width that contains the \a fill
3203 character followed by this byte array.
3205 If \a truncate is false and the size of the byte array is more
3206 than \a width, then the returned byte array is a copy of this byte
3209 If \a truncate is true and the size of the byte array is more
3210 than \a width, then the resulting byte array is truncated at
3214 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 35
3219 QByteArray QByteArray::rightJustified(int width, char fill, bool truncate) const
3223 int padlen = width - len;
3225 result.resize(len+padlen);
3227 memcpy(result.d->data()+padlen, data(), len);
3228 memset(result.d->data(), fill, padlen);
3231 result = left(width);
3238 bool QByteArray::isNull() const { return d == &shared_null.ba; }
3242 Returns the byte array converted to a \c {long long} using base \a
3243 base, which is 10 by default and must be between 2 and 36, or 0.
3245 If \a base is 0, the base is determined automatically using the
3246 following rules: If the byte array begins with "0x", it is assumed to
3247 be hexadecimal; if it begins with "0", it is assumed to be octal;
3248 otherwise it is assumed to be decimal.
3250 Returns 0 if the conversion fails.
3252 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3253 false; otherwise *\a{ok} is set to true.
3255 \note The conversion of the number is performed in the default C locale,
3256 irrespective of the user's locale.
3261 qlonglong QByteArray::toLongLong(bool *ok, int base) const
3263 #if defined(QT_CHECK_RANGE)
3264 if (base != 0 && (base < 2 || base > 36)) {
3265 qWarning("QByteArray::toLongLong: Invalid base %d", base);
3270 return QLocalePrivate::bytearrayToLongLong(nulTerminated().constData(), base, ok);
3274 Returns the byte array converted to an \c {unsigned long long}
3275 using base \a base, which is 10 by default and must be between 2
3278 If \a base is 0, the base is determined automatically using the
3279 following rules: If the byte array begins with "0x", it is assumed to
3280 be hexadecimal; if it begins with "0", it is assumed to be octal;
3281 otherwise it is assumed to be decimal.
3283 Returns 0 if the conversion fails.
3285 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3286 false; otherwise *\a{ok} is set to true.
3288 \note The conversion of the number is performed in the default C locale,
3289 irrespective of the user's locale.
3294 qulonglong QByteArray::toULongLong(bool *ok, int base) const
3296 #if defined(QT_CHECK_RANGE)
3297 if (base != 0 && (base < 2 || base > 36)) {
3298 qWarning("QByteArray::toULongLong: Invalid base %d", base);
3303 return QLocalePrivate::bytearrayToUnsLongLong(nulTerminated().constData(), base, ok);
3308 Returns the byte array converted to an \c int using base \a
3309 base, which is 10 by default and must be between 2 and 36, or 0.
3311 If \a base is 0, the base is determined automatically using the
3312 following rules: If the byte array begins with "0x", it is assumed to
3313 be hexadecimal; if it begins with "0", it is assumed to be octal;
3314 otherwise it is assumed to be decimal.
3316 Returns 0 if the conversion fails.
3318 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3319 false; otherwise *\a{ok} is set to true.
3321 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 36
3323 \note The conversion of the number is performed in the default C locale,
3324 irrespective of the user's locale.
3329 int QByteArray::toInt(bool *ok, int base) const
3331 qlonglong v = toLongLong(ok, base);
3332 if (v < INT_MIN || v > INT_MAX) {
3341 Returns the byte array converted to an \c {unsigned int} using base \a
3342 base, which is 10 by default and must be between 2 and 36, or 0.
3344 If \a base is 0, the base is determined automatically using the
3345 following rules: If the byte array begins with "0x", it is assumed to
3346 be hexadecimal; if it begins with "0", it is assumed to be octal;
3347 otherwise it is assumed to be decimal.
3349 Returns 0 if the conversion fails.
3351 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3352 false; otherwise *\a{ok} is set to true.
3354 \note The conversion of the number is performed in the default C locale,
3355 irrespective of the user's locale.
3360 uint QByteArray::toUInt(bool *ok, int base) const
3362 qulonglong v = toULongLong(ok, base);
3374 Returns the byte array converted to a \c long int using base \a
3375 base, which is 10 by default and must be between 2 and 36, or 0.
3377 If \a base is 0, the base is determined automatically using the
3378 following rules: If the byte array begins with "0x", it is assumed to
3379 be hexadecimal; if it begins with "0", it is assumed to be octal;
3380 otherwise it is assumed to be decimal.
3382 Returns 0 if the conversion fails.
3384 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3385 false; otherwise *\a{ok} is set to true.
3387 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 37
3389 \note The conversion of the number is performed in the default C locale,
3390 irrespective of the user's locale.
3394 long QByteArray::toLong(bool *ok, int base) const
3396 qlonglong v = toLongLong(ok, base);
3397 if (v < LONG_MIN || v > LONG_MAX) {
3408 Returns the byte array converted to an \c {unsigned long int} using base \a
3409 base, which is 10 by default and must be between 2 and 36, or 0.
3411 If \a base is 0, the base is determined automatically using the
3412 following rules: If the byte array begins with "0x", it is assumed to
3413 be hexadecimal; if it begins with "0", it is assumed to be octal;
3414 otherwise it is assumed to be decimal.
3416 Returns 0 if the conversion fails.
3418 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3419 false; otherwise *\a{ok} is set to true.
3421 \note The conversion of the number is performed in the default C locale,
3422 irrespective of the user's locale.
3426 ulong QByteArray::toULong(bool *ok, int base) const
3428 qulonglong v = toULongLong(ok, base);
3429 if (v > ULONG_MAX) {
3438 Returns the byte array converted to a \c short using base \a
3439 base, which is 10 by default and must be between 2 and 36, or 0.
3441 If \a base is 0, the base is determined automatically using the
3442 following rules: If the byte array begins with "0x", it is assumed to
3443 be hexadecimal; if it begins with "0", it is assumed to be octal;
3444 otherwise it is assumed to be decimal.
3446 Returns 0 if the conversion fails.
3448 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3449 false; otherwise *\a{ok} is set to true.
3451 \note The conversion of the number is performed in the default C locale,
3452 irrespective of the user's locale.
3457 short QByteArray::toShort(bool *ok, int base) const
3459 qlonglong v = toLongLong(ok, base);
3460 if (v < SHRT_MIN || v > SHRT_MAX) {
3469 Returns the byte array converted to an \c {unsigned short} using base \a
3470 base, which is 10 by default and must be between 2 and 36, or 0.
3472 If \a base is 0, the base is determined automatically using the
3473 following rules: If the byte array begins with "0x", it is assumed to
3474 be hexadecimal; if it begins with "0", it is assumed to be octal;
3475 otherwise it is assumed to be decimal.
3477 Returns 0 if the conversion fails.
3479 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3480 false; otherwise *\a{ok} is set to true.
3482 \note The conversion of the number is performed in the default C locale,
3483 irrespective of the user's locale.
3488 ushort QByteArray::toUShort(bool *ok, int base) const
3490 qulonglong v = toULongLong(ok, base);
3491 if (v > USHRT_MAX) {
3501 Returns the byte array converted to a \c double value.
3503 Returns 0.0 if the conversion fails.
3505 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3506 false; otherwise *\a{ok} is set to true.
3508 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 38
3510 \note The conversion of the number is performed in the default C locale,
3511 irrespective of the user's locale.
3516 double QByteArray::toDouble(bool *ok) const
3518 return QLocalePrivate::bytearrayToDouble(nulTerminated().constData(), ok);
3522 Returns the byte array converted to a \c float value.
3524 Returns 0.0 if the conversion fails.
3526 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3527 false; otherwise *\a{ok} is set to true.
3529 \note The conversion of the number is performed in the default C locale,
3530 irrespective of the user's locale.
3535 float QByteArray::toFloat(bool *ok) const
3537 return float(toDouble(ok));
3541 Returns a copy of the byte array, encoded as Base64.
3543 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 39
3545 The algorithm used to encode Base64-encoded data is defined in \l{RFC 2045}.
3549 QByteArray QByteArray::toBase64() const
3551 const char alphabet[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
3552 "ghijklmn" "opqrstuv" "wxyz0123" "456789+/";
3553 const char padchar = '=';
3556 QByteArray tmp((d->size * 4) / 3 + 3, Qt::Uninitialized);
3559 char *out = tmp.data();
3560 while (i < d->size) {
3562 chunk |= int(uchar(d->data()[i++])) << 16;
3566 chunk |= int(uchar(d->data()[i++])) << 8;
3567 if (i == d->size) padlen = 1;
3568 else chunk |= int(uchar(d->data()[i++]));
3571 int j = (chunk & 0x00fc0000) >> 18;
3572 int k = (chunk & 0x0003f000) >> 12;
3573 int l = (chunk & 0x00000fc0) >> 6;
3574 int m = (chunk & 0x0000003f);
3575 *out++ = alphabet[j];
3576 *out++ = alphabet[k];
3577 if (padlen > 1) *out++ = padchar;
3578 else *out++ = alphabet[l];
3579 if (padlen > 0) *out++ = padchar;
3580 else *out++ = alphabet[m];
3583 tmp.truncate(out - tmp.data());
3588 \fn QByteArray &QByteArray::setNum(int n, int base)
3590 Sets the byte array to the printed value of \a n in base \a base (10
3591 by default) and returns a reference to the byte array. The \a base can
3592 be any value between 2 and 36.
3595 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 40
3597 \note The format of the number is not localized; the default C locale
3598 is used irrespective of the user's locale.
3600 \sa number(), toInt()
3604 \fn QByteArray &QByteArray::setNum(uint n, int base)
3611 \fn QByteArray &QByteArray::setNum(short n, int base)
3618 \fn QByteArray &QByteArray::setNum(ushort n, int base)
3630 QByteArray &QByteArray::setNum(qlonglong n, int base)
3632 #if defined(QT_CHECK_RANGE)
3633 if (base < 2 || base > 36) {
3634 qWarning("QByteArray::setNum: Invalid base %d", base);
3638 QLocale locale(QLocale::C);
3639 *this = locale.d()->longLongToString(n, -1, base).toLatin1();
3649 QByteArray &QByteArray::setNum(qulonglong n, int base)
3651 #if defined(QT_CHECK_RANGE)
3652 if (base < 2 || base > 36) {
3653 qWarning("QByteArray::setNum: Invalid base %d", base);
3657 QLocale locale(QLocale::C);
3658 *this = locale.d()->unsLongLongToString(n, -1, base).toLatin1();
3665 Sets the byte array to the printed value of \a n, formatted in format
3666 \a f with precision \a prec, and returns a reference to the
3669 The format \a f can be any of the following:
3672 \header \i Format \i Meaning
3673 \row \i \c e \i format as [-]9.9e[+|-]999
3674 \row \i \c E \i format as [-]9.9E[+|-]999
3675 \row \i \c f \i format as [-]9.9
3676 \row \i \c g \i use \c e or \c f format, whichever is the most concise
3677 \row \i \c G \i use \c E or \c f format, whichever is the most concise
3680 With 'e', 'E', and 'f', \a prec is the number of digits after the
3681 decimal point. With 'g' and 'G', \a prec is the maximum number of
3682 significant digits (trailing zeroes are omitted).
3684 \note The format of the number is not localized; the default C locale
3685 is used irrespective of the user's locale.
3690 QByteArray &QByteArray::setNum(double n, char f, int prec)
3692 QLocalePrivate::DoubleForm form = QLocalePrivate::DFDecimal;
3696 flags = QLocalePrivate::CapitalEorX;
3701 form = QLocalePrivate::DFDecimal;
3704 form = QLocalePrivate::DFExponent;
3707 form = QLocalePrivate::DFSignificantDigits;
3710 #if defined(QT_CHECK_RANGE)
3711 qWarning("QByteArray::setNum: Invalid format char '%c'", f);
3716 QLocale locale(QLocale::C);
3717 *this = locale.d()->doubleToString(n, prec, form, -1, flags).toLatin1();
3722 \fn QByteArray &QByteArray::setNum(float n, char f, int prec)
3725 Sets the byte array to the printed value of \a n, formatted in format
3726 \a f with precision \a prec, and returns a reference to the
3729 \note The format of the number is not localized; the default C locale
3730 is used irrespective of the user's locale.
3736 Returns a byte array containing the string equivalent of the
3737 number \a n to base \a base (10 by default). The \a base can be
3738 any value between 2 and 36.
3741 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 41
3743 \note The format of the number is not localized; the default C locale
3744 is used irrespective of the user's locale.
3746 \sa setNum(), toInt()
3748 QByteArray QByteArray::number(int n, int base)
3760 QByteArray QByteArray::number(uint n, int base)
3772 QByteArray QByteArray::number(qlonglong n, int base)
3784 QByteArray QByteArray::number(qulonglong n, int base)
3794 Returns a byte array that contains the printed value of \a n,
3795 formatted in format \a f with precision \a prec.
3797 Argument \a n is formatted according to the \a f format specified,
3798 which is \c g by default, and can be any of the following:
3801 \header \i Format \i Meaning
3802 \row \i \c e \i format as [-]9.9e[+|-]999
3803 \row \i \c E \i format as [-]9.9E[+|-]999
3804 \row \i \c f \i format as [-]9.9
3805 \row \i \c g \i use \c e or \c f format, whichever is the most concise
3806 \row \i \c G \i use \c E or \c f format, whichever is the most concise
3809 With 'e', 'E', and 'f', \a prec is the number of digits after the
3810 decimal point. With 'g' and 'G', \a prec is the maximum number of
3811 significant digits (trailing zeroes are omitted).
3813 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 42
3815 \note The format of the number is not localized; the default C locale
3816 is used irrespective of the user's locale.
3820 QByteArray QByteArray::number(double n, char f, int prec)
3823 s.setNum(n, f, prec);
3828 Constructs a QByteArray that uses the first \a size bytes of the
3829 \a data array. The bytes are \e not copied. The QByteArray will
3830 contain the \a data pointer. The caller guarantees that \a data
3831 will not be deleted or modified as long as this QByteArray and any
3832 copies of it exist that have not been modified. In other words,
3833 because QByteArray is an \l{implicitly shared} class and the
3834 instance returned by this function contains the \a data pointer,
3835 the caller must not delete \a data or modify it directly as long
3836 as the returned QByteArray and any copies exist. However,
3837 QByteArray does not take ownership of \a data, so the QByteArray
3838 destructor will never delete the raw \a data, even when the
3839 last QByteArray referring to \a data is destroyed.
3841 A subsequent attempt to modify the contents of the returned
3842 QByteArray or any copy made from it will cause it to create a deep
3843 copy of the \a data array before doing the modification. This
3844 ensures that the raw \a data array itself will never be modified
3847 Here is an example of how to read data using a QDataStream on raw
3848 data in memory without copying the raw data into a QByteArray:
3850 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 43
3852 \warning A byte array created with fromRawData() is \e not
3853 null-terminated, unless the raw data contains a 0 character at
3854 position \a size. While that does not matter for QDataStream or
3855 functions like indexOf(), passing the byte array to a function
3856 accepting a \c{const char *} expected to be '\\0'-terminated will
3859 \sa setRawData(), data(), constData()
3862 QByteArray QByteArray::fromRawData(const char *data, int size)
3866 x = const_cast<Data *>(&shared_null.ba);
3868 x = const_cast<Data *>(&shared_empty.ba);
3870 x = static_cast<Data *>(malloc(sizeof(Data) + 1));
3872 x->ref.initializeOwned();
3875 x->capacityReserved = false;
3876 x->offset = data - (x->d + sizeof(qptrdiff));
3878 return QByteArray(x, 0, 0);
3884 Resets the QByteArray to use the first \a size bytes of the
3885 \a data array. The bytes are \e not copied. The QByteArray will
3886 contain the \a data pointer. The caller guarantees that \a data
3887 will not be deleted or modified as long as this QByteArray and any
3888 copies of it exist that have not been modified.
3890 This function can be used instead of fromRawData() to re-use
3891 existings QByteArray objects to save memory re-allocations.
3893 \sa fromRawData(), data(), constData()
3895 QByteArray &QByteArray::setRawData(const char *data, uint size)
3897 if (d->ref.isShared() || d->alloc) {
3898 *this = fromRawData(data, size);
3902 d->offset = data - (d->d + sizeof(qptrdiff));
3913 Returns a decoded copy of the Base64 array \a base64. Input is not checked
3914 for validity; invalid characters in the input are skipped, enabling the
3915 decoding process to continue with subsequent characters.
3919 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 44
3921 The algorithm used to decode Base64-encoded data is defined in \l{RFC 2045}.
3925 QByteArray QByteArray::fromBase64(const QByteArray &base64)
3927 unsigned int buf = 0;
3929 QByteArray tmp((base64.size() * 3) / 4, Qt::Uninitialized);
3932 for (int i = 0; i < base64.size(); ++i) {
3933 int ch = base64.at(i);
3936 if (ch >= 'A' && ch <= 'Z')
3938 else if (ch >= 'a' && ch <= 'z')
3940 else if (ch >= '0' && ch <= '9')
3950 buf = (buf << 6) | d;
3954 tmp[offset++] = buf >> nbits;
3955 buf &= (1 << nbits) - 1;
3960 tmp.truncate(offset);
3965 Returns a decoded copy of the hex encoded array \a hexEncoded. Input is not checked
3966 for validity; invalid characters in the input are skipped, enabling the
3967 decoding process to continue with subsequent characters.
3971 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 45
3975 QByteArray QByteArray::fromHex(const QByteArray &hexEncoded)
3977 QByteArray res((hexEncoded.size() + 1)/ 2, Qt::Uninitialized);
3978 uchar *result = (uchar *)res.data() + res.size();
3980 bool odd_digit = true;
3981 for (int i = hexEncoded.size() - 1; i >= 0; --i) {
3982 int ch = hexEncoded.at(i);
3984 if (ch >= '0' && ch <= '9')
3986 else if (ch >= 'a' && ch <= 'f')
3987 tmp = ch - 'a' + 10;
3988 else if (ch >= 'A' && ch <= 'F')
3989 tmp = ch - 'A' + 10;
3997 *result |= tmp << 4;
4002 res.remove(0, result - (const uchar *)res.constData());
4007 Returns a hex encoded copy of the byte array. The hex encoding uses the numbers 0-9 and
4012 QByteArray QByteArray::toHex() const
4014 QByteArray hex(d->size * 2, Qt::Uninitialized);
4015 char *hexData = hex.data();
4016 const uchar *data = (const uchar *)d->data();
4017 for (int i = 0; i < d->size; ++i) {
4018 int j = (data[i] >> 4) & 0xf;
4020 hexData[i*2] = (j + '0');
4022 hexData[i*2] = (j + 'a' - 10);
4025 hexData[i*2+1] = (j + '0');
4027 hexData[i*2+1] = (j + 'a' - 10);
4032 static void q_fromPercentEncoding(QByteArray *ba, char percent)
4037 char *data = ba->data();
4038 const char *inputPtr = data;
4041 int len = ba->count();
4047 if (c == percent && i + 2 < len) {
4051 if (a >= '0' && a <= '9') a -= '0';
4052 else if (a >= 'a' && a <= 'f') a = a - 'a' + 10;
4053 else if (a >= 'A' && a <= 'F') a = a - 'A' + 10;
4055 if (b >= '0' && b <= '9') b -= '0';
4056 else if (b >= 'a' && b <= 'f') b = b - 'a' + 10;
4057 else if (b >= 'A' && b <= 'F') b = b - 'A' + 10;
4059 *data++ = (char)((a << 4) | b);
4069 ba->truncate(outlen);
4072 void q_fromPercentEncoding(QByteArray *ba)
4074 q_fromPercentEncoding(ba, '%');
4080 Returns a decoded copy of the URI/URL-style percent-encoded \a input.
4081 The \a percent parameter allows you to replace the '%' character for
4082 another (for instance, '_' or '=').
4086 QByteArray text = QByteArray::fromPercentEncoding("Qt%20is%20great%33");
4087 text.data(); // returns "Qt is great!"
4090 \sa toPercentEncoding(), QUrl::fromPercentEncoding()
4092 QByteArray QByteArray::fromPercentEncoding(const QByteArray &input, char percent)
4095 return QByteArray(); // preserve null
4096 if (input.isEmpty())
4097 return QByteArray(input.data(), 0);
4099 QByteArray tmp = input;
4100 q_fromPercentEncoding(&tmp, percent);
4104 static inline bool q_strchr(const char str[], char chr)
4106 if (!str) return false;
4108 const char *ptr = str;
4110 while ((c = *ptr++))
4116 static inline char toHexHelper(char c)
4118 static const char hexnumbers[] = "0123456789ABCDEF";
4119 return hexnumbers[c & 0xf];
4122 static void q_toPercentEncoding(QByteArray *ba, const char *dontEncode, const char *alsoEncode, char percent)
4127 QByteArray input = *ba;
4128 int len = input.count();
4129 const char *inputData = input.constData();
4133 for (int i = 0; i < len; ++i) {
4134 unsigned char c = *inputData++;
4135 if (((c >= 0x61 && c <= 0x7A) // ALPHA
4136 || (c >= 0x41 && c <= 0x5A) // ALPHA
4137 || (c >= 0x30 && c <= 0x39) // DIGIT
4142 || q_strchr(dontEncode, c))
4143 && !q_strchr(alsoEncode, c)) {
4150 ba->resize(len*3); // worst case
4151 output = ba->data();
4153 output[length++] = percent;
4154 output[length++] = toHexHelper((c & 0xf0) >> 4);
4155 output[length++] = toHexHelper(c & 0xf);
4159 ba->truncate(length);
4162 void q_toPercentEncoding(QByteArray *ba, const char *exclude, const char *include)
4164 q_toPercentEncoding(ba, exclude, include, '%');
4167 void q_normalizePercentEncoding(QByteArray *ba, const char *exclude)
4169 q_fromPercentEncoding(ba, '%');
4170 q_toPercentEncoding(ba, exclude, 0, '%');
4176 Returns a URI/URL-style percent-encoded copy of this byte array. The
4177 \a percent parameter allows you to override the default '%'
4178 character for another.
4180 By default, this function will encode all characters that are not
4181 one of the following:
4183 ALPHA ("a" to "z" and "A" to "Z") / DIGIT (0 to 9) / "-" / "." / "_" / "~"
4185 To prevent characters from being encoded pass them to \a
4186 exclude. To force characters to be encoded pass them to \a
4187 include. The \a percent character is always encoded.
4192 QByteArray text = "{a fishy string?}";
4193 QByteArray ba = text.toPercentEncoding("{}", "s");
4194 qDebug(ba.constData());
4195 // prints "{a fi%73hy %73tring%3F}"
4198 The hex encoding uses the numbers 0-9 and the uppercase letters A-F.
4200 \sa fromPercentEncoding(), QUrl::toPercentEncoding()
4202 QByteArray QByteArray::toPercentEncoding(const QByteArray &exclude, const QByteArray &include,
4206 return QByteArray(); // preserve null
4208 return QByteArray(data(), 0);
4210 QByteArray include2 = include;
4211 if (percent != '%') // the default
4212 if ((percent >= 0x61 && percent <= 0x7A) // ALPHA
4213 || (percent >= 0x41 && percent <= 0x5A) // ALPHA
4214 || (percent >= 0x30 && percent <= 0x39) // DIGIT
4215 || percent == 0x2D // -
4216 || percent == 0x2E // .
4217 || percent == 0x5F // _
4218 || percent == 0x7E) // ~
4219 include2 += percent;
4221 QByteArray result = *this;
4222 q_toPercentEncoding(&result, exclude.nulTerminated().constData(), include2.nulTerminated().constData(), percent);
4227 /*! \typedef QByteArray::ConstIterator
4231 /*! \typedef QByteArray::Iterator
4235 /*! \typedef QByteArray::const_iterator
4239 /*! \typedef QByteArray::iterator
4243 /*! \typedef QByteArray::const_reference
4247 /*! \typedef QByteArray::reference
4251 /*! \typedef QByteArray::value_type
4256 \fn DataPtr &QByteArray::data_ptr()
4261 \typedef QByteArray::DataPtr