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 != sizeof(QByteArrayData))
66 const char *haystack0, int haystackLen, int from,
67 const char *needle0, int needleLen);
70 int qAllocMore(int alloc, int extra)
72 Q_ASSERT(alloc >= 0 && extra >= 0);
73 Q_ASSERT(alloc < (1 << 30) - extra);
75 unsigned nalloc = alloc + extra;
77 // Round up to next power of 2
79 // Assuming container is growing, always overshoot
82 nalloc |= nalloc >> 1;
83 nalloc |= nalloc >> 2;
84 nalloc |= nalloc >> 4;
85 nalloc |= nalloc >> 8;
86 nalloc |= nalloc >> 16;
89 Q_ASSERT(nalloc > unsigned(alloc + extra));
91 return nalloc - extra;
94 /*****************************************************************************
95 Safe and portable C string functions; extensions to standard string.h
96 *****************************************************************************/
98 /*! \relates QByteArray
100 Returns a duplicate string.
102 Allocates space for a copy of \a src, copies it, and returns a
103 pointer to the copy. If \a src is 0, it immediately returns 0.
105 Ownership is passed to the caller, so the returned string must be
106 deleted using \c delete[].
109 char *qstrdup(const char *src)
113 char *dst = new char[strlen(src) + 1];
114 return qstrcpy(dst, src);
117 /*! \relates QByteArray
119 Copies all the characters up to and including the '\\0' from \a
120 src into \a dst and returns a pointer to \a dst. If \a src is 0,
121 it immediately returns 0.
123 This function assumes that \a dst is large enough to hold the
129 char *qstrcpy(char *dst, const char *src)
133 #if defined(_MSC_VER) && _MSC_VER >= 1400
134 int len = strlen(src);
135 // This is actually not secure!!! It will be fixed
136 // properly in a later release!
137 if (len >= 0 && strcpy_s(dst, len+1, src) == 0)
141 return strcpy(dst, src);
145 /*! \relates QByteArray
147 A safe \c strncpy() function.
149 Copies at most \a len bytes from \a src (stopping at \a len or the
150 terminating '\\0' whichever comes first) into \a dst and returns a
151 pointer to \a dst. Guarantees that \a dst is '\\0'-terminated. If
152 \a src or \a dst is 0, returns 0 immediately.
154 This function assumes that \a dst is at least \a len characters
157 \note When compiling with Visual C++ compiler version 14.00
158 (Visual C++ 2005) or later, internally the function strncpy_s
164 char *qstrncpy(char *dst, const char *src, uint len)
168 #if defined(_MSC_VER) && _MSC_VER >= 1400
169 strncpy_s(dst, len, src, len-1);
171 strncpy(dst, src, len);
178 /*! \fn uint qstrlen(const char *str)
181 A safe \c strlen() function.
183 Returns the number of characters that precede the terminating '\\0',
189 /*! \fn uint qstrnlen(const char *str, uint maxlen)
193 A safe \c strnlen() function.
195 Returns the number of characters that precede the terminating '\\0', but
196 at most \a maxlen. If \a str is 0, returns 0.
204 A safe \c strcmp() function.
206 Compares \a str1 and \a str2. Returns a negative value if \a str1
207 is less than \a str2, 0 if \a str1 is equal to \a str2 or a
208 positive value if \a str1 is greater than \a str2.
210 Special case 1: Returns 0 if \a str1 and \a str2 are both 0.
212 Special case 2: Returns an arbitrary non-zero value if \a str1 is 0
213 or \a str2 is 0 (but not both).
215 \sa qstrncmp(), qstricmp(), qstrnicmp(), {8-bit Character Comparisons}
217 int qstrcmp(const char *str1, const char *str2)
219 return (str1 && str2) ? strcmp(str1, str2)
220 : (str1 ? 1 : (str2 ? -1 : 0));
223 /*! \fn int qstrncmp(const char *str1, const char *str2, uint len);
227 A safe \c strncmp() function.
229 Compares at most \a len bytes of \a str1 and \a str2.
231 Returns a negative value if \a str1 is less than \a str2, 0 if \a
232 str1 is equal to \a str2 or a positive value if \a str1 is greater
235 Special case 1: Returns 0 if \a str1 and \a str2 are both 0.
237 Special case 2: Returns a random non-zero value if \a str1 is 0
238 or \a str2 is 0 (but not both).
240 \sa qstrcmp(), qstricmp(), qstrnicmp(), {8-bit Character Comparisons}
243 /*! \relates QByteArray
245 A safe \c stricmp() function.
247 Compares \a str1 and \a str2 ignoring the case of the
248 characters. The encoding of the strings is assumed to be Latin-1.
250 Returns a negative value if \a str1 is less than \a str2, 0 if \a
251 str1 is equal to \a str2 or a positive value if \a str1 is greater
254 Special case 1: Returns 0 if \a str1 and \a str2 are both 0.
256 Special case 2: Returns a random non-zero value if \a str1 is 0
257 or \a str2 is 0 (but not both).
259 \sa qstrcmp(), qstrncmp(), qstrnicmp(), {8-bit Character Comparisons}
262 int qstricmp(const char *str1, const char *str2)
264 register const uchar *s1 = reinterpret_cast<const uchar *>(str1);
265 register const uchar *s2 = reinterpret_cast<const uchar *>(str2);
269 return s1 ? 1 : (s2 ? -1 : 0);
270 for (; !(res = (c = QChar::toLower((ushort)*s1)) - QChar::toLower((ushort)*s2)); s1++, s2++)
271 if (!c) // strings are equal
276 /*! \relates QByteArray
278 A safe \c strnicmp() function.
280 Compares at most \a len bytes of \a str1 and \a str2 ignoring the
281 case of the characters. The encoding of the strings is assumed to
284 Returns a negative value if \a str1 is less than \a str2, 0 if \a str1
285 is equal to \a str2 or a positive value if \a str1 is greater than \a
288 Special case 1: Returns 0 if \a str1 and \a str2 are both 0.
290 Special case 2: Returns a random non-zero value if \a str1 is 0
291 or \a str2 is 0 (but not both).
293 \sa qstrcmp(), qstrncmp(), qstricmp(), {8-bit Character Comparisons}
296 int qstrnicmp(const char *str1, const char *str2, uint len)
298 register const uchar *s1 = reinterpret_cast<const uchar *>(str1);
299 register const uchar *s2 = reinterpret_cast<const uchar *>(str2);
303 return s1 ? 1 : (s2 ? -1 : 0);
304 for (; len--; s1++, s2++) {
305 if ((res = (c = QChar::toLower((ushort)*s1)) - QChar::toLower((ushort)*s2)))
307 if (!c) // strings are equal
316 int qstrcmp(const QByteArray &str1, const char *str2)
319 return str1.isEmpty() ? 0 : +1;
321 const char *str1data = str1.constData();
322 const char *str1end = str1data + str1.length();
323 for ( ; str1data < str1end && *str2; ++str1data, ++str2) {
324 register int diff = int(uchar(*str1data)) - uchar(*str2);
326 // found a difference
332 // not the null, so we stopped because str1 is shorter
334 if (str1data < str1end)
335 // we haven't reached the end, so str1 must be longer
343 int qstrcmp(const QByteArray &str1, const QByteArray &str2)
345 int l1 = str1.length();
346 int l2 = str2.length();
347 int ret = memcmp(str1.constData(), str2.constData(), qMin(l1, l2));
351 // they matched qMin(l1, l2) bytes
352 // so the longer one is lexically after the shorter one
356 // the CRC table below is created by the following piece of code
358 static void createCRC16Table() // build CRC16 lookup table
360 register unsigned int i;
361 register unsigned int j;
362 unsigned short crc_tbl[16];
363 unsigned int v0, v1, v2, v3;
364 for (i = 0; i < 16; i++) {
371 #define SET_BIT(x, b, v) (x) |= (v) << (b)
386 printf("static const quint16 crc_tbl[16] = {\n");
387 for (int i = 0; i < 16; i +=4)
388 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]);
393 static const quint16 crc_tbl[16] = {
394 0x0000, 0x1081, 0x2102, 0x3183,
395 0x4204, 0x5285, 0x6306, 0x7387,
396 0x8408, 0x9489, 0xa50a, 0xb58b,
397 0xc60c, 0xd68d, 0xe70e, 0xf78f
403 Returns the CRC-16 checksum of the first \a len bytes of \a data.
405 The checksum is independent of the byte order (endianness).
407 \note This function is a 16-bit cache conserving (16 entry table)
408 implementation of the CRC-16-CCITT algorithm.
411 quint16 qChecksum(const char *data, uint len)
413 register quint16 crc = 0xffff;
415 const uchar *p = reinterpret_cast<const uchar *>(data);
418 crc = ((crc >> 4) & 0x0fff) ^ crc_tbl[((crc ^ c) & 15)];
420 crc = ((crc >> 4) & 0x0fff) ^ crc_tbl[((crc ^ c) & 15)];
422 return ~crc & 0xffff;
426 \fn QByteArray qCompress(const QByteArray& data, int compressionLevel)
430 Compresses the \a data byte array and returns the compressed data
433 The \a compressionLevel parameter specifies how much compression
434 should be used. Valid values are between 0 and 9, with 9
435 corresponding to the greatest compression (i.e. smaller compressed
436 data) at the cost of using a slower algorithm. Smaller values (8,
437 7, ..., 1) provide successively less compression at slightly
438 faster speeds. The value 0 corresponds to no compression at all.
439 The default value is -1, which specifies zlib's default
445 /*! \relates QByteArray
449 Compresses the first \a nbytes of \a data and returns the
450 compressed data in a new byte array.
453 #ifndef QT_NO_COMPRESS
454 QByteArray qCompress(const uchar* data, int nbytes, int compressionLevel)
457 return QByteArray(4, '\0');
460 qWarning("qCompress: Data is null");
463 if (compressionLevel < -1 || compressionLevel > 9)
464 compressionLevel = -1;
466 ulong len = nbytes + nbytes / 100 + 13;
470 bazip.resize(len + 4);
471 res = ::compress2((uchar*)bazip.data()+4, &len, (uchar*)data, nbytes, compressionLevel);
475 bazip.resize(len + 4);
476 bazip[0] = (nbytes & 0xff000000) >> 24;
477 bazip[1] = (nbytes & 0x00ff0000) >> 16;
478 bazip[2] = (nbytes & 0x0000ff00) >> 8;
479 bazip[3] = (nbytes & 0x000000ff);
482 qWarning("qCompress: Z_MEM_ERROR: Not enough memory");
489 } while (res == Z_BUF_ERROR);
496 \fn QByteArray qUncompress(const QByteArray &data)
500 Uncompresses the \a data byte array and returns a new byte array
501 with the uncompressed data.
503 Returns an empty QByteArray if the input data was corrupt.
505 This function will uncompress data compressed with qCompress()
506 from this and any earlier Qt version, back to Qt 3.1 when this
509 \b{Note:} If you want to use this function to uncompress external
510 data that was compressed using zlib, you first need to prepend a four
511 byte header to the byte array containing the data. The header must
512 contain the expected length (in bytes) of the uncompressed data,
513 expressed as an unsigned, big-endian, 32-bit integer.
518 /*! \relates QByteArray
522 Uncompresses the first \a nbytes of \a data and returns a new byte
523 array with the uncompressed data.
526 #ifndef QT_NO_COMPRESS
527 QByteArray qUncompress(const uchar* data, int nbytes)
530 qWarning("qUncompress: Data is null");
534 if (nbytes < 4 || (data[0]!=0 || data[1]!=0 || data[2]!=0 || data[3]!=0))
535 qWarning("qUncompress: Input data is corrupted");
538 ulong expectedSize = (data[0] << 24) | (data[1] << 16) |
539 (data[2] << 8) | (data[3] );
540 ulong len = qMax(expectedSize, 1ul);
541 QScopedPointer<QByteArray::Data, QScopedPointerPodDeleter> d;
545 if (len >= (1u << 31u) - sizeof(QByteArray::Data)) {
546 //QByteArray does not support that huge size anyway.
547 qWarning("qUncompress: Input data is corrupted");
550 QByteArray::Data *p = static_cast<QByteArray::Data *>(::realloc(d.data(), sizeof(QByteArray::Data) + alloc + 1));
552 // we are not allowed to crash here when compiling with QT_NO_EXCEPTIONS
553 qWarning("qUncompress: could not allocate enough memory to uncompress data");
556 d.take(); // realloc was successful
558 d->offset = sizeof(QByteArrayData);
560 int res = ::uncompress((uchar*)d->data(), &len,
561 (uchar*)data+4, nbytes-4);
566 if (len >= (1u << 31u) - sizeof(QByteArray::Data)) {
567 //QByteArray does not support that huge size anyway.
568 qWarning("qUncompress: Input data is corrupted");
571 QByteArray::Data *p = static_cast<QByteArray::Data *>(::realloc(d.data(), sizeof(QByteArray::Data) + len + 1));
573 // we are not allowed to crash here when compiling with QT_NO_EXCEPTIONS
574 qWarning("qUncompress: could not allocate enough memory to uncompress data");
577 d.take(); // realloc was successful
580 d->ref.initializeOwned();
583 d->capacityReserved = false;
584 d->offset = sizeof(QByteArrayData);
588 QByteArrayDataPtr dataPtr = { d.take() };
589 return QByteArray(dataPtr);
593 qWarning("qUncompress: Z_MEM_ERROR: Not enough memory");
601 qWarning("qUncompress: Z_DATA_ERROR: Input data is corrupted");
608 static inline bool qIsUpper(char c)
610 return c >= 'A' && c <= 'Z';
613 static inline char qToLower(char c)
615 if (c >= 'A' && c <= 'Z')
616 return c - 'A' + 'a';
621 const QStaticByteArrayData<1> QByteArray::shared_null = { Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER(0), { 0 } };
622 const QStaticByteArrayData<1> QByteArray::shared_empty = { Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER(0), { 0 } };
626 \brief The QByteArray class provides an array of bytes.
630 \ingroup string-processing
634 QByteArray can be used to store both raw bytes (including '\\0's)
635 and traditional 8-bit '\\0'-terminated strings. Using QByteArray
636 is much more convenient than using \c{const char *}. Behind the
637 scenes, it always ensures that the data is followed by a '\\0'
638 terminator, and uses \l{implicit sharing} (copy-on-write) to
639 reduce memory usage and avoid needless copying of data.
641 In addition to QByteArray, Qt also provides the QString class to
642 store string data. For most purposes, QString is the class you
643 want to use. It stores 16-bit Unicode characters, making it easy
644 to store non-ASCII/non-Latin-1 characters in your application.
645 Furthermore, QString is used throughout in the Qt API. The two
646 main cases where QByteArray is appropriate are when you need to
647 store raw binary data, and when memory conservation is critical
648 (e.g., with Qt for Embedded Linux).
650 One way to initialize a QByteArray is simply to pass a \c{const
651 char *} to its constructor. For example, the following code
652 creates a byte array of size 5 containing the data "Hello":
654 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 0
656 Although the size() is 5, the byte array also maintains an extra
657 '\\0' character at the end so that if a function is used that
658 asks for a pointer to the underlying data (e.g. a call to
659 data()), the data pointed to is guaranteed to be
662 QByteArray makes a deep copy of the \c{const char *} data, so you
663 can modify it later without experiencing side effects. (If for
664 performance reasons you don't want to take a deep copy of the
665 character data, use QByteArray::fromRawData() instead.)
667 Another approach is to set the size of the array using resize()
668 and to initialize the data byte per byte. QByteArray uses 0-based
669 indexes, just like C++ arrays. To access the byte at a particular
670 index position, you can use operator[](). On non-const byte
671 arrays, operator[]() returns a reference to a byte that can be
672 used on the left side of an assignment. For example:
674 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 1
676 For read-only access, an alternative syntax is to use at():
678 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 2
680 at() can be faster than operator[](), because it never causes a
681 \l{deep copy} to occur.
683 To extract many bytes at a time, use left(), right(), or mid().
685 A QByteArray can embed '\\0' bytes. The size() function always
686 returns the size of the whole array, including embedded '\\0'
687 bytes. If you want to obtain the length of the data up to and
688 excluding the first '\\0' character, call qstrlen() on the byte
691 After a call to resize(), newly allocated bytes have undefined
692 values. To set all the bytes to a particular value, call fill().
694 To obtain a pointer to the actual character data, call data() or
695 constData(). These functions return a pointer to the beginning of the data.
696 The pointer is guaranteed to remain valid until a non-const function is
697 called on the QByteArray. It is also guaranteed that the data ends with a
698 '\\0' byte unless the QByteArray was created from a \l{fromRawData()}{raw
699 data}. This '\\0' byte is automatically provided by QByteArray and is not
702 QByteArray provides the following basic functions for modifying
703 the byte data: append(), prepend(), insert(), replace(), and
704 remove(). For example:
706 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 3
708 The replace() and remove() functions' first two arguments are the
709 position from which to start erasing and the number of bytes that
712 When you append() data to a non-empty array, the array will be
713 reallocated and the new data copied to it. You can avoid this
714 behavior by calling reserve(), which preallocates a certain amount
715 of memory. You can also call capacity() to find out how much
716 memory QByteArray actually allocated. Data appended to an empty
719 A frequent requirement is to remove whitespace characters from a
720 byte array ('\\n', '\\t', ' ', etc.). If you want to remove
721 whitespace from both ends of a QByteArray, use trimmed(). If you
722 want to remove whitespace from both ends and replace multiple
723 consecutive whitespaces with a single space character within the
724 byte array, use simplified().
726 If you want to find all occurrences of a particular character or
727 substring in a QByteArray, use indexOf() or lastIndexOf(). The
728 former searches forward starting from a given index position, the
729 latter searches backward. Both return the index position of the
730 character or substring if they find it; otherwise, they return -1.
731 For example, here's a typical loop that finds all occurrences of a
732 particular substring:
734 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 4
736 If you simply want to check whether a QByteArray contains a
737 particular character or substring, use contains(). If you want to
738 find out how many times a particular character or substring
739 occurs in the byte array, use count(). If you want to replace all
740 occurrences of a particular value with another, use one of the
741 two-parameter replace() overloads.
743 QByteArrays can be compared using overloaded operators such as
744 operator<(), operator<=(), operator==(), operator>=(), and so on.
745 The comparison is based exclusively on the numeric values
746 of the characters and is very fast, but is not what a human would
747 expect. QString::localeAwareCompare() is a better choice for
748 sorting user-interface strings.
750 For historical reasons, QByteArray distinguishes between a null
751 byte array and an empty byte array. A \e null byte array is a
752 byte array that is initialized using QByteArray's default
753 constructor or by passing (const char *)0 to the constructor. An
754 \e empty byte array is any byte array with size 0. A null byte
755 array is always empty, but an empty byte array isn't necessarily
758 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 5
760 All functions except isNull() treat null byte arrays the same as
761 empty byte arrays. For example, data() returns a pointer to a
762 '\\0' character for a null byte array (\e not a null pointer),
763 and QByteArray() compares equal to QByteArray(""). We recommend
764 that you always use isEmpty() and avoid isNull().
766 \section1 Notes on Locale
768 \section2 Number-String Conversions
770 Functions that perform conversions between numeric data types and
771 strings are performed in the C locale, irrespective of the user's
772 locale settings. Use QString to perform locale-aware conversions
773 between numbers and strings.
775 \section2 8-bit Character Comparisons
777 In QByteArray, the notion of uppercase and lowercase and of which
778 character is greater than or less than another character is
779 locale dependent. This affects functions that support a case
780 insensitive option or that compare or lowercase or uppercase
781 their arguments. Case insensitive operations and comparisons will
782 be accurate if both strings contain only ASCII characters. (If \c
783 $LC_CTYPE is set, most Unix systems do "the right thing".)
784 Functions that this affects include contains(), indexOf(),
785 lastIndexOf(), operator<(), operator<=(), operator>(),
786 operator>=(), toLower() and toUpper().
788 This issue does not apply to QStrings since they represent
789 characters using Unicode.
791 \sa QString, QBitArray
794 /*! \fn QByteArray::iterator QByteArray::begin()
799 /*! \fn QByteArray::const_iterator QByteArray::begin() const
804 /*! \fn QByteArray::const_iterator QByteArray::cbegin() const
810 /*! \fn QByteArray::const_iterator QByteArray::constBegin() const
815 /*! \fn QByteArray::iterator QByteArray::end()
820 /*! \fn QByteArray::const_iterator QByteArray::end() const
825 /*! \fn QByteArray::const_iterator QByteArray::cend() const
831 /*! \fn QByteArray::const_iterator QByteArray::constEnd() const
836 /*! \fn void QByteArray::push_back(const QByteArray &other)
838 This function is provided for STL compatibility. It is equivalent
842 /*! \fn void QByteArray::push_back(const char *str)
846 Same as append(\a str).
849 /*! \fn void QByteArray::push_back(char ch)
853 Same as append(\a ch).
856 /*! \fn void QByteArray::push_front(const QByteArray &other)
858 This function is provided for STL compatibility. It is equivalent
859 to prepend(\a other).
862 /*! \fn void QByteArray::push_front(const char *str)
866 Same as prepend(\a str).
869 /*! \fn void QByteArray::push_front(char ch)
873 Same as prepend(\a ch).
876 /*! \fn QByteArray::QByteArray(const QByteArray &other)
878 Constructs a copy of \a other.
880 This operation takes \l{constant time}, because QByteArray is
881 \l{implicitly shared}. This makes returning a QByteArray from a
882 function very fast. If a shared instance is modified, it will be
883 copied (copy-on-write), taking \l{linear time}.
888 /*! \fn QByteArray::~QByteArray()
889 Destroys the byte array.
893 Assigns \a other to this byte array and returns a reference to
896 QByteArray &QByteArray::operator=(const QByteArray & other)
909 Assigns \a str to this byte array.
912 QByteArray &QByteArray::operator=(const char *str)
916 x = shared_null.data_ptr();
918 x = shared_empty.data_ptr();
920 int len = strlen(str);
921 if (d->ref.isShared() || len > int(d->alloc) || (len < d->size && len < int(d->alloc) >> 1))
924 memcpy(x->data(), str, len + 1); // include null terminator
934 /*! \fn void QByteArray::swap(QByteArray &other)
937 Swaps byte array \a other with this byte array. This operation is very
938 fast and never fails.
941 /*! \fn int QByteArray::size() const
943 Returns the number of bytes in this byte array.
945 The last byte in the byte array is at position size() - 1. In addition,
946 QByteArray ensures that the byte at position size() is always '\\0', so
947 that you can use the return value of data() and constData() as arguments to
948 functions that expect '\\0'-terminated strings. If the QByteArray object
949 was created from a \l{fromRawData()}{raw data} that didn't include the
950 trailing null-termination character then QByteArray doesn't add it
951 automaticall unless the \l{deep copy} is created.
954 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 6
956 \sa isEmpty(), resize()
959 /*! \fn bool QByteArray::isEmpty() const
961 Returns true if the byte array has size 0; otherwise returns false.
964 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 7
969 /*! \fn int QByteArray::capacity() const
971 Returns the maximum number of bytes that can be stored in the
972 byte array without forcing a reallocation.
974 The sole purpose of this function is to provide a means of fine
975 tuning QByteArray's memory usage. In general, you will rarely
976 ever need to call this function. If you want to know how many
977 bytes are in the byte array, call size().
979 \sa reserve(), squeeze()
982 /*! \fn void QByteArray::reserve(int size)
984 Attempts to allocate memory for at least \a size bytes. If you
985 know in advance how large the byte array will be, you can call
986 this function, and if you call resize() often you are likely to
987 get better performance. If \a size is an underestimate, the worst
988 that will happen is that the QByteArray will be a bit slower.
990 The sole purpose of this function is to provide a means of fine
991 tuning QByteArray's memory usage. In general, you will rarely
992 ever need to call this function. If you want to change the size
993 of the byte array, call resize().
995 \sa squeeze(), capacity()
998 /*! \fn void QByteArray::squeeze()
1000 Releases any memory not required to store the array's data.
1002 The sole purpose of this function is to provide a means of fine
1003 tuning QByteArray's memory usage. In general, you will rarely
1004 ever need to call this function.
1006 \sa reserve(), capacity()
1009 /*! \fn QByteArray::operator const char *() const
1010 \fn QByteArray::operator const void *() const
1012 \obsolete Use constData() instead.
1014 Returns a pointer to the data stored in the byte array. The
1015 pointer can be used to access the bytes that compose the array.
1016 The data is '\\0'-terminated. The pointer remains valid as long
1017 as the array isn't reallocated or destroyed.
1019 This operator is mostly useful to pass a byte array to a function
1020 that accepts a \c{const char *}.
1022 You can disable this operator by defining \c
1023 QT_NO_CAST_FROM_BYTEARRAY when you compile your applications.
1025 Note: A QByteArray can store any byte values including '\\0's,
1026 but most functions that take \c{char *} arguments assume that the
1027 data ends at the first '\\0' they encounter.
1033 \macro QT_NO_CAST_FROM_BYTEARRAY
1036 Disables automatic conversions from QByteArray to
1037 const char * or const void *.
1039 \sa QT_NO_CAST_TO_ASCII, QT_NO_CAST_FROM_ASCII
1042 /*! \fn char *QByteArray::data()
1044 Returns a pointer to the data stored in the byte array. The
1045 pointer can be used to access and modify the bytes that compose
1046 the array. The data is '\\0'-terminated, i.e. the number of
1047 bytes in the returned character string is size() + 1 for the
1051 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 8
1053 The pointer remains valid as long as the byte array isn't
1054 reallocated or destroyed. For read-only access, constData() is
1055 faster because it never causes a \l{deep copy} to occur.
1057 This function is mostly useful to pass a byte array to a function
1058 that accepts a \c{const char *}.
1060 The following example makes a copy of the char* returned by
1061 data(), but it will corrupt the heap and cause a crash because it
1062 does not allocate a byte for the '\\0' at the end:
1064 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 46
1066 This one allocates the correct amount of space:
1068 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 47
1070 Note: A QByteArray can store any byte values including '\\0's,
1071 but most functions that take \c{char *} arguments assume that the
1072 data ends at the first '\\0' they encounter.
1074 \sa constData(), operator[]()
1077 /*! \fn const char *QByteArray::data() const
1082 /*! \fn const char *QByteArray::constData() const
1084 Returns a pointer to the data stored in the byte array. The pointer can be
1085 used to access the bytes that compose the array. The data is
1086 '\\0'-terminated unless the QByteArray object was created from raw data.
1087 The pointer remains valid as long as the byte array isn't reallocated or
1090 This function is mostly useful to pass a byte array to a function
1091 that accepts a \c{const char *}.
1093 Note: A QByteArray can store any byte values including '\\0's,
1094 but most functions that take \c{char *} arguments assume that the
1095 data ends at the first '\\0' they encounter.
1097 \sa data(), operator[](), fromRawData()
1100 /*! \fn void QByteArray::detach()
1105 /*! \fn bool QByteArray::isDetached() const
1110 /*! \fn bool QByteArray::isSharedWith(const QByteArray &other) const
1115 /*! \fn char QByteArray::at(int i) const
1117 Returns the character at index position \a i in the byte array.
1119 \a i must be a valid index position in the byte array (i.e., 0 <=
1125 /*! \fn QByteRef QByteArray::operator[](int i)
1127 Returns the byte at index position \a i as a modifiable reference.
1129 If an assignment is made beyond the end of the byte array, the
1130 array is extended with resize() before the assignment takes
1134 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 9
1136 The return value is of type QByteRef, a helper class for
1137 QByteArray. When you get an object of type QByteRef, you can use
1138 it as if it were a char &. If you assign to it, the assignment
1139 will apply to the character in the QByteArray from which you got
1145 /*! \fn char QByteArray::operator[](int i) const
1152 /*! \fn QByteRef QByteArray::operator[](uint i)
1157 /*! \fn char QByteArray::operator[](uint i) const
1162 /*! \fn bool QByteArray::contains(const QByteArray &ba) const
1164 Returns true if the byte array contains an occurrence of the byte
1165 array \a ba; otherwise returns false.
1167 \sa indexOf(), count()
1170 /*! \fn bool QByteArray::contains(const char *str) const
1174 Returns true if the byte array contains the string \a str;
1175 otherwise returns false.
1178 /*! \fn bool QByteArray::contains(char ch) const
1182 Returns true if the byte array contains the character \a ch;
1183 otherwise returns false.
1188 Truncates the byte array at index position \a pos.
1190 If \a pos is beyond the end of the array, nothing happens.
1193 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 10
1195 \sa chop(), resize(), left()
1197 void QByteArray::truncate(int pos)
1205 Removes \a n bytes from the end of the byte array.
1207 If \a n is greater than size(), the result is an empty byte
1211 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 11
1213 \sa truncate(), resize(), left()
1216 void QByteArray::chop(int n)
1219 resize(d->size - n);
1223 /*! \fn QByteArray &QByteArray::operator+=(const QByteArray &ba)
1225 Appends the byte array \a ba onto the end of this byte array and
1226 returns a reference to this byte array.
1229 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 12
1231 Note: QByteArray is an \l{implicitly shared} class. Consequently,
1232 if \e this is an empty QByteArray, then \e this will just share
1233 the data held in \a ba. In this case, no copying of data is done,
1234 taking \l{constant time}. If a shared instance is modified, it will
1235 be copied (copy-on-write), taking \l{linear time}.
1237 If \e this is not an empty QByteArray, a deep copy of the data is
1238 performed, taking \l{linear time}.
1240 This operation typically does not suffer from allocation overhead,
1241 because QByteArray preallocates extra space at the end of the data
1242 so that it may grow without reallocating for each append operation.
1244 \sa append(), prepend()
1247 /*! \fn QByteArray &QByteArray::operator+=(const QString &str)
1251 Appends the string \a str onto the end of this byte array and
1252 returns a reference to this byte array. The Unicode data is
1253 converted into 8-bit characters using QString::toAscii().
1255 If the QString contains non-ASCII Unicode characters, using this
1256 operator can lead to loss of information. You can disable this
1257 operator by defining \c QT_NO_CAST_TO_ASCII when you compile your
1258 applications. You then need to call QString::toAscii() (or
1259 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
1260 explicitly if you want to convert the data to \c{const char *}.
1263 /*! \fn QByteArray &QByteArray::operator+=(const char *str)
1267 Appends the string \a str onto the end of this byte array and
1268 returns a reference to this byte array.
1271 /*! \fn QByteArray &QByteArray::operator+=(char ch)
1275 Appends the character \a ch onto the end of this byte array and
1276 returns a reference to this byte array.
1279 /*! \fn int QByteArray::length() const
1284 /*! \fn bool QByteArray::isNull() const
1286 Returns true if this byte array is null; otherwise returns false.
1289 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 13
1291 Qt makes a distinction between null byte arrays and empty byte
1292 arrays for historical reasons. For most applications, what
1293 matters is whether or not a byte array contains any data,
1294 and this can be determined using isEmpty().
1299 /*! \fn QByteArray::QByteArray()
1301 Constructs an empty byte array.
1307 Constructs a byte array containing the first \a size bytes of
1310 If \a data is 0, a null byte array is constructed.
1312 If \a size is negative, \a data is assumed to point to a nul-terminated
1313 string and its length is determined dynamically. The terminating
1314 nul-character is not considered part of the byte array.
1316 QByteArray makes a deep copy of the string data.
1321 QByteArray::QByteArray(const char *data, int size)
1324 d = shared_null.data_ptr();
1327 size = strlen(data);
1329 d = shared_empty.data_ptr();
1331 d = static_cast<Data *>(malloc(sizeof(Data) + size + 1));
1333 d->ref.initializeOwned();
1336 d->capacityReserved = false;
1337 d->offset = sizeof(QByteArrayData);
1338 memcpy(d->data(), data, size);
1339 d->data()[size] = '\0';
1345 Constructs a byte array of size \a size with every byte set to
1351 QByteArray::QByteArray(int size, char ch)
1354 d = shared_empty.data_ptr();
1356 d = static_cast<Data *>(malloc(sizeof(Data) + size + 1));
1358 d->ref.initializeOwned();
1361 d->capacityReserved = false;
1362 d->offset = sizeof(QByteArrayData);
1363 memset(d->data(), ch, size);
1364 d->data()[size] = '\0';
1371 Constructs a byte array of size \a size with uninitialized contents.
1374 QByteArray::QByteArray(int size, Qt::Initialization)
1376 d = static_cast<Data *>(malloc(sizeof(Data) + size + 1));
1378 d->ref.initializeOwned();
1381 d->capacityReserved = false;
1382 d->offset = sizeof(QByteArrayData);
1383 d->data()[size] = '\0';
1387 Sets the size of the byte array to \a size bytes.
1389 If \a size is greater than the current size, the byte array is
1390 extended to make it \a size bytes with the extra bytes added to
1391 the end. The new bytes are uninitialized.
1393 If \a size is less than the current size, bytes are removed from
1396 \sa size(), truncate()
1399 void QByteArray::resize(int size)
1404 if (IS_RAW_DATA(d) && !d->ref.isShared() && size < d->size) {
1409 if (size == 0 && !d->capacityReserved) {
1410 Data *x = shared_empty.data_ptr();
1411 if (!d->ref.deref())
1414 } else if (d == &shared_null.ba || d == &shared_empty.ba) {
1416 // Optimize the idiom:
1420 // which is used in place of the Qt 3 idiom:
1421 // QByteArray a(sz);
1423 Data *x = static_cast<Data *>(malloc(sizeof(Data) + size + 1));
1425 x->ref.initializeOwned();
1428 x->capacityReserved = false;
1429 x->offset = sizeof(QByteArrayData);
1430 x->data()[size] = '\0';
1433 if (d->ref.isShared() || size > int(d->alloc)
1434 || (!d->capacityReserved && size < d->size && size < int(d->alloc) >> 1))
1435 reallocData(size, true);
1438 d->data()[size] = '\0';
1444 Sets every byte in the byte array to character \a ch. If \a size
1445 is different from -1 (the default), the byte array is resized to
1446 size \a size beforehand.
1449 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 14
1454 QByteArray &QByteArray::fill(char ch, int size)
1456 resize(size < 0 ? d->size : size);
1458 memset(d->data(), ch, d->size);
1462 void QByteArray::reallocData(int alloc, bool grow)
1465 alloc = qAllocMore(alloc + 1, sizeof(Data)) - 1;
1467 if (d->ref.isShared() || IS_RAW_DATA(d)) {
1468 Data *x = static_cast<Data *>(malloc(sizeof(Data) + alloc + 1));
1470 x->ref.initializeOwned();
1471 x->size = qMin(alloc, d->size);
1473 x->capacityReserved = d->capacityReserved;
1474 x->offset = sizeof(QByteArrayData);
1475 ::memcpy(x->data(), d->data(), x->size);
1476 x->data()[x->size] = '\0';
1477 if (!d->ref.deref())
1481 Data *x = static_cast<Data *>(::realloc(d, sizeof(Data) + alloc + 1));
1484 x->offset = sizeof(QByteArrayData);
1489 void QByteArray::expand(int i)
1491 resize(qMax(i + 1, d->size));
1496 Return a QByteArray that is sure to be NUL-terminated.
1498 By default, all QByteArray have an extra NUL at the end,
1499 guaranteeing that assumption. However, if QByteArray::fromRawData
1500 is used, then the NUL is there only if the user put it there. We
1503 QByteArray QByteArray::nulTerminated() const
1505 // is this fromRawData?
1506 if (!IS_RAW_DATA(d))
1507 return *this; // no, then we're sure we're zero terminated
1509 QByteArray copy(*this);
1515 Prepends the byte array \a ba to this byte array and returns a
1516 reference to this byte array.
1519 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 15
1521 This is the same as insert(0, \a ba).
1523 Note: QByteArray is an \l{implicitly shared} class. Consequently,
1524 if \e this is an empty QByteArray, then \e this will just share
1525 the data held in \a ba. In this case, no copying of data is done,
1526 taking \l{constant time}. If a shared instance is modified, it will
1527 be copied (copy-on-write), taking \l{linear time}.
1529 If \e this is not an empty QByteArray, a deep copy of the data is
1530 performed, taking \l{linear time}.
1532 \sa append(), insert()
1535 QByteArray &QByteArray::prepend(const QByteArray &ba)
1537 if ((d == &shared_null.ba || d == &shared_empty.ba) && !IS_RAW_DATA(ba.d)) {
1539 } else if (ba.d != &shared_null.ba) {
1540 QByteArray tmp = *this;
1550 Prepends the string \a str to this byte array.
1553 QByteArray &QByteArray::prepend(const char *str)
1555 return prepend(str, qstrlen(str));
1562 Prepends \a len bytes of the string \a str to this byte array.
1565 QByteArray &QByteArray::prepend(const char *str, int len)
1568 if (d->ref.isShared() || d->size + len > int(d->alloc))
1569 reallocData(d->size + len, true);
1570 memmove(d->data()+len, d->data(), d->size);
1571 memcpy(d->data(), str, len);
1573 d->data()[d->size] = '\0';
1581 Prepends the character \a ch to this byte array.
1584 QByteArray &QByteArray::prepend(char ch)
1586 if (d->ref.isShared() || d->size + 1 > int(d->alloc))
1587 reallocData(d->size + 1, true);
1588 memmove(d->data()+1, d->data(), d->size);
1591 d->data()[d->size] = '\0';
1596 Appends the byte array \a ba onto the end of this byte array.
1599 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 16
1601 This is the same as insert(size(), \a ba).
1603 Note: QByteArray is an \l{implicitly shared} class. Consequently,
1604 if \e this is an empty QByteArray, then \e this will just share
1605 the data held in \a ba. In this case, no copying of data is done,
1606 taking \l{constant time}. If a shared instance is modified, it will
1607 be copied (copy-on-write), taking \l{linear time}.
1609 If \e this is not an empty QByteArray, a deep copy of the data is
1610 performed, taking \l{linear time}.
1612 This operation typically does not suffer from allocation overhead,
1613 because QByteArray preallocates extra space at the end of the data
1614 so that it may grow without reallocating for each append operation.
1616 \sa operator+=(), prepend(), insert()
1619 QByteArray &QByteArray::append(const QByteArray &ba)
1621 if ((d == &shared_null.ba || d == &shared_empty.ba) && !IS_RAW_DATA(ba.d)) {
1623 } else if (ba.d != &shared_null.ba) {
1624 if (d->ref.isShared() || d->size + ba.d->size > int(d->alloc))
1625 reallocData(d->size + ba.d->size, true);
1626 memcpy(d->data() + d->size, ba.d->data(), ba.d->size);
1627 d->size += ba.d->size;
1628 d->data()[d->size] = '\0';
1633 /*! \fn QByteArray &QByteArray::append(const QString &str)
1637 Appends the string \a str to this byte array. The Unicode data is
1638 converted into 8-bit characters using QString::toAscii().
1640 If the QString contains non-ASCII Unicode characters, using this
1641 function can lead to loss of information. You can disable this
1642 function by defining \c QT_NO_CAST_TO_ASCII when you compile your
1643 applications. You then need to call QString::toAscii() (or
1644 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
1645 explicitly if you want to convert the data to \c{const char *}.
1651 Appends the string \a str to this byte array.
1654 QByteArray& QByteArray::append(const char *str)
1657 int len = strlen(str);
1658 if (d->ref.isShared() || d->size + len > int(d->alloc))
1659 reallocData(d->size + len, true);
1660 memcpy(d->data() + d->size, str, len + 1); // include null terminator
1669 Appends the first \a len characters of the string \a str to this byte
1670 array and returns a reference to this byte array.
1672 If \a len is negative, the length of the string will be determined
1673 automatically using qstrlen(). If \a len is zero or \a str is
1674 null, nothing is appended to the byte array. Ensure that \a len is
1675 \e not longer than \a str.
1678 QByteArray &QByteArray::append(const char *str, int len)
1683 if (d->ref.isShared() || d->size + len > int(d->alloc))
1684 reallocData(d->size + len, true);
1685 memcpy(d->data() + d->size, str, len); // include null terminator
1687 d->data()[d->size] = '\0';
1695 Appends the character \a ch to this byte array.
1698 QByteArray& QByteArray::append(char ch)
1700 if (d->ref.isShared() || d->size + 1 > int(d->alloc))
1701 reallocData(d->size + 1, true);
1702 d->data()[d->size++] = ch;
1703 d->data()[d->size] = '\0';
1709 Inserts \a len bytes from the array \a arr at position \a pos and returns a
1710 reference the modified byte array.
1712 static inline QByteArray &qbytearray_insert(QByteArray *ba,
1713 int pos, const char *arr, int len)
1717 if (pos < 0 || len <= 0 || arr == 0)
1720 int oldsize = ba->size();
1721 ba->resize(qMax(pos, oldsize) + len);
1722 char *dst = ba->data();
1724 ::memset(dst + oldsize, 0x20, pos - oldsize);
1726 ::memmove(dst + pos + len, dst + pos, oldsize - pos);
1727 memcpy(dst + pos, arr, len);
1732 Inserts the byte array \a ba at index position \a i and returns a
1733 reference to this byte array.
1736 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 17
1738 \sa append(), prepend(), replace(), remove()
1741 QByteArray &QByteArray::insert(int i, const QByteArray &ba)
1743 QByteArray copy(ba);
1744 return qbytearray_insert(this, i, copy.d->data(), copy.d->size);
1748 \fn QByteArray &QByteArray::insert(int i, const QString &str)
1752 Inserts the string \a str at index position \a i in the byte
1753 array. The Unicode data is converted into 8-bit characters using
1756 If \a i is greater than size(), the array is first extended using
1759 If the QString contains non-ASCII Unicode characters, using this
1760 function can lead to loss of information. You can disable this
1761 function by defining \c QT_NO_CAST_TO_ASCII when you compile your
1762 applications. You then need to call QString::toAscii() (or
1763 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
1764 explicitly if you want to convert the data to \c{const char *}.
1770 Inserts the string \a str at position \a i in the byte array.
1772 If \a i is greater than size(), the array is first extended using
1776 QByteArray &QByteArray::insert(int i, const char *str)
1778 return qbytearray_insert(this, i, str, qstrlen(str));
1785 Inserts \a len bytes of the string \a str at position
1786 \a i in the byte array.
1788 If \a i is greater than size(), the array is first extended using
1792 QByteArray &QByteArray::insert(int i, const char *str, int len)
1794 return qbytearray_insert(this, i, str, len);
1800 Inserts character \a ch at index position \a i in the byte array.
1801 If \a i is greater than size(), the array is first extended using
1805 QByteArray &QByteArray::insert(int i, char ch)
1807 return qbytearray_insert(this, i, &ch, 1);
1811 Removes \a len bytes from the array, starting at index position \a
1812 pos, and returns a reference to the array.
1814 If \a pos is out of range, nothing happens. If \a pos is valid,
1815 but \a pos + \a len is larger than the size of the array, the
1816 array is truncated at position \a pos.
1819 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 18
1821 \sa insert(), replace()
1824 QByteArray &QByteArray::remove(int pos, int len)
1826 if (len <= 0 || pos >= d->size || pos < 0)
1829 if (pos + len >= d->size) {
1832 memmove(d->data() + pos, d->data() + pos + len, d->size - pos - len);
1833 resize(d->size - len);
1839 Replaces \a len bytes from index position \a pos with the byte
1840 array \a after, and returns a reference to this byte array.
1843 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 19
1845 \sa insert(), remove()
1848 QByteArray &QByteArray::replace(int pos, int len, const QByteArray &after)
1850 if (len == after.d->size && (pos + len <= d->size)) {
1852 memmove(d->data() + pos, after.d->data(), len*sizeof(char));
1855 QByteArray copy(after);
1858 return insert(pos, copy);
1862 /*! \fn QByteArray &QByteArray::replace(int pos, int len, const char *after)
1866 Replaces \a len bytes from index position \a pos with the zero terminated
1869 Notice: this can change the length of the byte array.
1871 QByteArray &QByteArray::replace(int pos, int len, const char *after)
1873 return replace(pos,len,after,qstrlen(after));
1876 /*! \fn QByteArray &QByteArray::replace(int pos, int len, const char *after, int alen)
1880 Replaces \a len bytes from index position \a pos with \a alen bytes
1881 from the string \a after. \a after is allowed to have '\0' characters.
1885 QByteArray &QByteArray::replace(int pos, int len, const char *after, int alen)
1887 if (len == alen && (pos + len <= d->size)) {
1889 memcpy(d->data() + pos, after, len*sizeof(char));
1893 return qbytearray_insert(this, pos, after, alen);
1897 // ### optimize all other replace method, by offering
1898 // QByteArray::replace(const char *before, int blen, const char *after, int alen)
1903 Replaces every occurrence of the byte array \a before with the
1904 byte array \a after.
1907 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 20
1910 QByteArray &QByteArray::replace(const QByteArray &before, const QByteArray &after)
1912 if (isNull() || before.d == after.d)
1915 QByteArray aft = after;
1919 return replace(before.constData(), before.size(), aft.constData(), aft.size());
1923 \fn QByteArray &QByteArray::replace(const char *before, const QByteArray &after)
1926 Replaces every occurrence of the string \a before with the
1927 byte array \a after.
1930 QByteArray &QByteArray::replace(const char *c, const QByteArray &after)
1932 QByteArray aft = after;
1936 return replace(c, qstrlen(c), aft.constData(), aft.size());
1940 \fn QByteArray &QByteArray::replace(const char *before, int bsize, const char *after, int asize)
1943 Replaces every occurrence of the string \a before with the string \a after.
1944 Since the sizes of the strings are given by \a bsize and \a asize, they
1945 may contain zero characters and do not need to be zero-terminated.
1948 QByteArray &QByteArray::replace(const char *before, int bsize, const char *after, int asize)
1950 if (isNull() || (before == after && bsize == asize))
1953 // protect against before or after being part of this
1954 const char *a = after;
1955 const char *b = before;
1956 if (after >= d->data() && after < d->data() + d->size) {
1957 char *copy = (char *)malloc(asize);
1959 memcpy(copy, after, asize);
1962 if (before >= d->data() && before < d->data() + d->size) {
1963 char *copy = (char *)malloc(bsize);
1965 memcpy(copy, before, bsize);
1969 QByteArrayMatcher matcher(before, bsize);
1974 if (bsize == asize) {
1976 while ((index = matcher.indexIn(*this, index)) != -1) {
1977 memcpy(d + index, after, asize);
1981 } else if (asize < bsize) {
1985 while ((index = matcher.indexIn(*this, index)) != -1) {
1987 int msize = index - movestart;
1989 memmove(d + to, d + movestart, msize);
1996 memcpy(d + to, after, asize);
2004 int msize = len - movestart;
2006 memmove(d + to, d + movestart, msize);
2007 resize(len - num*(bsize-asize));
2010 // the most complex case. We don't want to lose performance by doing repeated
2011 // copies and reallocs of the string.
2012 while (index != -1) {
2016 index = matcher.indexIn(*this, index);
2019 indices[pos++] = index;
2021 // avoid infinite loop
2028 // we have a table of replacement positions, use them for fast replacing
2029 int adjust = pos*(asize-bsize);
2030 // index has to be adjusted in case we get back into the loop above.
2033 int newlen = len + adjust;
2039 d = this->d->data();
2043 int movestart = indices[pos] + bsize;
2044 int insertstart = indices[pos] + pos*(asize-bsize);
2045 int moveto = insertstart + asize;
2046 memmove(d + moveto, d + movestart, (moveend - movestart));
2048 memcpy(d + insertstart, after, asize);
2049 moveend = movestart - bsize;
2065 \fn QByteArray &QByteArray::replace(const QByteArray &before, const char *after)
2068 Replaces every occurrence of the byte array \a before with the
2072 /*! \fn QByteArray &QByteArray::replace(const QString &before, const QByteArray &after)
2076 Replaces every occurrence of the string \a before with the byte
2077 array \a after. The Unicode data is converted into 8-bit
2078 characters using QString::toAscii().
2080 If the QString contains non-ASCII Unicode characters, using this
2081 function can lead to loss of information. You can disable this
2082 function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2083 applications. You then need to call QString::toAscii() (or
2084 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2085 explicitly if you want to convert the data to \c{const char *}.
2088 /*! \fn QByteArray &QByteArray::replace(const QString &before, const char *after)
2091 Replaces every occurrence of the string \a before with the string
2095 /*! \fn QByteArray &QByteArray::replace(const char *before, const char *after)
2099 Replaces every occurrence of the string \a before with the string
2106 Replaces every occurrence of the character \a before with the
2107 byte array \a after.
2110 QByteArray &QByteArray::replace(char before, const QByteArray &after)
2112 char b[2] = { before, '\0' };
2113 QByteArray cb = fromRawData(b, 1);
2114 return replace(cb, after);
2117 /*! \fn QByteArray &QByteArray::replace(char before, const QString &after)
2121 Replaces every occurrence of the character \a before with the
2122 string \a after. The Unicode data is converted into 8-bit
2123 characters using QString::toAscii().
2125 If the QString contains non-ASCII Unicode characters, using this
2126 function can lead to loss of information. You can disable this
2127 function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2128 applications. You then need to call QString::toAscii() (or
2129 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2130 explicitly if you want to convert the data to \c{const char *}.
2133 /*! \fn QByteArray &QByteArray::replace(char before, const char *after)
2137 Replaces every occurrence of the character \a before with the
2144 Replaces every occurrence of the character \a before with the
2148 QByteArray &QByteArray::replace(char before, char after)
2152 char *e = i + d->size;
2161 Splits the byte array into subarrays wherever \a sep occurs, and
2162 returns the list of those arrays. If \a sep does not match
2163 anywhere in the byte array, split() returns a single-element list
2164 containing this byte array.
2167 QList<QByteArray> QByteArray::split(char sep) const
2169 QList<QByteArray> list;
2172 while ((end = indexOf(sep, start)) != -1) {
2173 list.append(mid(start, end - start));
2176 list.append(mid(start));
2183 Returns a copy of this byte array repeated the specified number of \a times.
2185 If \a times is less than 1, an empty byte array is returned.
2190 QByteArray ba("ab");
2191 ba.repeated(4); // returns "abababab"
2194 QByteArray QByteArray::repeated(int times) const
2202 return QByteArray();
2205 const int resultSize = times * d->size;
2208 result.reserve(resultSize);
2209 if (int(result.d->alloc) != resultSize)
2210 return QByteArray(); // not enough memory
2212 memcpy(result.d->data(), d->data(), d->size);
2214 int sizeSoFar = d->size;
2215 char *end = result.d->data() + sizeSoFar;
2217 const int halfResultSize = resultSize >> 1;
2218 while (sizeSoFar <= halfResultSize) {
2219 memcpy(end, result.d->data(), sizeSoFar);
2223 memcpy(end, result.d->data(), resultSize - sizeSoFar);
2224 result.d->data()[resultSize] = '\0';
2225 result.d->size = resultSize;
2230 if (ol_minus_1 < sizeof(uint) * CHAR_BIT) \
2231 hashHaystack -= (a) << ol_minus_1; \
2235 Returns the index position of the first occurrence of the byte
2236 array \a ba in this byte array, searching forward from index
2237 position \a from. Returns -1 if \a ba could not be found.
2240 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 21
2242 \sa lastIndexOf(), contains(), count()
2245 int QByteArray::indexOf(const QByteArray &ba, int from) const
2247 const int ol = ba.d->size;
2251 return indexOf(*ba.d->data(), from);
2253 const int l = d->size;
2254 if (from > d->size || ol + from > l)
2257 return qFindByteArray(d->data(), d->size, from, ba.d->data(), ol);
2260 /*! \fn int QByteArray::indexOf(const QString &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
2266 \a from. Returns -1 if \a str could not be found.
2268 The Unicode data is converted into 8-bit characters using
2271 If the QString contains non-ASCII Unicode characters, using this
2272 function can lead to loss of information. You can disable this
2273 function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2274 applications. You then need to call QString::toAscii() (or
2275 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2276 explicitly if you want to convert the data to \c{const char *}.
2279 /*! \fn int QByteArray::indexOf(const char *str, int from) const
2283 Returns the index position of the first occurrence of the string
2284 \a str in the byte array, searching forward from index position \a
2285 from. Returns -1 if \a str could not be found.
2287 int QByteArray::indexOf(const char *c, int from) const
2289 const int ol = qstrlen(c);
2291 return indexOf(*c, from);
2293 const int l = d->size;
2294 if (from > d->size || ol + from > l)
2299 return qFindByteArray(d->data(), d->size, from, c, ol);
2305 Returns the index position of the first occurrence of the
2306 character \a ch in the byte array, searching forward from index
2307 position \a from. Returns -1 if \a ch could not be found.
2310 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 22
2312 \sa lastIndexOf(), contains()
2315 int QByteArray::indexOf(char ch, int from) const
2318 from = qMax(from + d->size, 0);
2319 if (from < d->size) {
2320 const char *n = d->data() + from - 1;
2321 const char *e = d->data() + d->size;
2324 return n - d->data();
2330 static int lastIndexOfHelper(const char *haystack, int l, const char *needle, int ol, int from)
2335 if (from < 0 || from > l)
2340 const char *end = haystack;
2342 const uint ol_minus_1 = ol - 1;
2343 const char *n = needle + ol_minus_1;
2344 const char *h = haystack + ol_minus_1;
2345 uint hashNeedle = 0, hashHaystack = 0;
2347 for (idx = 0; idx < ol; ++idx) {
2348 hashNeedle = ((hashNeedle<<1) + *(n-idx));
2349 hashHaystack = ((hashHaystack<<1) + *(h-idx));
2351 hashHaystack -= *haystack;
2352 while (haystack >= end) {
2353 hashHaystack += *haystack;
2354 if (hashHaystack == hashNeedle && memcmp(needle, haystack, ol) == 0)
2355 return haystack - end;
2357 REHASH(*(haystack + ol));
2364 \fn int QByteArray::lastIndexOf(const QByteArray &ba, int from) const
2366 Returns the index position of the last occurrence of the byte
2367 array \a ba in this byte array, searching backward from index
2368 position \a from. If \a from is -1 (the default), the search
2369 starts at the last byte. Returns -1 if \a ba could not be found.
2372 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 23
2374 \sa indexOf(), contains(), count()
2377 int QByteArray::lastIndexOf(const QByteArray &ba, int from) const
2379 const int ol = ba.d->size;
2381 return lastIndexOf(*ba.d->data(), from);
2383 return lastIndexOfHelper(d->data(), d->size, ba.d->data(), ol, from);
2386 /*! \fn int QByteArray::lastIndexOf(const QString &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 The Unicode data is converted into 8-bit characters using
2398 If the QString contains non-ASCII Unicode characters, using this
2399 function can lead to loss of information. You can disable this
2400 function by defining \c QT_NO_CAST_TO_ASCII when you compile your
2401 applications. You then need to call QString::toAscii() (or
2402 QString::toLatin1() or QString::toUtf8() or QString::toLocal8Bit())
2403 explicitly if you want to convert the data to \c{const char *}.
2406 /*! \fn int QByteArray::lastIndexOf(const char *str, int from) const
2409 Returns the index position of the last occurrence of the string \a
2410 str in the byte array, searching backward from index position \a
2411 from. If \a from is -1 (the default), the search starts at the
2412 last (size() - 1) byte. Returns -1 if \a str could not be found.
2414 int QByteArray::lastIndexOf(const char *str, int from) const
2416 const int ol = qstrlen(str);
2418 return lastIndexOf(*str, from);
2420 return lastIndexOfHelper(d->data(), d->size, str, ol, from);
2426 Returns the index position of the last occurrence of character \a
2427 ch in the byte array, searching backward from index position \a
2428 from. If \a from is -1 (the default), the search starts at the
2429 last (size() - 1) byte. Returns -1 if \a ch could not be found.
2432 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 24
2434 \sa indexOf(), contains()
2437 int QByteArray::lastIndexOf(char ch, int from) const
2441 else if (from > d->size)
2444 const char *b = d->data();
2445 const char *n = d->data() + from + 1;
2454 Returns the number of (potentially overlapping) occurrences of
2455 byte array \a ba in this byte array.
2457 \sa contains(), indexOf()
2460 int QByteArray::count(const QByteArray &ba) const
2464 if (d->size > 500 && ba.d->size > 5) {
2465 QByteArrayMatcher matcher(ba);
2466 while ((i = matcher.indexIn(*this, i + 1)) != -1)
2469 while ((i = indexOf(ba, i + 1)) != -1)
2478 Returns the number of (potentially overlapping) occurrences of
2479 string \a str in the byte array.
2482 int QByteArray::count(const char *str) const
2484 return count(fromRawData(str, qstrlen(str)));
2490 Returns the number of occurrences of character \a ch in the byte
2493 \sa contains(), indexOf()
2496 int QByteArray::count(char ch) const
2499 const char *i = d->data() + d->size;
2500 const char *b = d->data();
2507 /*! \fn int QByteArray::count() const
2515 Returns true if this byte array starts with byte array \a ba;
2516 otherwise returns false.
2519 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 25
2521 \sa endsWith(), left()
2523 bool QByteArray::startsWith(const QByteArray &ba) const
2525 if (d == ba.d || ba.d->size == 0)
2527 if (d->size < ba.d->size)
2529 return memcmp(d->data(), ba.d->data(), ba.d->size) == 0;
2534 Returns true if this byte array starts with string \a str;
2535 otherwise returns false.
2537 bool QByteArray::startsWith(const char *str) const
2541 int len = strlen(str);
2544 return qstrncmp(d->data(), str, len) == 0;
2549 Returns true if this byte array starts with character \a ch;
2550 otherwise returns false.
2552 bool QByteArray::startsWith(char ch) const
2556 return d->data()[0] == ch;
2560 Returns true if this byte array ends with byte array \a ba;
2561 otherwise returns false.
2564 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 26
2566 \sa startsWith(), right()
2568 bool QByteArray::endsWith(const QByteArray &ba) const
2570 if (d == ba.d || ba.d->size == 0)
2572 if (d->size < ba.d->size)
2574 return memcmp(d->data() + d->size - ba.d->size, ba.d->data(), ba.d->size) == 0;
2579 Returns true if this byte array ends with string \a str; otherwise
2582 bool QByteArray::endsWith(const char *str) const
2586 int len = strlen(str);
2589 return qstrncmp(d->data() + d->size - len, str, len) == 0;
2594 Returns true if this byte array ends with character \a ch;
2595 otherwise returns false.
2597 bool QByteArray::endsWith(char ch) const
2601 return d->data()[d->size - 1] == ch;
2605 Returns a byte array that contains the leftmost \a len bytes of
2608 The entire byte array is returned if \a len is greater than
2612 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 27
2614 \sa right(), mid(), startsWith(), truncate()
2617 QByteArray QByteArray::left(int len) const
2623 return QByteArray(d->data(), len);
2627 Returns a byte array that contains the rightmost \a len bytes of
2630 The entire byte array is returned if \a len is greater than
2634 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 28
2636 \sa endsWith(), left(), mid()
2639 QByteArray QByteArray::right(int len) const
2645 return QByteArray(d->data() + d->size - len, len);
2649 Returns a byte array containing \a len bytes from this byte array,
2650 starting at position \a pos.
2652 If \a len is -1 (the default), or \a pos + \a len >= size(),
2653 returns a byte array containing all bytes starting at position \a
2654 pos until the end of the byte array.
2657 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 29
2662 QByteArray QByteArray::mid(int pos, int len) const
2664 if (d == &shared_null.ba || d == &shared_empty.ba || pos > d->size)
2665 return QByteArray();
2667 len = d->size - pos;
2672 if (len + pos > d->size)
2673 len = d->size - pos;
2674 if (pos == 0 && len == d->size)
2676 return QByteArray(d->data() + pos, len);
2680 Returns a lowercase copy of the byte array. The bytearray is
2681 interpreted as a Latin-1 encoded string.
2684 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 30
2686 \sa toUpper(), {8-bit Character Comparisons}
2688 QByteArray QByteArray::toLower() const
2690 QByteArray s(*this);
2691 register uchar *p = reinterpret_cast<uchar *>(s.data());
2694 *p = QChar::toLower((ushort)*p);
2702 Returns an uppercase copy of the byte array. The bytearray is
2703 interpreted as a Latin-1 encoded string.
2706 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 31
2708 \sa toLower(), {8-bit Character Comparisons}
2711 QByteArray QByteArray::toUpper() const
2713 QByteArray s(*this);
2714 register uchar *p = reinterpret_cast<uchar *>(s.data());
2717 *p = QChar::toUpper((ushort)*p);
2724 /*! \fn void QByteArray::clear()
2726 Clears the contents of the byte array and makes it empty.
2728 \sa resize(), isEmpty()
2731 void QByteArray::clear()
2733 if (!d->ref.deref())
2735 d = shared_null.data_ptr();
2738 #if !defined(QT_NO_DATASTREAM) || (defined(QT_BOOTSTRAPPED) && !defined(QT_BUILD_QMAKE))
2740 /*! \relates QByteArray
2742 Writes byte array \a ba to the stream \a out and returns a reference
2745 \sa {Serializing Qt Data Types}
2748 QDataStream &operator<<(QDataStream &out, const QByteArray &ba)
2750 if (ba.isNull() && out.version() >= 6) {
2751 out << (quint32)0xffffffff;
2754 return out.writeBytes(ba.constData(), ba.size());
2757 /*! \relates QByteArray
2759 Reads a byte array into \a ba from the stream \a in and returns a
2760 reference to the stream.
2762 \sa {Serializing Qt Data Types}
2765 QDataStream &operator>>(QDataStream &in, QByteArray &ba)
2770 if (len == 0xffffffff)
2773 const quint32 Step = 1024 * 1024;
2774 quint32 allocated = 0;
2777 int blockSize = qMin(Step, len - allocated);
2778 ba.resize(allocated + blockSize);
2779 if (in.readRawData(ba.data() + allocated, blockSize) != blockSize) {
2781 in.setStatus(QDataStream::ReadPastEnd);
2784 allocated += blockSize;
2785 } while (allocated < len);
2789 #endif // QT_NO_DATASTREAM
2791 /*! \fn bool QByteArray::operator==(const QString &str) const
2793 Returns true if this byte array is equal to string \a str;
2794 otherwise returns false.
2796 The Unicode data is converted into 8-bit characters using
2799 The comparison is case sensitive.
2801 You can disable this operator by defining \c
2802 QT_NO_CAST_FROM_ASCII when you compile your applications. You
2803 then need to call QString::fromAscii(), QString::fromLatin1(),
2804 QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2805 you want to convert the byte array to a QString before doing the
2809 /*! \fn bool QByteArray::operator!=(const QString &str) const
2811 Returns true if this byte array is not equal to string \a str;
2812 otherwise returns false.
2814 The Unicode data is converted into 8-bit characters using
2817 The comparison is case sensitive.
2819 You can disable this operator by defining \c
2820 QT_NO_CAST_FROM_ASCII when you compile your applications. You
2821 then need to call QString::fromAscii(), QString::fromLatin1(),
2822 QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2823 you want to convert the byte array to a QString before doing the
2827 /*! \fn bool QByteArray::operator<(const QString &str) const
2829 Returns true if this byte array is lexically less than string \a
2830 str; otherwise returns false.
2832 The Unicode data is converted into 8-bit characters using
2835 The comparison is case sensitive.
2837 You can disable this operator by defining \c
2838 QT_NO_CAST_FROM_ASCII when you compile your applications. You
2839 then need to call QString::fromAscii(), QString::fromLatin1(),
2840 QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2841 you want to convert the byte array to a QString before doing the
2845 /*! \fn bool QByteArray::operator>(const QString &str) const
2847 Returns true if this byte array is lexically greater than string
2848 \a str; otherwise returns false.
2850 The Unicode data is converted into 8-bit characters using
2853 The comparison is case sensitive.
2855 You can disable this operator by defining \c
2856 QT_NO_CAST_FROM_ASCII when you compile your applications. You
2857 then need to call QString::fromAscii(), QString::fromLatin1(),
2858 QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2859 you want to convert the byte array to a QString before doing the
2863 /*! \fn bool QByteArray::operator<=(const QString &str) const
2865 Returns true if this byte array is lexically less than or equal
2866 to string \a str; otherwise returns false.
2868 The Unicode data is converted into 8-bit characters using
2871 The comparison is case sensitive.
2873 You can disable this operator by defining \c
2874 QT_NO_CAST_FROM_ASCII when you compile your applications. You
2875 then need to call QString::fromAscii(), QString::fromLatin1(),
2876 QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2877 you want to convert the byte array to a QString before doing the
2881 /*! \fn bool QByteArray::operator>=(const QString &str) const
2883 Returns true if this byte array is greater than or equal to string
2884 \a str; otherwise returns false.
2886 The Unicode data is converted into 8-bit characters using
2889 The comparison is case sensitive.
2891 You can disable this operator by defining \c
2892 QT_NO_CAST_FROM_ASCII when you compile your applications. You
2893 then need to call QString::fromAscii(), QString::fromLatin1(),
2894 QString::fromUtf8(), or QString::fromLocal8Bit() explicitly if
2895 you want to convert the byte array to a QString before doing the
2899 /*! \fn bool operator==(const QByteArray &a1, const QByteArray &a2)
2904 Returns true if byte array \a a1 is equal to byte array \a a2;
2905 otherwise returns false.
2908 /*! \fn bool operator==(const QByteArray &a1, const char *a2)
2913 Returns true if byte array \a a1 is equal to string \a a2;
2914 otherwise returns false.
2917 /*! \fn bool operator==(const char *a1, const QByteArray &a2)
2922 Returns true if string \a a1 is equal to byte array \a a2;
2923 otherwise returns false.
2926 /*! \fn bool operator!=(const QByteArray &a1, const QByteArray &a2)
2931 Returns true if byte array \a a1 is not equal to byte array \a a2;
2932 otherwise returns false.
2935 /*! \fn bool operator!=(const QByteArray &a1, const char *a2)
2940 Returns true if byte array \a a1 is not equal to string \a a2;
2941 otherwise returns false.
2944 /*! \fn bool operator!=(const char *a1, const QByteArray &a2)
2949 Returns true if string \a a1 is not equal to byte array \a a2;
2950 otherwise returns false.
2953 /*! \fn bool operator<(const QByteArray &a1, const QByteArray &a2)
2958 Returns true if byte array \a a1 is lexically less than byte array
2959 \a a2; otherwise returns false.
2962 /*! \fn inline bool operator<(const QByteArray &a1, const char *a2)
2967 Returns true if byte array \a a1 is lexically less than string
2968 \a a2; otherwise returns false.
2971 /*! \fn bool operator<(const char *a1, const QByteArray &a2)
2976 Returns true if string \a a1 is lexically less than byte array
2977 \a a2; otherwise returns false.
2980 /*! \fn bool operator<=(const QByteArray &a1, const QByteArray &a2)
2985 Returns true if byte array \a a1 is lexically less than or equal
2986 to byte array \a a2; otherwise returns false.
2989 /*! \fn bool operator<=(const QByteArray &a1, const char *a2)
2994 Returns true if byte array \a a1 is lexically less than or equal
2995 to string \a a2; otherwise returns false.
2998 /*! \fn bool operator<=(const char *a1, const QByteArray &a2)
3003 Returns true if string \a a1 is lexically less than or equal
3004 to byte array \a a2; otherwise returns false.
3007 /*! \fn bool operator>(const QByteArray &a1, const QByteArray &a2)
3012 Returns true if byte array \a a1 is lexically greater than byte
3013 array \a a2; otherwise returns false.
3016 /*! \fn bool operator>(const QByteArray &a1, const char *a2)
3021 Returns true if byte array \a a1 is lexically greater than string
3022 \a a2; otherwise returns false.
3025 /*! \fn bool operator>(const char *a1, const QByteArray &a2)
3030 Returns true if string \a a1 is lexically greater than byte array
3031 \a a2; otherwise returns false.
3034 /*! \fn bool operator>=(const QByteArray &a1, const QByteArray &a2)
3039 Returns true if byte array \a a1 is lexically greater than or
3040 equal to byte array \a a2; otherwise returns false.
3043 /*! \fn bool operator>=(const QByteArray &a1, const char *a2)
3048 Returns true if byte array \a a1 is lexically greater than or
3049 equal to string \a a2; otherwise returns false.
3052 /*! \fn bool operator>=(const char *a1, const QByteArray &a2)
3057 Returns true if string \a a1 is lexically greater than or
3058 equal to byte array \a a2; otherwise returns false.
3061 /*! \fn const QByteArray operator+(const QByteArray &a1, const QByteArray &a2)
3064 Returns a byte array that is the result of concatenating byte
3065 array \a a1 and byte array \a a2.
3067 \sa QByteArray::operator+=()
3070 /*! \fn const QByteArray operator+(const QByteArray &a1, const char *a2)
3075 Returns a byte array that is the result of concatenating byte
3076 array \a a1 and string \a a2.
3079 /*! \fn const QByteArray operator+(const QByteArray &a1, char a2)
3084 Returns a byte array that is the result of concatenating byte
3085 array \a a1 and character \a a2.
3088 /*! \fn const QByteArray operator+(const char *a1, const QByteArray &a2)
3093 Returns a byte array that is the result of concatenating string
3094 \a a1 and byte array \a a2.
3097 /*! \fn const QByteArray operator+(char a1, const QByteArray &a2)
3102 Returns a byte array that is the result of concatenating character
3103 \a a1 and byte array \a a2.
3107 Returns a byte array that has whitespace removed from the start
3108 and the end, and which has each sequence of internal whitespace
3109 replaced with a single space.
3111 Whitespace means any character for which the standard C++
3112 isspace() function returns true. This includes the ASCII
3113 characters '\\t', '\\n', '\\v', '\\f', '\\r', and ' '.
3116 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 32
3120 QByteArray QByteArray::simplified() const
3124 QByteArray result(d->size, Qt::Uninitialized);
3125 const char *from = d->data();
3126 const char *fromend = from + d->size;
3128 char *to = result.d->data();
3130 while (from!=fromend && isspace(uchar(*from)))
3132 while (from!=fromend && !isspace(uchar(*from)))
3133 to[outc++] = *from++;
3139 if (outc > 0 && to[outc-1] == ' ')
3141 result.resize(outc);
3146 Returns a byte array that has whitespace removed from the start
3149 Whitespace means any character for which the standard C++
3150 isspace() function returns true. This includes the ASCII
3151 characters '\\t', '\\n', '\\v', '\\f', '\\r', and ' '.
3154 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 33
3156 Unlike simplified(), trimmed() leaves internal whitespace alone.
3160 QByteArray QByteArray::trimmed() const
3164 const char *s = d->data();
3165 if (!isspace(uchar(*s)) && !isspace(uchar(s[d->size-1])))
3168 int end = d->size - 1;
3169 while (start<=end && isspace(uchar(s[start]))) // skip white space from start
3171 if (start <= end) { // only white space
3172 while (end && isspace(uchar(s[end]))) // skip white space from end
3175 int l = end - start + 1;
3177 QByteArrayDataPtr empty = { shared_empty.data_ptr() };
3178 return QByteArray(empty);
3180 return QByteArray(s+start, l);
3184 Returns a byte array of size \a width that contains this byte
3185 array padded by the \a fill character.
3187 If \a truncate is false and the size() of the byte array is more
3188 than \a width, then the returned byte array is a copy of this byte
3191 If \a truncate is true and the size() of the byte array is more
3192 than \a width, then any bytes in a copy of the byte array
3193 after position \a width are removed, and the copy is returned.
3196 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 34
3198 \sa rightJustified()
3201 QByteArray QByteArray::leftJustified(int width, char fill, bool truncate) const
3205 int padlen = width - len;
3207 result.resize(len+padlen);
3209 memcpy(result.d->data(), d->data(), len);
3210 memset(result.d->data()+len, fill, padlen);
3213 result = left(width);
3221 Returns a byte array of size \a width that contains the \a fill
3222 character followed by this byte array.
3224 If \a truncate is false and the size of the byte array is more
3225 than \a width, then the returned byte array is a copy of this byte
3228 If \a truncate is true and the size of the byte array is more
3229 than \a width, then the resulting byte array is truncated at
3233 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 35
3238 QByteArray QByteArray::rightJustified(int width, char fill, bool truncate) const
3242 int padlen = width - len;
3244 result.resize(len+padlen);
3246 memcpy(result.d->data()+padlen, data(), len);
3247 memset(result.d->data(), fill, padlen);
3250 result = left(width);
3257 bool QByteArray::isNull() const { return d == &shared_null.ba; }
3261 Returns the byte array converted to a \c {long long} using base \a
3262 base, which is 10 by default and must be between 2 and 36, or 0.
3264 If \a base is 0, the base is determined automatically using the
3265 following rules: If the byte array begins with "0x", it is assumed to
3266 be hexadecimal; if it begins with "0", it is assumed to be octal;
3267 otherwise it is assumed to be decimal.
3269 Returns 0 if the conversion fails.
3271 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3272 false; otherwise *\a{ok} is set to true.
3274 \note The conversion of the number is performed in the default C locale,
3275 irrespective of the user's locale.
3280 qlonglong QByteArray::toLongLong(bool *ok, int base) const
3282 #if defined(QT_CHECK_RANGE)
3283 if (base != 0 && (base < 2 || base > 36)) {
3284 qWarning("QByteArray::toLongLong: Invalid base %d", base);
3289 return QLocalePrivate::bytearrayToLongLong(nulTerminated().constData(), base, ok);
3293 Returns the byte array converted to an \c {unsigned long long}
3294 using base \a base, which is 10 by default and must be between 2
3297 If \a base is 0, the base is determined automatically using the
3298 following rules: If the byte array begins with "0x", it is assumed to
3299 be hexadecimal; if it begins with "0", it is assumed to be octal;
3300 otherwise it is assumed to be decimal.
3302 Returns 0 if the conversion fails.
3304 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3305 false; otherwise *\a{ok} is set to true.
3307 \note The conversion of the number is performed in the default C locale,
3308 irrespective of the user's locale.
3313 qulonglong QByteArray::toULongLong(bool *ok, int base) const
3315 #if defined(QT_CHECK_RANGE)
3316 if (base != 0 && (base < 2 || base > 36)) {
3317 qWarning("QByteArray::toULongLong: Invalid base %d", base);
3322 return QLocalePrivate::bytearrayToUnsLongLong(nulTerminated().constData(), base, ok);
3327 Returns the byte array converted to an \c int using base \a
3328 base, which is 10 by default and must be between 2 and 36, or 0.
3330 If \a base is 0, the base is determined automatically using the
3331 following rules: If the byte array begins with "0x", it is assumed to
3332 be hexadecimal; if it begins with "0", it is assumed to be octal;
3333 otherwise it is assumed to be decimal.
3335 Returns 0 if the conversion fails.
3337 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3338 false; otherwise *\a{ok} is set to true.
3340 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 36
3342 \note The conversion of the number is performed in the default C locale,
3343 irrespective of the user's locale.
3348 int QByteArray::toInt(bool *ok, int base) const
3350 qlonglong v = toLongLong(ok, base);
3351 if (v < INT_MIN || v > INT_MAX) {
3360 Returns the byte array converted to an \c {unsigned int} using base \a
3361 base, which is 10 by default and must be between 2 and 36, or 0.
3363 If \a base is 0, the base is determined automatically using the
3364 following rules: If the byte array begins with "0x", it is assumed to
3365 be hexadecimal; if it begins with "0", it is assumed to be octal;
3366 otherwise it is assumed to be decimal.
3368 Returns 0 if the conversion fails.
3370 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3371 false; otherwise *\a{ok} is set to true.
3373 \note The conversion of the number is performed in the default C locale,
3374 irrespective of the user's locale.
3379 uint QByteArray::toUInt(bool *ok, int base) const
3381 qulonglong v = toULongLong(ok, base);
3393 Returns the byte array converted to a \c long int using base \a
3394 base, which is 10 by default and must be between 2 and 36, or 0.
3396 If \a base is 0, the base is determined automatically using the
3397 following rules: If the byte array begins with "0x", it is assumed to
3398 be hexadecimal; if it begins with "0", it is assumed to be octal;
3399 otherwise it is assumed to be decimal.
3401 Returns 0 if the conversion fails.
3403 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3404 false; otherwise *\a{ok} is set to true.
3406 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 37
3408 \note The conversion of the number is performed in the default C locale,
3409 irrespective of the user's locale.
3413 long QByteArray::toLong(bool *ok, int base) const
3415 qlonglong v = toLongLong(ok, base);
3416 if (v < LONG_MIN || v > LONG_MAX) {
3427 Returns the byte array converted to an \c {unsigned long int} using base \a
3428 base, which is 10 by default and must be between 2 and 36, or 0.
3430 If \a base is 0, the base is determined automatically using the
3431 following rules: If the byte array begins with "0x", it is assumed to
3432 be hexadecimal; if it begins with "0", it is assumed to be octal;
3433 otherwise it is assumed to be decimal.
3435 Returns 0 if the conversion fails.
3437 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3438 false; otherwise *\a{ok} is set to true.
3440 \note The conversion of the number is performed in the default C locale,
3441 irrespective of the user's locale.
3445 ulong QByteArray::toULong(bool *ok, int base) const
3447 qulonglong v = toULongLong(ok, base);
3448 if (v > ULONG_MAX) {
3457 Returns the byte array converted to a \c short using base \a
3458 base, which is 10 by default and must be between 2 and 36, or 0.
3460 If \a base is 0, the base is determined automatically using the
3461 following rules: If the byte array begins with "0x", it is assumed to
3462 be hexadecimal; if it begins with "0", it is assumed to be octal;
3463 otherwise it is assumed to be decimal.
3465 Returns 0 if the conversion fails.
3467 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3468 false; otherwise *\a{ok} is set to true.
3470 \note The conversion of the number is performed in the default C locale,
3471 irrespective of the user's locale.
3476 short QByteArray::toShort(bool *ok, int base) const
3478 qlonglong v = toLongLong(ok, base);
3479 if (v < SHRT_MIN || v > SHRT_MAX) {
3488 Returns the byte array converted to an \c {unsigned short} using base \a
3489 base, which is 10 by default and must be between 2 and 36, or 0.
3491 If \a base is 0, the base is determined automatically using the
3492 following rules: If the byte array begins with "0x", it is assumed to
3493 be hexadecimal; if it begins with "0", it is assumed to be octal;
3494 otherwise it is assumed to be decimal.
3496 Returns 0 if the conversion fails.
3498 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3499 false; otherwise *\a{ok} is set to true.
3501 \note The conversion of the number is performed in the default C locale,
3502 irrespective of the user's locale.
3507 ushort QByteArray::toUShort(bool *ok, int base) const
3509 qulonglong v = toULongLong(ok, base);
3510 if (v > USHRT_MAX) {
3520 Returns the byte array converted to a \c double value.
3522 Returns 0.0 if the conversion fails.
3524 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3525 false; otherwise *\a{ok} is set to true.
3527 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 38
3529 \note The conversion of the number is performed in the default C locale,
3530 irrespective of the user's locale.
3535 double QByteArray::toDouble(bool *ok) const
3537 return QLocalePrivate::bytearrayToDouble(nulTerminated().constData(), ok);
3541 Returns the byte array converted to a \c float value.
3543 Returns 0.0 if the conversion fails.
3545 If \a ok is not 0: if a conversion error occurs, *\a{ok} is set to
3546 false; otherwise *\a{ok} is set to true.
3548 \note The conversion of the number is performed in the default C locale,
3549 irrespective of the user's locale.
3554 float QByteArray::toFloat(bool *ok) const
3556 return float(toDouble(ok));
3560 Returns a copy of the byte array, encoded as Base64.
3562 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 39
3564 The algorithm used to encode Base64-encoded data is defined in \l{RFC 2045}.
3568 QByteArray QByteArray::toBase64() const
3570 const char alphabet[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
3571 "ghijklmn" "opqrstuv" "wxyz0123" "456789+/";
3572 const char padchar = '=';
3575 QByteArray tmp((d->size * 4) / 3 + 3, Qt::Uninitialized);
3578 char *out = tmp.data();
3579 while (i < d->size) {
3581 chunk |= int(uchar(d->data()[i++])) << 16;
3585 chunk |= int(uchar(d->data()[i++])) << 8;
3586 if (i == d->size) padlen = 1;
3587 else chunk |= int(uchar(d->data()[i++]));
3590 int j = (chunk & 0x00fc0000) >> 18;
3591 int k = (chunk & 0x0003f000) >> 12;
3592 int l = (chunk & 0x00000fc0) >> 6;
3593 int m = (chunk & 0x0000003f);
3594 *out++ = alphabet[j];
3595 *out++ = alphabet[k];
3596 if (padlen > 1) *out++ = padchar;
3597 else *out++ = alphabet[l];
3598 if (padlen > 0) *out++ = padchar;
3599 else *out++ = alphabet[m];
3602 tmp.truncate(out - tmp.data());
3607 \fn QByteArray &QByteArray::setNum(int n, int base)
3609 Sets the byte array to the printed value of \a n in base \a base (10
3610 by default) and returns a reference to the byte array. The \a base can
3611 be any value between 2 and 36.
3614 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 40
3616 \note The format of the number is not localized; the default C locale
3617 is used irrespective of the user's locale.
3619 \sa number(), toInt()
3623 \fn QByteArray &QByteArray::setNum(uint n, int base)
3630 \fn QByteArray &QByteArray::setNum(short n, int base)
3637 \fn QByteArray &QByteArray::setNum(ushort n, int base)
3649 QByteArray &QByteArray::setNum(qlonglong 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()->longLongToString(n, -1, base).toLatin1();
3668 QByteArray &QByteArray::setNum(qulonglong n, int base)
3670 #if defined(QT_CHECK_RANGE)
3671 if (base < 2 || base > 36) {
3672 qWarning("QByteArray::setNum: Invalid base %d", base);
3676 QLocale locale(QLocale::C);
3677 *this = locale.d()->unsLongLongToString(n, -1, base).toLatin1();
3684 Sets the byte array to the printed value of \a n, formatted in format
3685 \a f with precision \a prec, and returns a reference to the
3688 The format \a f can be any of the following:
3691 \header \li Format \li Meaning
3692 \row \li \c e \li format as [-]9.9e[+|-]999
3693 \row \li \c E \li format as [-]9.9E[+|-]999
3694 \row \li \c f \li format as [-]9.9
3695 \row \li \c g \li use \c e or \c f format, whichever is the most concise
3696 \row \li \c G \li use \c E or \c f format, whichever is the most concise
3699 With 'e', 'E', and 'f', \a prec is the number of digits after the
3700 decimal point. With 'g' and 'G', \a prec is the maximum number of
3701 significant digits (trailing zeroes are omitted).
3703 \note The format of the number is not localized; the default C locale
3704 is used irrespective of the user's locale.
3709 QByteArray &QByteArray::setNum(double n, char f, int prec)
3711 QLocalePrivate::DoubleForm form = QLocalePrivate::DFDecimal;
3715 flags = QLocalePrivate::CapitalEorX;
3720 form = QLocalePrivate::DFDecimal;
3723 form = QLocalePrivate::DFExponent;
3726 form = QLocalePrivate::DFSignificantDigits;
3729 #if defined(QT_CHECK_RANGE)
3730 qWarning("QByteArray::setNum: Invalid format char '%c'", f);
3735 QLocale locale(QLocale::C);
3736 *this = locale.d()->doubleToString(n, prec, form, -1, flags).toLatin1();
3741 \fn QByteArray &QByteArray::setNum(float n, char f, int prec)
3744 Sets the byte array to the printed value of \a n, formatted in format
3745 \a f with precision \a prec, and returns a reference to the
3748 \note The format of the number is not localized; the default C locale
3749 is used irrespective of the user's locale.
3755 Returns a byte array containing the string equivalent of the
3756 number \a n to base \a base (10 by default). The \a base can be
3757 any value between 2 and 36.
3760 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 41
3762 \note The format of the number is not localized; the default C locale
3763 is used irrespective of the user's locale.
3765 \sa setNum(), toInt()
3767 QByteArray QByteArray::number(int n, int base)
3779 QByteArray QByteArray::number(uint n, int base)
3791 QByteArray QByteArray::number(qlonglong n, int base)
3803 QByteArray QByteArray::number(qulonglong n, int base)
3813 Returns a byte array that contains the printed value of \a n,
3814 formatted in format \a f with precision \a prec.
3816 Argument \a n is formatted according to the \a f format specified,
3817 which is \c g by default, and can be any of the following:
3820 \header \li Format \li Meaning
3821 \row \li \c e \li format as [-]9.9e[+|-]999
3822 \row \li \c E \li format as [-]9.9E[+|-]999
3823 \row \li \c f \li format as [-]9.9
3824 \row \li \c g \li use \c e or \c f format, whichever is the most concise
3825 \row \li \c G \li use \c E or \c f format, whichever is the most concise
3828 With 'e', 'E', and 'f', \a prec is the number of digits after the
3829 decimal point. With 'g' and 'G', \a prec is the maximum number of
3830 significant digits (trailing zeroes are omitted).
3832 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 42
3834 \note The format of the number is not localized; the default C locale
3835 is used irrespective of the user's locale.
3839 QByteArray QByteArray::number(double n, char f, int prec)
3842 s.setNum(n, f, prec);
3847 Constructs a QByteArray that uses the first \a size bytes of the
3848 \a data array. The bytes are \e not copied. The QByteArray will
3849 contain the \a data pointer. The caller guarantees that \a data
3850 will not be deleted or modified as long as this QByteArray and any
3851 copies of it exist that have not been modified. In other words,
3852 because QByteArray is an \l{implicitly shared} class and the
3853 instance returned by this function contains the \a data pointer,
3854 the caller must not delete \a data or modify it directly as long
3855 as the returned QByteArray and any copies exist. However,
3856 QByteArray does not take ownership of \a data, so the QByteArray
3857 destructor will never delete the raw \a data, even when the
3858 last QByteArray referring to \a data is destroyed.
3860 A subsequent attempt to modify the contents of the returned
3861 QByteArray or any copy made from it will cause it to create a deep
3862 copy of the \a data array before doing the modification. This
3863 ensures that the raw \a data array itself will never be modified
3866 Here is an example of how to read data using a QDataStream on raw
3867 data in memory without copying the raw data into a QByteArray:
3869 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 43
3871 \warning A byte array created with fromRawData() is \e not
3872 null-terminated, unless the raw data contains a 0 character at
3873 position \a size. While that does not matter for QDataStream or
3874 functions like indexOf(), passing the byte array to a function
3875 accepting a \c{const char *} expected to be '\\0'-terminated will
3878 \sa setRawData(), data(), constData()
3881 QByteArray QByteArray::fromRawData(const char *data, int size)
3885 x = shared_null.data_ptr();
3887 x = shared_empty.data_ptr();
3889 x = static_cast<Data *>(malloc(sizeof(Data)));
3891 x->ref.initializeOwned();
3894 x->capacityReserved = false;
3895 x->offset = data - reinterpret_cast<char *>(x);
3897 QByteArrayDataPtr dataPtr = { x };
3898 return QByteArray(dataPtr);
3904 Resets the QByteArray to use the first \a size bytes of the
3905 \a data array. The bytes are \e not copied. The QByteArray will
3906 contain the \a data pointer. The caller guarantees that \a data
3907 will not be deleted or modified as long as this QByteArray and any
3908 copies of it exist that have not been modified.
3910 This function can be used instead of fromRawData() to re-use
3911 existings QByteArray objects to save memory re-allocations.
3913 \sa fromRawData(), data(), constData()
3915 QByteArray &QByteArray::setRawData(const char *data, uint size)
3917 if (d->ref.isShared() || d->alloc) {
3918 *this = fromRawData(data, size);
3922 d->offset = data - reinterpret_cast<char *>(d);
3924 d->offset = sizeof(QByteArrayData);
3933 Returns a decoded copy of the Base64 array \a base64. Input is not checked
3934 for validity; invalid characters in the input are skipped, enabling the
3935 decoding process to continue with subsequent characters.
3939 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 44
3941 The algorithm used to decode Base64-encoded data is defined in \l{RFC 2045}.
3945 QByteArray QByteArray::fromBase64(const QByteArray &base64)
3947 unsigned int buf = 0;
3949 QByteArray tmp((base64.size() * 3) / 4, Qt::Uninitialized);
3952 for (int i = 0; i < base64.size(); ++i) {
3953 int ch = base64.at(i);
3956 if (ch >= 'A' && ch <= 'Z')
3958 else if (ch >= 'a' && ch <= 'z')
3960 else if (ch >= '0' && ch <= '9')
3970 buf = (buf << 6) | d;
3974 tmp[offset++] = buf >> nbits;
3975 buf &= (1 << nbits) - 1;
3980 tmp.truncate(offset);
3985 Returns a decoded copy of the hex encoded array \a hexEncoded. Input is not checked
3986 for validity; invalid characters in the input are skipped, enabling the
3987 decoding process to continue with subsequent characters.
3991 \snippet doc/src/snippets/code/src_corelib_tools_qbytearray.cpp 45
3995 QByteArray QByteArray::fromHex(const QByteArray &hexEncoded)
3997 QByteArray res((hexEncoded.size() + 1)/ 2, Qt::Uninitialized);
3998 uchar *result = (uchar *)res.data() + res.size();
4000 bool odd_digit = true;
4001 for (int i = hexEncoded.size() - 1; i >= 0; --i) {
4002 int ch = hexEncoded.at(i);
4004 if (ch >= '0' && ch <= '9')
4006 else if (ch >= 'a' && ch <= 'f')
4007 tmp = ch - 'a' + 10;
4008 else if (ch >= 'A' && ch <= 'F')
4009 tmp = ch - 'A' + 10;
4017 *result |= tmp << 4;
4022 res.remove(0, result - (const uchar *)res.constData());
4027 Returns a hex encoded copy of the byte array. The hex encoding uses the numbers 0-9 and
4032 QByteArray QByteArray::toHex() const
4034 QByteArray hex(d->size * 2, Qt::Uninitialized);
4035 char *hexData = hex.data();
4036 const uchar *data = (const uchar *)d->data();
4037 for (int i = 0; i < d->size; ++i) {
4038 int j = (data[i] >> 4) & 0xf;
4040 hexData[i*2] = (j + '0');
4042 hexData[i*2] = (j + 'a' - 10);
4045 hexData[i*2+1] = (j + '0');
4047 hexData[i*2+1] = (j + 'a' - 10);
4052 static void q_fromPercentEncoding(QByteArray *ba, char percent)
4057 char *data = ba->data();
4058 const char *inputPtr = data;
4061 int len = ba->count();
4067 if (c == percent && i + 2 < len) {
4071 if (a >= '0' && a <= '9') a -= '0';
4072 else if (a >= 'a' && a <= 'f') a = a - 'a' + 10;
4073 else if (a >= 'A' && a <= 'F') a = a - 'A' + 10;
4075 if (b >= '0' && b <= '9') b -= '0';
4076 else if (b >= 'a' && b <= 'f') b = b - 'a' + 10;
4077 else if (b >= 'A' && b <= 'F') b = b - 'A' + 10;
4079 *data++ = (char)((a << 4) | b);
4089 ba->truncate(outlen);
4092 void q_fromPercentEncoding(QByteArray *ba)
4094 q_fromPercentEncoding(ba, '%');
4100 Returns a decoded copy of the URI/URL-style percent-encoded \a input.
4101 The \a percent parameter allows you to replace the '%' character for
4102 another (for instance, '_' or '=').
4106 QByteArray text = QByteArray::fromPercentEncoding("Qt%20is%20great%33");
4107 text.data(); // returns "Qt is great!"
4110 \sa toPercentEncoding(), QUrl::fromPercentEncoding()
4112 QByteArray QByteArray::fromPercentEncoding(const QByteArray &input, char percent)
4115 return QByteArray(); // preserve null
4116 if (input.isEmpty())
4117 return QByteArray(input.data(), 0);
4119 QByteArray tmp = input;
4120 q_fromPercentEncoding(&tmp, percent);
4124 static inline bool q_strchr(const char str[], char chr)
4126 if (!str) return false;
4128 const char *ptr = str;
4130 while ((c = *ptr++))
4136 static inline char toHexHelper(char c)
4138 static const char hexnumbers[] = "0123456789ABCDEF";
4139 return hexnumbers[c & 0xf];
4142 static void q_toPercentEncoding(QByteArray *ba, const char *dontEncode, const char *alsoEncode, char percent)
4147 QByteArray input = *ba;
4148 int len = input.count();
4149 const char *inputData = input.constData();
4153 for (int i = 0; i < len; ++i) {
4154 unsigned char c = *inputData++;
4155 if (((c >= 0x61 && c <= 0x7A) // ALPHA
4156 || (c >= 0x41 && c <= 0x5A) // ALPHA
4157 || (c >= 0x30 && c <= 0x39) // DIGIT
4162 || q_strchr(dontEncode, c))
4163 && !q_strchr(alsoEncode, c)) {
4170 ba->resize(len*3); // worst case
4171 output = ba->data();
4173 output[length++] = percent;
4174 output[length++] = toHexHelper((c & 0xf0) >> 4);
4175 output[length++] = toHexHelper(c & 0xf);
4179 ba->truncate(length);
4182 void q_toPercentEncoding(QByteArray *ba, const char *exclude, const char *include)
4184 q_toPercentEncoding(ba, exclude, include, '%');
4187 void q_normalizePercentEncoding(QByteArray *ba, const char *exclude)
4189 q_fromPercentEncoding(ba, '%');
4190 q_toPercentEncoding(ba, exclude, 0, '%');
4196 Returns a URI/URL-style percent-encoded copy of this byte array. The
4197 \a percent parameter allows you to override the default '%'
4198 character for another.
4200 By default, this function will encode all characters that are not
4201 one of the following:
4203 ALPHA ("a" to "z" and "A" to "Z") / DIGIT (0 to 9) / "-" / "." / "_" / "~"
4205 To prevent characters from being encoded pass them to \a
4206 exclude. To force characters to be encoded pass them to \a
4207 include. The \a percent character is always encoded.
4212 QByteArray text = "{a fishy string?}";
4213 QByteArray ba = text.toPercentEncoding("{}", "s");
4214 qDebug(ba.constData());
4215 // prints "{a fi%73hy %73tring%3F}"
4218 The hex encoding uses the numbers 0-9 and the uppercase letters A-F.
4220 \sa fromPercentEncoding(), QUrl::toPercentEncoding()
4222 QByteArray QByteArray::toPercentEncoding(const QByteArray &exclude, const QByteArray &include,
4226 return QByteArray(); // preserve null
4228 return QByteArray(data(), 0);
4230 QByteArray include2 = include;
4231 if (percent != '%') // the default
4232 if ((percent >= 0x61 && percent <= 0x7A) // ALPHA
4233 || (percent >= 0x41 && percent <= 0x5A) // ALPHA
4234 || (percent >= 0x30 && percent <= 0x39) // DIGIT
4235 || percent == 0x2D // -
4236 || percent == 0x2E // .
4237 || percent == 0x5F // _
4238 || percent == 0x7E) // ~
4239 include2 += percent;
4241 QByteArray result = *this;
4242 q_toPercentEncoding(&result, exclude.nulTerminated().constData(), include2.nulTerminated().constData(), percent);
4247 /*! \typedef QByteArray::ConstIterator
4251 /*! \typedef QByteArray::Iterator
4255 /*! \typedef QByteArray::const_iterator
4259 /*! \typedef QByteArray::iterator
4263 /*! \typedef QByteArray::const_reference
4267 /*! \typedef QByteArray::reference
4271 /*! \typedef QByteArray::value_type
4276 \fn DataPtr &QByteArray::data_ptr()
4281 \typedef QByteArray::DataPtr