1/****************************************************************************
2**
3** Copyright (C) 2019 The Qt Company Ltd.
4** Copyright (C) 2016 Intel Corporation.
5** Copyright (C) 2019 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Giuseppe D'Angelo <giuseppe.dangelo@kdab.com>
6** Contact: https://www.qt.io/licensing/
7**
8** This file is part of the QtCore module of the Qt Toolkit.
9**
10** $QT_BEGIN_LICENSE:LGPL$
11** Commercial License Usage
12** Licensees holding valid commercial Qt licenses may use this file in
13** accordance with the commercial license agreement provided with the
14** Software or, alternatively, in accordance with the terms contained in
15** a written agreement between you and The Qt Company. For licensing terms
16** and conditions see https://www.qt.io/terms-conditions. For further
17** information use the contact form at https://www.qt.io/contact-us.
18**
19** GNU Lesser General Public License Usage
20** Alternatively, this file may be used under the terms of the GNU Lesser
21** General Public License version 3 as published by the Free Software
22** Foundation and appearing in the file LICENSE.LGPL3 included in the
23** packaging of this file. Please review the following information to
24** ensure the GNU Lesser General Public License version 3 requirements
25** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
26**
27** GNU General Public License Usage
28** Alternatively, this file may be used under the terms of the GNU
29** General Public License version 2.0 or (at your option) the GNU General
30** Public license version 3 or any later version approved by the KDE Free
31** Qt Foundation. The licenses are as published by the Free Software
32** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
33** included in the packaging of this file. Please review the following
34** information to ensure the GNU General Public License requirements will
35** be met: https://www.gnu.org/licenses/gpl-2.0.html and
36** https://www.gnu.org/licenses/gpl-3.0.html.
37**
38** $QT_END_LICENSE$
39**
40****************************************************************************/
41
42#include "qbytearray.h"
43#include "qbytearraymatcher.h"
44#include "private/qtools_p.h"
45#include "qhashfunctions.h"
46#include "qstring.h"
47#include "qlist.h"
48#include "qlocale.h"
49#include "qlocale_p.h"
50#include "qlocale_tools_p.h"
51#include "private/qnumeric_p.h"
52#include "private/qsimd_p.h"
53#include "qstringalgorithms_p.h"
54#include "qscopedpointer.h"
55#include "qbytearray_p.h"
56#include <qdatastream.h>
57#include <qmath.h>
58
59#ifndef QT_NO_COMPRESS
60#include <zconf.h>
61#include <zlib.h>
62#endif
63#include <ctype.h>
64#include <limits.h>
65#include <string.h>
66#include <stdlib.h>
67
68#define IS_RAW_DATA(d) ((d)->offset != sizeof(QByteArrayData))
69
70QT_BEGIN_NAMESPACE
71
72// Latin 1 case system, used by QByteArray::to{Upper,Lower}() and qstr(n)icmp():
73/*
74#!/usr/bin/perl -l
75use feature "unicode_strings";
76for (0..255) {
77 $up = uc(chr($_));
78 $up = chr($_) if ord($up) > 0x100 || length $up > 1;
79 printf "0x%02x,", ord($up);
80 print "" if ($_ & 0xf) == 0xf;
81}
82*/
83static const uchar latin1_uppercased[256] = {
84 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,
85 0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f,
86 0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x2e,0x2f,
87 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x3c,0x3d,0x3e,0x3f,
88 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,
89 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x5b,0x5c,0x5d,0x5e,0x5f,
90 0x60,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4a,0x4b,0x4c,0x4d,0x4e,0x4f,
91 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x7b,0x7c,0x7d,0x7e,0x7f,
92 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8a,0x8b,0x8c,0x8d,0x8e,0x8f,
93 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0x9b,0x9c,0x9d,0x9e,0x9f,
94 0xa0,0xa1,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xab,0xac,0xad,0xae,0xaf,
95 0xb0,0xb1,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xbb,0xbc,0xbd,0xbe,0xbf,
96 0xc0,0xc1,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xcb,0xcc,0xcd,0xce,0xcf,
97 0xd0,0xd1,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xdb,0xdc,0xdd,0xde,0xdf,
98 0xc0,0xc1,0xc2,0xc3,0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xcb,0xcc,0xcd,0xce,0xcf,
99 0xd0,0xd1,0xd2,0xd3,0xd4,0xd5,0xd6,0xf7,0xd8,0xd9,0xda,0xdb,0xdc,0xdd,0xde,0xff
100};
101
102/*
103#!/usr/bin/perl -l
104use feature "unicode_strings";
105for (0..255) {
106 $up = lc(chr($_));
107 $up = chr($_) if ord($up) > 0x100 || length $up > 1;
108 printf "0x%02x,", ord($up);
109 print "" if ($_ & 0xf) == 0xf;
110}
111*/
112static const uchar latin1_lowercased[256] = {
113 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0a,0x0b,0x0c,0x0d,0x0e,0x0f,
114 0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1a,0x1b,0x1c,0x1d,0x1e,0x1f,
115 0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2a,0x2b,0x2c,0x2d,0x2e,0x2f,
116 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x3b,0x3c,0x3d,0x3e,0x3f,
117 0x40,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,
118 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x5b,0x5c,0x5d,0x5e,0x5f,
119 0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x6b,0x6c,0x6d,0x6e,0x6f,
120 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x7b,0x7c,0x7d,0x7e,0x7f,
121 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8a,0x8b,0x8c,0x8d,0x8e,0x8f,
122 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0x9b,0x9c,0x9d,0x9e,0x9f,
123 0xa0,0xa1,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xab,0xac,0xad,0xae,0xaf,
124 0xb0,0xb1,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xbb,0xbc,0xbd,0xbe,0xbf,
125 0xe0,0xe1,0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xeb,0xec,0xed,0xee,0xef,
126 0xf0,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xd7,0xf8,0xf9,0xfa,0xfb,0xfc,0xfd,0xfe,0xdf,
127 0xe0,0xe1,0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xeb,0xec,0xed,0xee,0xef,
128 0xf0,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa,0xfb,0xfc,0xfd,0xfe,0xff
129};
130
131int qFindByteArray(
132 const char *haystack0, int haystackLen, int from,
133 const char *needle0, int needleLen);
134
135/*****************************************************************************
136 Safe and portable C string functions; extensions to standard string.h
137 *****************************************************************************/
138
139/*! \relates QByteArray
140
141 Returns a duplicate string.
142
143 Allocates space for a copy of \a src, copies it, and returns a
144 pointer to the copy. If \a src is \nullptr, it immediately returns
145 \nullptr.
146
147 Ownership is passed to the caller, so the returned string must be
148 deleted using \c delete[].
149*/
150
151char *qstrdup(const char *src)
152{
153 if (!src)
154 return nullptr;
155 char *dst = new char[strlen(s: src) + 1];
156 return qstrcpy(dst, src);
157}
158
159/*! \relates QByteArray
160
161 Copies all the characters up to and including the '\\0' from \a
162 src into \a dst and returns a pointer to \a dst. If \a src is
163 \nullptr, it immediately returns \nullptr.
164
165 This function assumes that \a dst is large enough to hold the
166 contents of \a src.
167
168 \note If \a dst and \a src overlap, the behavior is undefined.
169
170 \sa qstrncpy()
171*/
172
173char *qstrcpy(char *dst, const char *src)
174{
175 if (!src)
176 return nullptr;
177#ifdef Q_CC_MSVC
178 const int len = int(strlen(src));
179 // This is actually not secure!!! It will be fixed
180 // properly in a later release!
181 if (len >= 0 && strcpy_s(dst, len+1, src) == 0)
182 return dst;
183 return nullptr;
184#else
185 return strcpy(dest: dst, src: src);
186#endif
187}
188
189/*! \relates QByteArray
190
191 A safe \c strncpy() function.
192
193 Copies at most \a len bytes from \a src (stopping at \a len or the
194 terminating '\\0' whichever comes first) into \a dst and returns a
195 pointer to \a dst. Guarantees that \a dst is '\\0'-terminated. If
196 \a src or \a dst is \nullptr, returns \nullptr immediately.
197
198 This function assumes that \a dst is at least \a len characters
199 long.
200
201 \note If \a dst and \a src overlap, the behavior is undefined.
202
203 \note When compiling with Visual C++ compiler version 14.00
204 (Visual C++ 2005) or later, internally the function strncpy_s
205 will be used.
206
207 \sa qstrcpy()
208*/
209
210char *qstrncpy(char *dst, const char *src, uint len)
211{
212 if (!src || !dst)
213 return nullptr;
214 if (len > 0) {
215#ifdef Q_CC_MSVC
216 strncpy_s(dst, len, src, len - 1);
217#else
218 strncpy(dest: dst, src: src, n: len);
219#endif
220 dst[len-1] = '\0';
221 }
222 return dst;
223}
224
225/*! \fn uint qstrlen(const char *str)
226 \relates QByteArray
227
228 A safe \c strlen() function.
229
230 Returns the number of characters that precede the terminating '\\0',
231 or 0 if \a str is \nullptr.
232
233 \sa qstrnlen()
234*/
235
236/*! \fn uint qstrnlen(const char *str, uint maxlen)
237 \relates QByteArray
238 \since 4.2
239
240 A safe \c strnlen() function.
241
242 Returns the number of characters that precede the terminating '\\0', but
243 at most \a maxlen. If \a str is \nullptr, returns 0.
244
245 \sa qstrlen()
246*/
247
248/*!
249 \relates QByteArray
250
251 A safe \c strcmp() function.
252
253 Compares \a str1 and \a str2. Returns a negative value if \a str1
254 is less than \a str2, 0 if \a str1 is equal to \a str2 or a
255 positive value if \a str1 is greater than \a str2.
256
257 Special case 1: Returns 0 if \a str1 and \a str2 are both \nullptr.
258
259 Special case 2: Returns an arbitrary non-zero value if \a str1 is
260 \nullptr or \a str2 is \nullptr (but not both).
261
262 \sa qstrncmp(), qstricmp(), qstrnicmp(), {8-bit Character Comparisons},
263 QByteArray::compare()
264*/
265int qstrcmp(const char *str1, const char *str2)
266{
267 return (str1 && str2) ? strcmp(s1: str1, s2: str2)
268 : (str1 ? 1 : (str2 ? -1 : 0));
269}
270
271/*! \fn int qstrncmp(const char *str1, const char *str2, uint len);
272
273 \relates QByteArray
274
275 A safe \c strncmp() function.
276
277 Compares at most \a len bytes of \a str1 and \a str2.
278
279 Returns a negative value if \a str1 is less than \a str2, 0 if \a
280 str1 is equal to \a str2 or a positive value if \a str1 is greater
281 than \a str2.
282
283 Special case 1: Returns 0 if \a str1 and \a str2 are both \nullptr.
284
285 Special case 2: Returns a random non-zero value if \a str1 is \nullptr
286 or \a str2 is \nullptr (but not both).
287
288 \sa qstrcmp(), qstricmp(), qstrnicmp(), {8-bit Character Comparisons},
289 QByteArray::compare()
290*/
291
292/*! \relates QByteArray
293
294 A safe \c stricmp() function.
295
296 Compares \a str1 and \a str2 ignoring the case of the
297 characters. The encoding of the strings is assumed to be Latin-1.
298
299 Returns a negative value if \a str1 is less than \a str2, 0 if \a
300 str1 is equal to \a str2 or a positive value if \a str1 is greater
301 than \a str2.
302
303 Special case 1: Returns 0 if \a str1 and \a str2 are both \nullptr.
304
305 Special case 2: Returns a random non-zero value if \a str1 is \nullptr
306 or \a str2 is \nullptr (but not both).
307
308 \sa qstrcmp(), qstrncmp(), qstrnicmp(), {8-bit Character Comparisons},
309 QByteArray::compare()
310*/
311
312int qstricmp(const char *str1, const char *str2)
313{
314 const uchar *s1 = reinterpret_cast<const uchar *>(str1);
315 const uchar *s2 = reinterpret_cast<const uchar *>(str2);
316 if (!s1)
317 return s2 ? -1 : 0;
318 if (!s2)
319 return 1;
320
321 enum { Incomplete = 256 };
322 qptrdiff offset = 0;
323 auto innerCompare = [=, &offset](qptrdiff max, bool unlimited) {
324 max += offset;
325 do {
326 uchar c = latin1_lowercased[s1[offset]];
327 int res = c - latin1_lowercased[s2[offset]];
328 if (Q_UNLIKELY(res))
329 return res;
330 if (Q_UNLIKELY(!c))
331 return 0;
332 ++offset;
333 } while (unlimited || offset < max);
334 return int(Incomplete);
335 };
336
337#if defined(__SSE4_1__) && !(defined(__SANITIZE_ADDRESS__) || __has_feature(address_sanitizer))
338 enum { PageSize = 4096, PageMask = PageSize - 1 };
339 const __m128i zero = _mm_setzero_si128();
340 forever {
341 // Calculate how many bytes we can load until we cross a page boundary
342 // for either source. This isn't an exact calculation, just something
343 // very quick.
344 quintptr u1 = quintptr(s1 + offset);
345 quintptr u2 = quintptr(s2 + offset);
346 uint n = PageSize - ((u1 | u2) & PageMask);
347
348 qptrdiff maxoffset = offset + n;
349 for ( ; offset + 16 <= maxoffset; offset += sizeof(__m128i)) {
350 // load 16 bytes from either source
351 __m128i a = _mm_loadu_si128(reinterpret_cast<const __m128i *>(s1 + offset));
352 __m128i b = _mm_loadu_si128(reinterpret_cast<const __m128i *>(s2 + offset));
353
354 // compare the two against each oher
355 __m128i cmp = _mm_cmpeq_epi8(a, b);
356
357 // find NUL terminators too
358 cmp = _mm_min_epu8(cmp, a);
359 cmp = _mm_cmpeq_epi8(cmp, zero);
360
361 // was there any difference or a NUL?
362 uint mask = _mm_movemask_epi8(cmp);
363 if (mask) {
364 // yes, find out where
365 uint start = qCountTrailingZeroBits(mask);
366 uint end = sizeof(mask) * 8 - qCountLeadingZeroBits(mask);
367 Q_ASSUME(end >= start);
368 offset += start;
369 n = end - start;
370 break;
371 }
372 }
373
374 // using SIMD could cause a page fault, so iterate byte by byte
375 int res = innerCompare(n, false);
376 if (res != Incomplete)
377 return res;
378 }
379#endif
380
381 return innerCompare(-1, true);
382}
383
384/*! \relates QByteArray
385
386 A safe \c strnicmp() function.
387
388 Compares at most \a len bytes of \a str1 and \a str2 ignoring the
389 case of the characters. The encoding of the strings is assumed to
390 be Latin-1.
391
392 Returns a negative value if \a str1 is less than \a str2, 0 if \a str1
393 is equal to \a str2 or a positive value if \a str1 is greater than \a
394 str2.
395
396 Special case 1: Returns 0 if \a str1 and \a str2 are both \nullptr.
397
398 Special case 2: Returns a random non-zero value if \a str1 is \nullptr
399 or \a str2 is \nullptr (but not both).
400
401 \sa qstrcmp(), qstrncmp(), qstricmp(), {8-bit Character Comparisons},
402 QByteArray::compare()
403*/
404
405int qstrnicmp(const char *str1, const char *str2, uint len)
406{
407 const uchar *s1 = reinterpret_cast<const uchar *>(str1);
408 const uchar *s2 = reinterpret_cast<const uchar *>(str2);
409 int res;
410 uchar c;
411 if (!s1 || !s2)
412 return s1 ? 1 : (s2 ? -1 : 0);
413 for (; len--; s1++, s2++) {
414 if ((res = (c = latin1_lowercased[*s1]) - latin1_lowercased[*s2]))
415 return res;
416 if (!c) // strings are equal
417 break;
418 }
419 return 0;
420}
421
422/*!
423 \internal
424 \since 5.12
425
426 A helper for QByteArray::compare. Compares \a len1 bytes from \a str1 to \a
427 len2 bytes from \a str2. If \a len2 is -1, then \a str2 is expected to be
428 '\\0'-terminated.
429 */
430int qstrnicmp(const char *str1, qsizetype len1, const char *str2, qsizetype len2)
431{
432 Q_ASSERT(str1);
433 Q_ASSERT(len1 >= 0);
434 Q_ASSERT(len2 >= -1);
435 const uchar *s1 = reinterpret_cast<const uchar *>(str1);
436 const uchar *s2 = reinterpret_cast<const uchar *>(str2);
437 if (!s2)
438 return len1 == 0 ? 0 : 1;
439
440 int res;
441 uchar c;
442 if (len2 == -1) {
443 // null-terminated str2
444 qsizetype i;
445 for (i = 0; i < len1; ++i) {
446 c = latin1_lowercased[s2[i]];
447 if (!c)
448 return 1;
449
450 res = latin1_lowercased[s1[i]] - c;
451 if (res)
452 return res;
453 }
454 c = latin1_lowercased[s2[i]];
455 return c ? -1 : 0;
456 } else {
457 // not null-terminated
458 for (qsizetype i = 0; i < qMin(a: len1, b: len2); ++i) {
459 c = latin1_lowercased[s2[i]];
460 res = latin1_lowercased[s1[i]] - c;
461 if (res)
462 return res;
463 }
464 if (len1 == len2)
465 return 0;
466 return len1 < len2 ? -1 : 1;
467 }
468}
469
470/*!
471 \internal
472 ### Qt6: replace the QByteArray parameter with [pointer,len] pair
473 */
474int qstrcmp(const QByteArray &str1, const char *str2)
475{
476 if (!str2)
477 return str1.isEmpty() ? 0 : +1;
478
479 const char *str1data = str1.constData();
480 const char *str1end = str1data + str1.length();
481 for ( ; str1data < str1end && *str2; ++str1data, ++str2) {
482 int diff = int(uchar(*str1data)) - uchar(*str2);
483 if (diff)
484 // found a difference
485 return diff;
486 }
487
488 // Why did we stop?
489 if (*str2 != '\0')
490 // not the null, so we stopped because str1 is shorter
491 return -1;
492 if (str1data < str1end)
493 // we haven't reached the end, so str1 must be longer
494 return +1;
495 return 0;
496}
497
498/*!
499 \internal
500 ### Qt6: replace the QByteArray parameter with [pointer,len] pair
501 */
502int qstrcmp(const QByteArray &str1, const QByteArray &str2)
503{
504 int l1 = str1.length();
505 int l2 = str2.length();
506 int ret = memcmp(s1: str1.constData(), s2: str2.constData(), n: qMin(a: l1, b: l2));
507 if (ret != 0)
508 return ret;
509
510 // they matched qMin(l1, l2) bytes
511 // so the longer one is lexically after the shorter one
512 return l1 - l2;
513}
514
515// the CRC table below is created by the following piece of code
516#if 0
517static void createCRC16Table() // build CRC16 lookup table
518{
519 unsigned int i;
520 unsigned int j;
521 unsigned short crc_tbl[16];
522 unsigned int v0, v1, v2, v3;
523 for (i = 0; i < 16; i++) {
524 v0 = i & 1;
525 v1 = (i >> 1) & 1;
526 v2 = (i >> 2) & 1;
527 v3 = (i >> 3) & 1;
528 j = 0;
529#undef SET_BIT
530#define SET_BIT(x, b, v) (x) |= (v) << (b)
531 SET_BIT(j, 0, v0);
532 SET_BIT(j, 7, v0);
533 SET_BIT(j, 12, v0);
534 SET_BIT(j, 1, v1);
535 SET_BIT(j, 8, v1);
536 SET_BIT(j, 13, v1);
537 SET_BIT(j, 2, v2);
538 SET_BIT(j, 9, v2);
539 SET_BIT(j, 14, v2);
540 SET_BIT(j, 3, v3);
541 SET_BIT(j, 10, v3);
542 SET_BIT(j, 15, v3);
543 crc_tbl[i] = j;
544 }
545 printf("static const quint16 crc_tbl[16] = {\n");
546 for (int i = 0; i < 16; i +=4)
547 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]);
548 printf("};\n");
549}
550#endif
551
552static const quint16 crc_tbl[16] = {
553 0x0000, 0x1081, 0x2102, 0x3183,
554 0x4204, 0x5285, 0x6306, 0x7387,
555 0x8408, 0x9489, 0xa50a, 0xb58b,
556 0xc60c, 0xd68d, 0xe70e, 0xf78f
557};
558
559/*!
560 \relates QByteArray
561
562 Returns the CRC-16 checksum of the first \a len bytes of \a data.
563
564 The checksum is independent of the byte order (endianness) and will be
565 calculated accorded to the algorithm published in ISO 3309 (Qt::ChecksumIso3309).
566
567 \note This function is a 16-bit cache conserving (16 entry table)
568 implementation of the CRC-16-CCITT algorithm.
569*/
570quint16 qChecksum(const char *data, uint len)
571{
572 return qChecksum(s: data, len, standard: Qt::ChecksumIso3309);
573}
574
575/*!
576 \relates QByteArray
577 \since 5.9
578
579 Returns the CRC-16 checksum of the first \a len bytes of \a data.
580
581 The checksum is independent of the byte order (endianness) and will
582 be calculated accorded to the algorithm published in \a standard.
583
584 \note This function is a 16-bit cache conserving (16 entry table)
585 implementation of the CRC-16-CCITT algorithm.
586*/
587quint16 qChecksum(const char *data, uint len, Qt::ChecksumType standard)
588{
589 quint16 crc = 0x0000;
590 switch (standard) {
591 case Qt::ChecksumIso3309:
592 crc = 0xffff;
593 break;
594 case Qt::ChecksumItuV41:
595 crc = 0x6363;
596 break;
597 }
598 uchar c;
599 const uchar *p = reinterpret_cast<const uchar *>(data);
600 while (len--) {
601 c = *p++;
602 crc = ((crc >> 4) & 0x0fff) ^ crc_tbl[((crc ^ c) & 15)];
603 c >>= 4;
604 crc = ((crc >> 4) & 0x0fff) ^ crc_tbl[((crc ^ c) & 15)];
605 }
606 switch (standard) {
607 case Qt::ChecksumIso3309:
608 crc = ~crc;
609 break;
610 case Qt::ChecksumItuV41:
611 break;
612 }
613 return crc & 0xffff;
614}
615
616/*!
617 \fn QByteArray qCompress(const QByteArray& data, int compressionLevel)
618
619 \relates QByteArray
620
621 Compresses the \a data byte array and returns the compressed data
622 in a new byte array.
623
624 The \a compressionLevel parameter specifies how much compression
625 should be used. Valid values are between 0 and 9, with 9
626 corresponding to the greatest compression (i.e. smaller compressed
627 data) at the cost of using a slower algorithm. Smaller values (8,
628 7, ..., 1) provide successively less compression at slightly
629 faster speeds. The value 0 corresponds to no compression at all.
630 The default value is -1, which specifies zlib's default
631 compression.
632
633 \sa qUncompress()
634*/
635
636/*! \relates QByteArray
637
638 \overload
639
640 Compresses the first \a nbytes of \a data at compression level
641 \a compressionLevel and returns the compressed data in a new byte array.
642*/
643
644#ifndef QT_NO_COMPRESS
645QByteArray qCompress(const uchar* data, int nbytes, int compressionLevel)
646{
647 if (nbytes == 0) {
648 return QByteArray(4, '\0');
649 }
650 if (!data) {
651 qWarning(msg: "qCompress: Data is null");
652 return QByteArray();
653 }
654 if (compressionLevel < -1 || compressionLevel > 9)
655 compressionLevel = -1;
656
657 ulong len = nbytes + nbytes / 100 + 13;
658 QByteArray bazip;
659 int res;
660 do {
661 bazip.resize(size: len + 4);
662 res = ::compress2(dest: (uchar*)bazip.data()+4, destLen: &len, source: data, sourceLen: nbytes, level: compressionLevel);
663
664 switch (res) {
665 case Z_OK:
666 bazip.resize(size: len + 4);
667 bazip[0] = (nbytes & 0xff000000) >> 24;
668 bazip[1] = (nbytes & 0x00ff0000) >> 16;
669 bazip[2] = (nbytes & 0x0000ff00) >> 8;
670 bazip[3] = (nbytes & 0x000000ff);
671 break;
672 case Z_MEM_ERROR:
673 qWarning(msg: "qCompress: Z_MEM_ERROR: Not enough memory");
674 bazip.resize(size: 0);
675 break;
676 case Z_BUF_ERROR:
677 len *= 2;
678 break;
679 }
680 } while (res == Z_BUF_ERROR);
681
682 return bazip;
683}
684#endif
685
686/*!
687 \fn QByteArray qUncompress(const QByteArray &data)
688
689 \relates QByteArray
690
691 Uncompresses the \a data byte array and returns a new byte array
692 with the uncompressed data.
693
694 Returns an empty QByteArray if the input data was corrupt.
695
696 This function will uncompress data compressed with qCompress()
697 from this and any earlier Qt version, back to Qt 3.1 when this
698 feature was added.
699
700 \b{Note:} If you want to use this function to uncompress external
701 data that was compressed using zlib, you first need to prepend a four
702 byte header to the byte array containing the data. The header must
703 contain the expected length (in bytes) of the uncompressed data,
704 expressed as an unsigned, big-endian, 32-bit integer.
705
706 \sa qCompress()
707*/
708
709#ifndef QT_NO_COMPRESS
710namespace {
711struct QByteArrayDataDeleter
712{
713 static inline void cleanup(QTypedArrayData<char> *d)
714 { if (d) QTypedArrayData<char>::deallocate(data: d); }
715};
716}
717
718static QByteArray invalidCompressedData()
719{
720 qWarning(msg: "qUncompress: Input data is corrupted");
721 return QByteArray();
722}
723
724/*! \relates QByteArray
725
726 \overload
727
728 Uncompresses the first \a nbytes of \a data and returns a new byte
729 array with the uncompressed data.
730*/
731QByteArray qUncompress(const uchar* data, int nbytes)
732{
733 if (!data) {
734 qWarning(msg: "qUncompress: Data is null");
735 return QByteArray();
736 }
737 if (nbytes <= 4) {
738 if (nbytes < 4 || (data[0]!=0 || data[1]!=0 || data[2]!=0 || data[3]!=0))
739 qWarning(msg: "qUncompress: Input data is corrupted");
740 return QByteArray();
741 }
742 ulong expectedSize = uint((data[0] << 24) | (data[1] << 16) |
743 (data[2] << 8) | (data[3] ));
744 ulong len = qMax(a: expectedSize, b: 1ul);
745 const ulong maxPossibleSize = MaxAllocSize - sizeof(QByteArray::Data);
746 if (Q_UNLIKELY(len >= maxPossibleSize)) {
747 // QByteArray does not support that huge size anyway.
748 return invalidCompressedData();
749 }
750
751 QScopedPointer<QByteArray::Data, QByteArrayDataDeleter> d(QByteArray::Data::allocate(capacity: expectedSize + 1));
752 if (Q_UNLIKELY(d.data() == nullptr))
753 return invalidCompressedData();
754
755 d->size = expectedSize;
756 forever {
757 ulong alloc = len;
758
759 int res = ::uncompress(dest: (uchar*)d->data(), destLen: &len,
760 source: data+4, sourceLen: nbytes-4);
761
762 switch (res) {
763 case Z_OK:
764 Q_ASSERT(len <= alloc);
765 Q_UNUSED(alloc);
766 d->size = len;
767 d->data()[len] = 0;
768 {
769 QByteArrayDataPtr dataPtr = { .ptr: d.take() };
770 return QByteArray(dataPtr);
771 }
772
773 case Z_MEM_ERROR:
774 qWarning(msg: "qUncompress: Z_MEM_ERROR: Not enough memory");
775 return QByteArray();
776
777 case Z_BUF_ERROR:
778 len *= 2;
779 if (Q_UNLIKELY(len >= maxPossibleSize)) {
780 // QByteArray does not support that huge size anyway.
781 return invalidCompressedData();
782 } else {
783 // grow the block
784 QByteArray::Data *p = QByteArray::Data::reallocateUnaligned(data: d.data(), capacity: len + 1);
785 if (Q_UNLIKELY(p == nullptr))
786 return invalidCompressedData();
787 d.take(); // don't free
788 d.reset(other: p);
789 }
790 continue;
791
792 case Z_DATA_ERROR:
793 qWarning(msg: "qUncompress: Z_DATA_ERROR: Input data is corrupted");
794 return QByteArray();
795 }
796 }
797}
798#endif
799
800/*!
801 \class QByteArray
802 \inmodule QtCore
803 \brief The QByteArray class provides an array of bytes.
804
805 \ingroup tools
806 \ingroup shared
807 \ingroup string-processing
808
809 \reentrant
810
811 QByteArray can be used to store both raw bytes (including '\\0's)
812 and traditional 8-bit '\\0'-terminated strings. Using QByteArray
813 is much more convenient than using \c{const char *}. Behind the
814 scenes, it always ensures that the data is followed by a '\\0'
815 terminator, and uses \l{implicit sharing} (copy-on-write) to
816 reduce memory usage and avoid needless copying of data.
817
818 In addition to QByteArray, Qt also provides the QString class to
819 store string data. For most purposes, QString is the class you
820 want to use. It stores 16-bit Unicode characters, making it easy
821 to store non-ASCII/non-Latin-1 characters in your application.
822 Furthermore, QString is used throughout in the Qt API. The two
823 main cases where QByteArray is appropriate are when you need to
824 store raw binary data, and when memory conservation is critical
825 (e.g., with Qt for Embedded Linux).
826
827 One way to initialize a QByteArray is simply to pass a \c{const
828 char *} to its constructor. For example, the following code
829 creates a byte array of size 5 containing the data "Hello":
830
831 \snippet code/src_corelib_tools_qbytearray.cpp 0
832
833 Although the size() is 5, the byte array also maintains an extra
834 '\\0' character at the end so that if a function is used that
835 asks for a pointer to the underlying data (e.g. a call to
836 data()), the data pointed to is guaranteed to be
837 '\\0'-terminated.
838
839 QByteArray makes a deep copy of the \c{const char *} data, so you
840 can modify it later without experiencing side effects. (If for
841 performance reasons you don't want to take a deep copy of the
842 character data, use QByteArray::fromRawData() instead.)
843
844 Another approach is to set the size of the array using resize()
845 and to initialize the data byte per byte. QByteArray uses 0-based
846 indexes, just like C++ arrays. To access the byte at a particular
847 index position, you can use operator[](). On non-const byte
848 arrays, operator[]() returns a reference to a byte that can be
849 used on the left side of an assignment. For example:
850
851 \snippet code/src_corelib_tools_qbytearray.cpp 1
852
853 For read-only access, an alternative syntax is to use at():
854
855 \snippet code/src_corelib_tools_qbytearray.cpp 2
856
857 at() can be faster than operator[](), because it never causes a
858 \l{deep copy} to occur.
859
860 To extract many bytes at a time, use left(), right(), or mid().
861
862 A QByteArray can embed '\\0' bytes. The size() function always
863 returns the size of the whole array, including embedded '\\0'
864 bytes, but excluding the terminating '\\0' added by QByteArray.
865 For example:
866
867 \snippet code/src_corelib_tools_qbytearray.cpp 48
868
869 If you want to obtain the length of the data up to and
870 excluding the first '\\0' character, call qstrlen() on the byte
871 array.
872
873 After a call to resize(), newly allocated bytes have undefined
874 values. To set all the bytes to a particular value, call fill().
875
876 To obtain a pointer to the actual character data, call data() or
877 constData(). These functions return a pointer to the beginning of the data.
878 The pointer is guaranteed to remain valid until a non-const function is
879 called on the QByteArray. It is also guaranteed that the data ends with a
880 '\\0' byte unless the QByteArray was created from a \l{fromRawData()}{raw
881 data}. This '\\0' byte is automatically provided by QByteArray and is not
882 counted in size().
883
884 QByteArray provides the following basic functions for modifying
885 the byte data: append(), prepend(), insert(), replace(), and
886 remove(). For example:
887
888 \snippet code/src_corelib_tools_qbytearray.cpp 3
889
890 The replace() and remove() functions' first two arguments are the
891 position from which to start erasing and the number of bytes that
892 should be erased.
893
894 When you append() data to a non-empty array, the array will be
895 reallocated and the new data copied to it. You can avoid this
896 behavior by calling reserve(), which preallocates a certain amount
897 of memory. You can also call capacity() to find out how much
898 memory QByteArray actually allocated. Data appended to an empty
899 array is not copied.
900
901 A frequent requirement is to remove whitespace characters from a
902 byte array ('\\n', '\\t', ' ', etc.). If you want to remove
903 whitespace from both ends of a QByteArray, use trimmed(). If you
904 want to remove whitespace from both ends and replace multiple
905 consecutive whitespaces with a single space character within the
906 byte array, use simplified().
907
908 If you want to find all occurrences of a particular character or
909 substring in a QByteArray, use indexOf() or lastIndexOf(). The
910 former searches forward starting from a given index position, the
911 latter searches backward. Both return the index position of the
912 character or substring if they find it; otherwise, they return -1.
913 For example, here's a typical loop that finds all occurrences of a
914 particular substring:
915
916 \snippet code/src_corelib_tools_qbytearray.cpp 4
917
918 If you simply want to check whether a QByteArray contains a
919 particular character or substring, use contains(). If you want to
920 find out how many times a particular character or substring
921 occurs in the byte array, use count(). If you want to replace all
922 occurrences of a particular value with another, use one of the
923 two-parameter replace() overloads.
924
925 \l{QByteArray}s can be compared using overloaded operators such as
926 operator<(), operator<=(), operator==(), operator>=(), and so on.
927 The comparison is based exclusively on the numeric values
928 of the characters and is very fast, but is not what a human would
929 expect. QString::localeAwareCompare() is a better choice for
930 sorting user-interface strings.
931
932 For historical reasons, QByteArray distinguishes between a null
933 byte array and an empty byte array. A \e null byte array is a
934 byte array that is initialized using QByteArray's default
935 constructor or by passing (const char *)0 to the constructor. An
936 \e empty byte array is any byte array with size 0. A null byte
937 array is always empty, but an empty byte array isn't necessarily
938 null:
939
940 \snippet code/src_corelib_tools_qbytearray.cpp 5
941
942 All functions except isNull() treat null byte arrays the same as
943 empty byte arrays. For example, data() returns a valid pointer
944 (\e not nullptr) to a '\\0' character for a byte array
945 and QByteArray() compares equal to QByteArray(""). We recommend
946 that you always use isEmpty() and avoid isNull().
947
948 \section1 Maximum size and out-of-memory conditions
949
950 The current version of QByteArray is limited to just under 2 GB (2^31
951 bytes) in size. The exact value is architecture-dependent, since it depends
952 on the overhead required for managing the data block, but is no more than
953 32 bytes. Raw data blocks are also limited by the use of \c int type in the
954 current version to 2 GB minus 1 byte.
955
956 In case memory allocation fails, QByteArray will throw a \c std::bad_alloc
957 exception. Out of memory conditions in the Qt containers are the only case
958 where Qt will throw exceptions.
959
960 Note that the operating system may impose further limits on applications
961 holding a lot of allocated memory, especially large, contiguous blocks.
962 Such considerations, the configuration of such behavior or any mitigation
963 are outside the scope of the QByteArray API.
964
965 \section1 Notes on Locale
966
967 \section2 Number-String Conversions
968
969 Functions that perform conversions between numeric data types and
970 strings are performed in the C locale, irrespective of the user's
971 locale settings. Use QString to perform locale-aware conversions
972 between numbers and strings.
973
974 \section2 8-bit Character Comparisons
975
976 In QByteArray, the notion of uppercase and lowercase and of which
977 character is greater than or less than another character is done
978 in the Latin-1 locale. This affects functions that support a case
979 insensitive option or that compare or lowercase or uppercase
980 their arguments. Case insensitive operations and comparisons will
981 be accurate if both strings contain only Latin-1 characters.
982 Functions that this affects include contains(), indexOf(),
983 lastIndexOf(), operator<(), operator<=(), operator>(),
984 operator>=(), isLower(), isUpper(), toLower() and toUpper().
985
986 This issue does not apply to \l{QString}s since they represent
987 characters using Unicode.
988
989 \sa QString, QBitArray
990*/
991
992/*!
993 \enum QByteArray::Base64Option
994 \since 5.2
995
996 This enum contains the options available for encoding and decoding Base64.
997 Base64 is defined by \l{RFC 4648}, with the following options:
998
999 \value Base64Encoding (default) The regular Base64 alphabet, called simply "base64"
1000 \value Base64UrlEncoding An alternate alphabet, called "base64url", which replaces two
1001 characters in the alphabet to be more friendly to URLs.
1002 \value KeepTrailingEquals (default) Keeps the trailing padding equal signs at the end
1003 of the encoded data, so the data is always a size multiple of
1004 four.
1005 \value OmitTrailingEquals Omits adding the padding equal signs at the end of the encoded
1006 data.
1007 \value IgnoreBase64DecodingErrors When decoding Base64-encoded data, ignores errors
1008 in the input; invalid characters are simply skipped.
1009 This enum value has been added in Qt 5.15.
1010 \value AbortOnBase64DecodingErrors When decoding Base64-encoded data, stops at the first
1011 decoding error.
1012 This enum value has been added in Qt 5.15.
1013
1014 QByteArray::fromBase64Encoding() and QByteArray::fromBase64()
1015 ignore the KeepTrailingEquals and OmitTrailingEquals options. If
1016 the IgnoreBase64DecodingErrors option is specified, they will not
1017 flag errors in case trailing equal signs are missing or if there
1018 are too many of them. If instead the AbortOnBase64DecodingErrors is
1019 specified, then the input must either have no padding or have the
1020 correct amount of equal signs.
1021*/
1022
1023/*! \fn QByteArray::iterator QByteArray::begin()
1024
1025 Returns an \l{STL-style iterators}{STL-style iterator} pointing to the first character in
1026 the byte-array.
1027
1028 \sa constBegin(), end()
1029*/
1030
1031/*! \fn QByteArray::const_iterator QByteArray::begin() const
1032
1033 \overload begin()
1034*/
1035
1036/*! \fn QByteArray::const_iterator QByteArray::cbegin() const
1037 \since 5.0
1038
1039 Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the first character
1040 in the byte-array.
1041
1042 \sa begin(), cend()
1043*/
1044
1045/*! \fn QByteArray::const_iterator QByteArray::constBegin() const
1046
1047 Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the first character
1048 in the byte-array.
1049
1050 \sa begin(), constEnd()
1051*/
1052
1053/*! \fn QByteArray::iterator QByteArray::end()
1054
1055 Returns an \l{STL-style iterators}{STL-style iterator} pointing to the imaginary character
1056 after the last character in the byte-array.
1057
1058 \sa begin(), constEnd()
1059*/
1060
1061/*! \fn QByteArray::const_iterator QByteArray::end() const
1062
1063 \overload end()
1064*/
1065
1066/*! \fn QByteArray::const_iterator QByteArray::cend() const
1067 \since 5.0
1068
1069 Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the imaginary
1070 character after the last character in the list.
1071
1072 \sa cbegin(), end()
1073*/
1074
1075/*! \fn QByteArray::const_iterator QByteArray::constEnd() const
1076
1077 Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the imaginary
1078 character after the last character in the list.
1079
1080 \sa constBegin(), end()
1081*/
1082
1083/*! \fn QByteArray::reverse_iterator QByteArray::rbegin()
1084 \since 5.6
1085
1086 Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing to the first
1087 character in the byte-array, in reverse order.
1088
1089 \sa begin(), crbegin(), rend()
1090*/
1091
1092/*! \fn QByteArray::const_reverse_iterator QByteArray::rbegin() const
1093 \since 5.6
1094 \overload
1095*/
1096
1097/*! \fn QByteArray::const_reverse_iterator QByteArray::crbegin() const
1098 \since 5.6
1099
1100 Returns a const \l{STL-style iterators}{STL-style} reverse iterator pointing to the first
1101 character in the byte-array, in reverse order.
1102
1103 \sa begin(), rbegin(), rend()
1104*/
1105
1106/*! \fn QByteArray::reverse_iterator QByteArray::rend()
1107 \since 5.6
1108
1109 Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing to one past
1110 the last character in the byte-array, in reverse order.
1111
1112 \sa end(), crend(), rbegin()
1113*/
1114
1115/*! \fn QByteArray::const_reverse_iterator QByteArray::rend() const
1116 \since 5.6
1117 \overload
1118*/
1119
1120/*! \fn QByteArray::const_reverse_iterator QByteArray::crend() const
1121 \since 5.6
1122
1123 Returns a const \l{STL-style iterators}{STL-style} reverse iterator pointing to one
1124 past the last character in the byte-array, in reverse order.
1125
1126 \sa end(), rend(), rbegin()
1127*/
1128
1129/*! \fn void QByteArray::push_back(const QByteArray &other)
1130
1131 This function is provided for STL compatibility. It is equivalent
1132 to append(\a other).
1133*/
1134
1135/*! \fn void QByteArray::push_back(const char *str)
1136
1137 \overload
1138
1139 Same as append(\a str).
1140*/
1141
1142/*! \fn void QByteArray::push_back(char ch)
1143
1144 \overload
1145
1146 Same as append(\a ch).
1147*/
1148
1149/*! \fn void QByteArray::push_front(const QByteArray &other)
1150
1151 This function is provided for STL compatibility. It is equivalent
1152 to prepend(\a other).
1153*/
1154
1155/*! \fn void QByteArray::push_front(const char *str)
1156
1157 \overload
1158
1159 Same as prepend(\a str).
1160*/
1161
1162/*! \fn void QByteArray::push_front(char ch)
1163
1164 \overload
1165
1166 Same as prepend(\a ch).
1167*/
1168
1169/*! \fn void QByteArray::shrink_to_fit()
1170 \since 5.10
1171
1172 This function is provided for STL compatibility. It is equivalent to
1173 squeeze().
1174*/
1175
1176/*! \fn QByteArray::QByteArray(const QByteArray &other)
1177
1178 Constructs a copy of \a other.
1179
1180 This operation takes \l{constant time}, because QByteArray is
1181 \l{implicitly shared}. This makes returning a QByteArray from a
1182 function very fast. If a shared instance is modified, it will be
1183 copied (copy-on-write), taking \l{linear time}.
1184
1185 \sa operator=()
1186*/
1187
1188/*!
1189 \fn QByteArray::QByteArray(QByteArray &&other)
1190
1191 Move-constructs a QByteArray instance, making it point at the same
1192 object that \a other was pointing to.
1193
1194 \since 5.2
1195*/
1196
1197/*! \fn QByteArray::QByteArray(QByteArrayDataPtr dd)
1198
1199 \internal
1200
1201 Constructs a byte array pointing to the same data as \a dd.
1202*/
1203
1204/*! \fn QByteArray::~QByteArray()
1205 Destroys the byte array.
1206*/
1207
1208/*!
1209 Assigns \a other to this byte array and returns a reference to
1210 this byte array.
1211*/
1212QByteArray &QByteArray::operator=(const QByteArray & other) noexcept
1213{
1214 other.d->ref.ref();
1215 if (!d->ref.deref())
1216 Data::deallocate(data: d);
1217 d = other.d;
1218 return *this;
1219}
1220
1221
1222/*!
1223 \overload
1224
1225 Assigns \a str to this byte array.
1226*/
1227
1228QByteArray &QByteArray::operator=(const char *str)
1229{
1230 Data *x;
1231 if (!str) {
1232 x = Data::sharedNull();
1233 } else if (!*str) {
1234 x = Data::allocate(capacity: 0);
1235 } else {
1236 const int len = int(strlen(s: str));
1237 const uint fullLen = len + 1;
1238 if (d->ref.isShared() || fullLen > d->alloc
1239 || (len < d->size && fullLen < uint(d->alloc >> 1)))
1240 reallocData(alloc: fullLen, options: d->detachFlags());
1241 x = d;
1242 memcpy(dest: x->data(), src: str, n: fullLen); // include null terminator
1243 x->size = len;
1244 }
1245 x->ref.ref();
1246 if (!d->ref.deref())
1247 Data::deallocate(data: d);
1248 d = x;
1249 return *this;
1250}
1251
1252/*!
1253 \fn QByteArray &QByteArray::operator=(QByteArray &&other)
1254
1255 Move-assigns \a other to this QByteArray instance.
1256
1257 \since 5.2
1258*/
1259
1260/*! \fn void QByteArray::swap(QByteArray &other)
1261 \since 4.8
1262
1263 Swaps byte array \a other with this byte array. This operation is very
1264 fast and never fails.
1265*/
1266
1267/*! \fn int QByteArray::size() const
1268
1269 Returns the number of bytes in this byte array.
1270
1271 The last byte in the byte array is at position size() - 1. In addition,
1272 QByteArray ensures that the byte at position size() is always '\\0', so
1273 that you can use the return value of data() and constData() as arguments to
1274 functions that expect '\\0'-terminated strings. If the QByteArray object
1275 was created from a \l{fromRawData()}{raw data} that didn't include the
1276 trailing null-termination character then QByteArray doesn't add it
1277 automaticall unless the \l{deep copy} is created.
1278
1279 Example:
1280 \snippet code/src_corelib_tools_qbytearray.cpp 6
1281
1282 \sa isEmpty(), resize()
1283*/
1284
1285/*! \fn bool QByteArray::isEmpty() const
1286
1287 Returns \c true if the byte array has size 0; otherwise returns \c false.
1288
1289 Example:
1290 \snippet code/src_corelib_tools_qbytearray.cpp 7
1291
1292 \sa size()
1293*/
1294
1295/*! \fn int QByteArray::capacity() const
1296
1297 Returns the maximum number of bytes that can be stored in the
1298 byte array without forcing a reallocation.
1299
1300 The sole purpose of this function is to provide a means of fine
1301 tuning QByteArray's memory usage. In general, you will rarely
1302 ever need to call this function. If you want to know how many
1303 bytes are in the byte array, call size().
1304
1305 \sa reserve(), squeeze()
1306*/
1307
1308/*! \fn void QByteArray::reserve(int size)
1309
1310 Attempts to allocate memory for at least \a size bytes. If you
1311 know in advance how large the byte array will be, you can call
1312 this function, and if you call resize() often you are likely to
1313 get better performance. If \a size is an underestimate, the worst
1314 that will happen is that the QByteArray will be a bit slower.
1315
1316 The sole purpose of this function is to provide a means of fine
1317 tuning QByteArray's memory usage. In general, you will rarely
1318 ever need to call this function. If you want to change the size
1319 of the byte array, call resize().
1320
1321 \sa squeeze(), capacity()
1322*/
1323
1324/*! \fn void QByteArray::squeeze()
1325
1326 Releases any memory not required to store the array's data.
1327
1328 The sole purpose of this function is to provide a means of fine
1329 tuning QByteArray's memory usage. In general, you will rarely
1330 ever need to call this function.
1331
1332 \sa reserve(), capacity()
1333*/
1334
1335/*! \fn QByteArray::operator const char *() const
1336 \fn QByteArray::operator const void *() const
1337
1338 \obsolete Use constData() instead.
1339
1340 Returns a pointer to the data stored in the byte array. The
1341 pointer can be used to access the bytes that compose the array.
1342 The data is '\\0'-terminated. The pointer remains valid as long
1343 as the array isn't reallocated or destroyed.
1344
1345 This operator is mostly useful to pass a byte array to a function
1346 that accepts a \c{const char *}.
1347
1348 You can disable this operator by defining \c
1349 QT_NO_CAST_FROM_BYTEARRAY when you compile your applications.
1350
1351 Note: A QByteArray can store any byte values including '\\0's,
1352 but most functions that take \c{char *} arguments assume that the
1353 data ends at the first '\\0' they encounter.
1354
1355 \sa constData()
1356*/
1357
1358/*!
1359 \macro QT_NO_CAST_FROM_BYTEARRAY
1360 \relates QByteArray
1361
1362 Disables automatic conversions from QByteArray to
1363 const char * or const void *.
1364
1365 \sa QT_NO_CAST_TO_ASCII, QT_NO_CAST_FROM_ASCII
1366*/
1367
1368/*! \fn char *QByteArray::data()
1369
1370 Returns a pointer to the data stored in the byte array. The
1371 pointer can be used to access and modify the bytes that compose
1372 the array. The data is '\\0'-terminated, i.e. the number of
1373 bytes in the returned character string is size() + 1 for the
1374 '\\0' terminator.
1375
1376 Example:
1377 \snippet code/src_corelib_tools_qbytearray.cpp 8
1378
1379 The pointer remains valid as long as the byte array isn't
1380 reallocated or destroyed. For read-only access, constData() is
1381 faster because it never causes a \l{deep copy} to occur.
1382
1383 This function is mostly useful to pass a byte array to a function
1384 that accepts a \c{const char *}.
1385
1386 The following example makes a copy of the char* returned by
1387 data(), but it will corrupt the heap and cause a crash because it
1388 does not allocate a byte for the '\\0' at the end:
1389
1390 \snippet code/src_corelib_tools_qbytearray.cpp 46
1391
1392 This one allocates the correct amount of space:
1393
1394 \snippet code/src_corelib_tools_qbytearray.cpp 47
1395
1396 Note: A QByteArray can store any byte values including '\\0's,
1397 but most functions that take \c{char *} arguments assume that the
1398 data ends at the first '\\0' they encounter.
1399
1400 \sa constData(), operator[]()
1401*/
1402
1403/*! \fn const char *QByteArray::data() const
1404
1405 \overload
1406*/
1407
1408/*! \fn const char *QByteArray::constData() const
1409
1410 Returns a pointer to the data stored in the byte array. The pointer can be
1411 used to access the bytes that compose the array. The data is
1412 '\\0'-terminated unless the QByteArray object was created from raw data.
1413 The pointer remains valid as long as the byte array isn't reallocated or
1414 destroyed.
1415
1416 This function is mostly useful to pass a byte array to a function
1417 that accepts a \c{const char *}.
1418
1419 Note: A QByteArray can store any byte values including '\\0's,
1420 but most functions that take \c{char *} arguments assume that the
1421 data ends at the first '\\0' they encounter.
1422
1423 \sa data(), operator[](), fromRawData()
1424*/
1425
1426/*! \fn void QByteArray::detach()
1427
1428 \internal
1429*/
1430
1431/*! \fn bool QByteArray::isDetached() const
1432
1433 \internal
1434*/
1435
1436/*! \fn bool QByteArray::isSharedWith(const QByteArray &other) const
1437
1438 \internal
1439*/
1440
1441/*! \fn char QByteArray::at(int i) const
1442
1443 Returns the character at index position \a i in the byte array.
1444
1445 \a i must be a valid index position in the byte array (i.e., 0 <=
1446 \a i < size()).
1447
1448 \sa operator[]()
1449*/
1450
1451/*! \fn QByteRef QByteArray::operator[](int i)
1452
1453 Returns the byte at index position \a i as a modifiable reference.
1454
1455 If an assignment is made beyond the end of the byte array, the
1456 array is extended with resize() before the assignment takes
1457 place.
1458
1459 Example:
1460 \snippet code/src_corelib_tools_qbytearray.cpp 9
1461
1462 The return value is of type QByteRef, a helper class for
1463 QByteArray. When you get an object of type QByteRef, you can use
1464 it as if it were a char &. If you assign to it, the assignment
1465 will apply to the character in the QByteArray from which you got
1466 the reference.
1467
1468 \note Before Qt 5.14 it was possible to use this operator to access
1469 a character at an out-of-bounds position in the byte array, and
1470 then assign to such a position, causing the byte array to be
1471 automatically resized. Furthermore, assigning a value to the
1472 returned QByteRef would cause a detach of the byte array, even if the
1473 byte array has been copied in the meanwhile (and the QByteRef kept
1474 alive while the copy was taken). These behaviors are deprecated,
1475 and will be changed in a future version of Qt.
1476
1477 \sa at()
1478*/
1479
1480/*! \fn char QByteArray::operator[](int i) const
1481
1482 \overload
1483
1484 Same as at(\a i).
1485*/
1486
1487/*! \fn QByteRef QByteArray::operator[](uint i)
1488
1489 \overload
1490*/
1491
1492/*! \fn char QByteArray::operator[](uint i) const
1493
1494 \overload
1495*/
1496
1497/*!
1498 \fn char QByteArray::front() const
1499 \since 5.10
1500
1501 Returns the first character in the byte array.
1502 Same as \c{at(0)}.
1503
1504 This function is provided for STL compatibility.
1505
1506 \warning Calling this function on an empty byte array constitutes
1507 undefined behavior.
1508
1509 \sa back(), at(), operator[]()
1510*/
1511
1512/*!
1513 \fn char QByteArray::back() const
1514 \since 5.10
1515
1516 Returns the last character in the byte array.
1517 Same as \c{at(size() - 1)}.
1518
1519 This function is provided for STL compatibility.
1520
1521 \warning Calling this function on an empty byte array constitutes
1522 undefined behavior.
1523
1524 \sa front(), at(), operator[]()
1525*/
1526
1527/*!
1528 \fn QByteRef QByteArray::front()
1529 \since 5.10
1530
1531 Returns a reference to the first character in the byte array.
1532 Same as \c{operator[](0)}.
1533
1534 This function is provided for STL compatibility.
1535
1536 \warning Calling this function on an empty byte array constitutes
1537 undefined behavior.
1538
1539 \sa back(), at(), operator[]()
1540*/
1541
1542/*!
1543 \fn QByteRef QByteArray::back()
1544 \since 5.10
1545
1546 Returns a reference to the last character in the byte array.
1547 Same as \c{operator[](size() - 1)}.
1548
1549 This function is provided for STL compatibility.
1550
1551 \warning Calling this function on an empty byte array constitutes
1552 undefined behavior.
1553
1554 \sa front(), at(), operator[]()
1555*/
1556
1557/*! \fn bool QByteArray::contains(const QByteArray &ba) const
1558
1559 Returns \c true if the byte array contains an occurrence of the byte
1560 array \a ba; otherwise returns \c false.
1561
1562 \sa indexOf(), count()
1563*/
1564
1565/*! \fn bool QByteArray::contains(const char *str) const
1566
1567 \overload
1568
1569 Returns \c true if the byte array contains the string \a str;
1570 otherwise returns \c false.
1571*/
1572
1573/*! \fn bool QByteArray::contains(char ch) const
1574
1575 \overload
1576
1577 Returns \c true if the byte array contains the character \a ch;
1578 otherwise returns \c false.
1579*/
1580
1581/*!
1582
1583 Truncates the byte array at index position \a pos.
1584
1585 If \a pos is beyond the end of the array, nothing happens.
1586
1587 Example:
1588 \snippet code/src_corelib_tools_qbytearray.cpp 10
1589
1590 \sa chop(), resize(), left()
1591*/
1592void QByteArray::truncate(int pos)
1593{
1594 if (pos < d->size)
1595 resize(size: pos);
1596}
1597
1598/*!
1599
1600 Removes \a n bytes from the end of the byte array.
1601
1602 If \a n is greater than size(), the result is an empty byte
1603 array.
1604
1605 Example:
1606 \snippet code/src_corelib_tools_qbytearray.cpp 11
1607
1608 \sa truncate(), resize(), left()
1609*/
1610
1611void QByteArray::chop(int n)
1612{
1613 if (n > 0)
1614 resize(size: d->size - n);
1615}
1616
1617
1618/*! \fn QByteArray &QByteArray::operator+=(const QByteArray &ba)
1619
1620 Appends the byte array \a ba onto the end of this byte array and
1621 returns a reference to this byte array.
1622
1623 Example:
1624 \snippet code/src_corelib_tools_qbytearray.cpp 12
1625
1626 Note: QByteArray is an \l{implicitly shared} class. Consequently,
1627 if you append to an empty byte array, then the byte array will just
1628 share the data held in \a ba. In this case, no copying of data is done,
1629 taking \l{constant time}. If a shared instance is modified, it will
1630 be copied (copy-on-write), taking \l{linear time}.
1631
1632 If the byte array being appended to is not empty, a deep copy of the
1633 data is performed, taking \l{linear time}.
1634
1635 This operation typically does not suffer from allocation overhead,
1636 because QByteArray preallocates extra space at the end of the data
1637 so that it may grow without reallocating for each append operation.
1638
1639 \sa append(), prepend()
1640*/
1641
1642/*! \fn QByteArray &QByteArray::operator+=(const QString &str)
1643
1644 \overload
1645 \obsolete
1646
1647 Appends the string \a str onto the end of this byte array and
1648 returns a reference to this byte array. The Unicode data is
1649 converted into 8-bit characters using QString::toUtf8().
1650
1651 You can disable this function by defining \c QT_NO_CAST_TO_ASCII when you
1652 compile your applications. You then need to call QString::toUtf8() (or
1653 QString::toLatin1() or QString::toLocal8Bit()) explicitly if you want to
1654 convert the data to \c{const char *}.
1655*/
1656
1657/*! \fn QByteArray &QByteArray::operator+=(const char *str)
1658
1659 \overload
1660
1661 Appends the string \a str onto the end of this byte array and
1662 returns a reference to this byte array.
1663*/
1664
1665/*! \fn QByteArray &QByteArray::operator+=(char ch)
1666
1667 \overload
1668
1669 Appends the character \a ch onto the end of this byte array and
1670 returns a reference to this byte array.
1671*/
1672
1673/*! \fn int QByteArray::length() const
1674
1675 Same as size().
1676*/
1677
1678/*! \fn bool QByteArray::isNull() const
1679
1680 Returns \c true if this byte array is null; otherwise returns \c false.
1681
1682 Example:
1683 \snippet code/src_corelib_tools_qbytearray.cpp 13
1684
1685 Qt makes a distinction between null byte arrays and empty byte
1686 arrays for historical reasons. For most applications, what
1687 matters is whether or not a byte array contains any data,
1688 and this can be determined using isEmpty().
1689
1690 \sa isEmpty()
1691*/
1692
1693/*! \fn QByteArray::QByteArray()
1694
1695 Constructs an empty byte array.
1696
1697 \sa isEmpty()
1698*/
1699
1700/*!
1701 Constructs a byte array containing the first \a size bytes of
1702 array \a data.
1703
1704 If \a data is 0, a null byte array is constructed.
1705
1706 If \a size is negative, \a data is assumed to point to a
1707 '\\0'-terminated string and its length is determined dynamically.
1708 The terminating \\0 character is not considered part of the
1709 byte array.
1710
1711 QByteArray makes a deep copy of the string data.
1712
1713 \sa fromRawData()
1714*/
1715
1716QByteArray::QByteArray(const char *data, int size)
1717{
1718 if (!data) {
1719 d = Data::sharedNull();
1720 } else {
1721 if (size < 0)
1722 size = int(strlen(s: data));
1723 if (!size) {
1724 d = Data::allocate(capacity: 0);
1725 } else {
1726 d = Data::allocate(capacity: uint(size) + 1u);
1727 Q_CHECK_PTR(d);
1728 d->size = size;
1729 memcpy(dest: d->data(), src: data, n: size);
1730 d->data()[size] = '\0';
1731 }
1732 }
1733}
1734
1735/*!
1736 Constructs a byte array of size \a size with every byte set to
1737 character \a ch.
1738
1739 \sa fill()
1740*/
1741
1742QByteArray::QByteArray(int size, char ch)
1743{
1744 if (size <= 0) {
1745 d = Data::allocate(capacity: 0);
1746 } else {
1747 d = Data::allocate(capacity: uint(size) + 1u);
1748 Q_CHECK_PTR(d);
1749 d->size = size;
1750 memset(s: d->data(), c: ch, n: size);
1751 d->data()[size] = '\0';
1752 }
1753}
1754
1755/*!
1756 \internal
1757
1758 Constructs a byte array of size \a size with uninitialized contents.
1759*/
1760
1761QByteArray::QByteArray(int size, Qt::Initialization)
1762{
1763 d = Data::allocate(capacity: uint(size) + 1u);
1764 Q_CHECK_PTR(d);
1765 d->size = size;
1766 d->data()[size] = '\0';
1767}
1768
1769/*!
1770 Sets the size of the byte array to \a size bytes.
1771
1772 If \a size is greater than the current size, the byte array is
1773 extended to make it \a size bytes with the extra bytes added to
1774 the end. The new bytes are uninitialized.
1775
1776 If \a size is less than the current size, bytes are removed from
1777 the end.
1778
1779 \sa size(), truncate()
1780*/
1781void QByteArray::resize(int size)
1782{
1783 if (size < 0)
1784 size = 0;
1785
1786 if (IS_RAW_DATA(d) && !d->ref.isShared() && size < d->size) {
1787 d->size = size;
1788 return;
1789 }
1790
1791 if (d->size == 0 && d->ref.isStatic()) {
1792 //
1793 // Optimize the idiom:
1794 // QByteArray a;
1795 // a.resize(sz);
1796 // ...
1797 // which is used in place of the Qt 3 idiom:
1798 // QByteArray a(sz);
1799 //
1800 Data *x = Data::allocate(capacity: uint(size) + 1u);
1801 Q_CHECK_PTR(x);
1802 x->size = size;
1803 x->data()[size] = '\0';
1804 d = x;
1805 } else {
1806 if (d->ref.isShared() || uint(size) + 1u > d->alloc)
1807 reallocData(alloc: uint(size) + 1u, options: d->detachFlags() | Data::Grow);
1808 if (d->alloc) {
1809 d->size = size;
1810 d->data()[size] = '\0';
1811 }
1812 }
1813}
1814
1815/*!
1816 Sets every byte in the byte array to character \a ch. If \a size
1817 is different from -1 (the default), the byte array is resized to
1818 size \a size beforehand.
1819
1820 Example:
1821 \snippet code/src_corelib_tools_qbytearray.cpp 14
1822
1823 \sa resize()
1824*/
1825
1826QByteArray &QByteArray::fill(char ch, int size)
1827{
1828 resize(size: size < 0 ? d->size : size);
1829 if (d->size)
1830 memset(s: d->data(), c: ch, n: d->size);
1831 return *this;
1832}
1833
1834void QByteArray::reallocData(uint alloc, Data::AllocationOptions options)
1835{
1836 if (d->ref.isShared() || IS_RAW_DATA(d)) {
1837 Data *x = Data::allocate(capacity: alloc, options);
1838 Q_CHECK_PTR(x);
1839 x->size = qMin(a: int(alloc) - 1, b: d->size);
1840 ::memcpy(dest: x->data(), src: d->data(), n: x->size);
1841 x->data()[x->size] = '\0';
1842 if (!d->ref.deref())
1843 Data::deallocate(data: d);
1844 d = x;
1845 } else {
1846 Data *x = Data::reallocateUnaligned(data: d, capacity: alloc, options);
1847 Q_CHECK_PTR(x);
1848 d = x;
1849 }
1850}
1851
1852void QByteArray::expand(int i)
1853{
1854 resize(size: qMax(a: i + 1, b: d->size));
1855}
1856
1857/*!
1858 \internal
1859 Return a QByteArray that is sure to be '\\0'-terminated.
1860
1861 By default, all QByteArray have an extra NUL at the end,
1862 guaranteeing that assumption. However, if QByteArray::fromRawData
1863 is used, then the NUL is there only if the user put it there. We
1864 can't be sure.
1865*/
1866QByteArray QByteArray::nulTerminated() const
1867{
1868 // is this fromRawData?
1869 if (!IS_RAW_DATA(d))
1870 return *this; // no, then we're sure we're zero terminated
1871
1872 QByteArray copy(*this);
1873 copy.detach();
1874 return copy;
1875}
1876
1877/*!
1878 Prepends the byte array \a ba to this byte array and returns a
1879 reference to this byte array.
1880
1881 Example:
1882 \snippet code/src_corelib_tools_qbytearray.cpp 15
1883
1884 This is the same as insert(0, \a ba).
1885
1886 Note: QByteArray is an \l{implicitly shared} class. Consequently,
1887 if you prepend to an empty byte array, then the byte array will just
1888 share the data held in \a ba. In this case, no copying of data is done,
1889 taking \l{constant time}. If a shared instance is modified, it will
1890 be copied (copy-on-write), taking \l{linear time}.
1891
1892 If the byte array being prepended to is not empty, a deep copy of the
1893 data is performed, taking \l{linear time}.
1894
1895 \sa append(), insert()
1896*/
1897
1898QByteArray &QByteArray::prepend(const QByteArray &ba)
1899{
1900 if (d->size == 0 && d->ref.isStatic() && !IS_RAW_DATA(ba.d)) {
1901 *this = ba;
1902 } else if (ba.d->size != 0) {
1903 QByteArray tmp = *this;
1904 *this = ba;
1905 append(a: tmp);
1906 }
1907 return *this;
1908}
1909
1910/*!
1911 \overload
1912
1913 Prepends the string \a str to this byte array.
1914*/
1915
1916QByteArray &QByteArray::prepend(const char *str)
1917{
1918 return prepend(s: str, len: qstrlen(str));
1919}
1920
1921/*!
1922 \overload
1923 \since 4.6
1924
1925 Prepends \a len bytes of the string \a str to this byte array.
1926*/
1927
1928QByteArray &QByteArray::prepend(const char *str, int len)
1929{
1930 if (str) {
1931 if (d->ref.isShared() || uint(d->size + len) + 1u > d->alloc)
1932 reallocData(alloc: uint(d->size + len) + 1u, options: d->detachFlags() | Data::Grow);
1933 memmove(dest: d->data()+len, src: d->data(), n: d->size);
1934 memcpy(dest: d->data(), src: str, n: len);
1935 d->size += len;
1936 d->data()[d->size] = '\0';
1937 }
1938 return *this;
1939}
1940
1941/*! \fn QByteArray &QByteArray::prepend(int count, char ch)
1942
1943 \overload
1944 \since 5.7
1945
1946 Prepends \a count copies of character \a ch to this byte array.
1947*/
1948
1949/*!
1950 \overload
1951
1952 Prepends the character \a ch to this byte array.
1953*/
1954
1955QByteArray &QByteArray::prepend(char ch)
1956{
1957 if (d->ref.isShared() || uint(d->size) + 2u > d->alloc)
1958 reallocData(alloc: uint(d->size) + 2u, options: d->detachFlags() | Data::Grow);
1959 memmove(dest: d->data()+1, src: d->data(), n: d->size);
1960 d->data()[0] = ch;
1961 ++d->size;
1962 d->data()[d->size] = '\0';
1963 return *this;
1964}
1965
1966/*!
1967 Appends the byte array \a ba onto the end of this byte array.
1968
1969 Example:
1970 \snippet code/src_corelib_tools_qbytearray.cpp 16
1971
1972 This is the same as insert(size(), \a ba).
1973
1974 Note: QByteArray is an \l{implicitly shared} class. Consequently,
1975 if you append to an empty byte array, then the byte array will just
1976 share the data held in \a ba. In this case, no copying of data is done,
1977 taking \l{constant time}. If a shared instance is modified, it will
1978 be copied (copy-on-write), taking \l{linear time}.
1979
1980 If the byte array being appended to is not empty, a deep copy of the
1981 data is performed, taking \l{linear time}.
1982
1983 This operation typically does not suffer from allocation overhead,
1984 because QByteArray preallocates extra space at the end of the data
1985 so that it may grow without reallocating for each append operation.
1986
1987 \sa operator+=(), prepend(), insert()
1988*/
1989
1990QByteArray &QByteArray::append(const QByteArray &ba)
1991{
1992 if (d->size == 0 && d->ref.isStatic() && !IS_RAW_DATA(ba.d)) {
1993 *this = ba;
1994 } else if (ba.d->size != 0) {
1995 if (d->ref.isShared() || uint(d->size + ba.d->size) + 1u > d->alloc)
1996 reallocData(alloc: uint(d->size + ba.d->size) + 1u, options: d->detachFlags() | Data::Grow);
1997 memcpy(dest: d->data() + d->size, src: ba.d->data(), n: ba.d->size);
1998 d->size += ba.d->size;
1999 d->data()[d->size] = '\0';
2000 }
2001 return *this;
2002}
2003
2004/*! \fn QByteArray &QByteArray::append(const QString &str)
2005
2006 \overload
2007 \obsolete
2008
2009 Appends the string \a str to this byte array. The Unicode data is
2010 converted into 8-bit characters using QString::toUtf8().
2011
2012 You can disable this function by defining \c QT_NO_CAST_TO_ASCII when you
2013 compile your applications. You then need to call QString::toUtf8() (or
2014 QString::toLatin1() or QString::toLocal8Bit()) explicitly if you want to
2015 convert the data to \c{const char *}.
2016*/
2017
2018/*!
2019 \overload
2020
2021 Appends the string \a str to this byte array.
2022*/
2023
2024QByteArray& QByteArray::append(const char *str)
2025{
2026 if (str) {
2027 const int len = int(strlen(s: str));
2028 if (d->ref.isShared() || uint(d->size + len) + 1u > d->alloc)
2029 reallocData(alloc: uint(d->size + len) + 1u, options: d->detachFlags() | Data::Grow);
2030 memcpy(dest: d->data() + d->size, src: str, n: len + 1); // include null terminator
2031 d->size += len;
2032 }
2033 return *this;
2034}
2035
2036/*!
2037 \overload append()
2038
2039 Appends the first \a len characters of the string \a str to this byte
2040 array and returns a reference to this byte array.
2041
2042 If \a len is negative, the length of the string will be determined
2043 automatically using qstrlen(). If \a len is zero or \a str is
2044 null, nothing is appended to the byte array. Ensure that \a len is
2045 \e not longer than \a str.
2046*/
2047
2048QByteArray &QByteArray::append(const char *str, int len)
2049{
2050 if (len < 0)
2051 len = qstrlen(str);
2052 if (str && len) {
2053 if (d->ref.isShared() || uint(d->size + len) + 1u > d->alloc)
2054 reallocData(alloc: uint(d->size + len) + 1u, options: d->detachFlags() | Data::Grow);
2055 memcpy(dest: d->data() + d->size, src: str, n: len); // include null terminator
2056 d->size += len;
2057 d->data()[d->size] = '\0';
2058 }
2059 return *this;
2060}
2061
2062/*! \fn QByteArray &QByteArray::append(int count, char ch)
2063
2064 \overload
2065 \since 5.7
2066
2067 Appends \a count copies of character \a ch to this byte
2068 array and returns a reference to this byte array.
2069
2070 If \a count is negative or zero nothing is appended to the byte array.
2071*/
2072
2073/*!
2074 \overload
2075
2076 Appends the character \a ch to this byte array.
2077*/
2078
2079QByteArray& QByteArray::append(char ch)
2080{
2081 if (d->ref.isShared() || uint(d->size) + 2u > d->alloc)
2082 reallocData(alloc: uint(d->size) + 2u, options: d->detachFlags() | Data::Grow);
2083 d->data()[d->size++] = ch;
2084 d->data()[d->size] = '\0';
2085 return *this;
2086}
2087
2088/*!
2089 \internal
2090 Inserts \a len bytes from the array \a arr at position \a pos and returns a
2091 reference the modified byte array.
2092*/
2093static inline QByteArray &qbytearray_insert(QByteArray *ba,
2094 int pos, const char *arr, int len)
2095{
2096 Q_ASSERT(pos >= 0);
2097
2098 if (pos < 0 || len <= 0 || arr == nullptr)
2099 return *ba;
2100
2101 int oldsize = ba->size();
2102 ba->resize(size: qMax(a: pos, b: oldsize) + len);
2103 char *dst = ba->data();
2104 if (pos > oldsize)
2105 ::memset(s: dst + oldsize, c: 0x20, n: pos - oldsize);
2106 else
2107 ::memmove(dest: dst + pos + len, src: dst + pos, n: oldsize - pos);
2108 memcpy(dest: dst + pos, src: arr, n: len);
2109 return *ba;
2110}
2111
2112/*!
2113 Inserts the byte array \a ba at index position \a i and returns a
2114 reference to this byte array.
2115
2116 Example:
2117 \snippet code/src_corelib_tools_qbytearray.cpp 17
2118
2119 \sa append(), prepend(), replace(), remove()
2120*/
2121
2122QByteArray &QByteArray::insert(int i, const QByteArray &ba)
2123{
2124 QByteArray copy(ba);
2125 return qbytearray_insert(ba: this, pos: i, arr: copy.d->data(), len: copy.d->size);
2126}
2127
2128/*!
2129 \fn QByteArray &QByteArray::insert(int i, const QString &str)
2130
2131 \overload
2132 \obsolete
2133
2134 Inserts the string \a str at index position \a i in the byte
2135 array. The Unicode data is converted into 8-bit characters using
2136 QString::toUtf8().
2137
2138 If \a i is greater than size(), the array is first extended using
2139 resize().
2140
2141 You can disable this function by defining \c QT_NO_CAST_TO_ASCII when you
2142 compile your applications. You then need to call QString::toUtf8() (or
2143 QString::toLatin1() or QString::toLocal8Bit()) explicitly if you want to
2144 convert the data to \c{const char *}.
2145*/
2146
2147/*!
2148 \overload
2149
2150 Inserts the string \a str at position \a i in the byte array.
2151
2152 If \a i is greater than size(), the array is first extended using
2153 resize().
2154*/
2155
2156QByteArray &QByteArray::insert(int i, const char *str)
2157{
2158 return qbytearray_insert(ba: this, pos: i, arr: str, len: qstrlen(str));
2159}
2160
2161/*!
2162 \overload
2163 \since 4.6
2164
2165 Inserts \a len bytes of the string \a str at position
2166 \a i in the byte array.
2167
2168 If \a i is greater than size(), the array is first extended using
2169 resize().
2170*/
2171
2172QByteArray &QByteArray::insert(int i, const char *str, int len)
2173{
2174 return qbytearray_insert(ba: this, pos: i, arr: str, len);
2175}
2176
2177/*!
2178 \overload
2179
2180 Inserts character \a ch at index position \a i in the byte array.
2181 If \a i is greater than size(), the array is first extended using
2182 resize().
2183*/
2184
2185QByteArray &QByteArray::insert(int i, char ch)
2186{
2187 return qbytearray_insert(ba: this, pos: i, arr: &ch, len: 1);
2188}
2189
2190/*! \fn QByteArray &QByteArray::insert(int i, int count, char ch)
2191
2192 \overload
2193 \since 5.7
2194
2195 Inserts \a count copies of character \a ch at index position \a i in the
2196 byte array.
2197
2198 If \a i is greater than size(), the array is first extended using resize().
2199*/
2200
2201QByteArray &QByteArray::insert(int i, int count, char ch)
2202{
2203 if (i < 0 || count <= 0)
2204 return *this;
2205
2206 int oldsize = size();
2207 resize(size: qMax(a: i, b: oldsize) + count);
2208 char *dst = d->data();
2209 if (i > oldsize)
2210 ::memset(s: dst + oldsize, c: 0x20, n: i - oldsize);
2211 else if (i < oldsize)
2212 ::memmove(dest: dst + i + count, src: dst + i, n: oldsize - i);
2213 ::memset(s: dst + i, c: ch, n: count);
2214 return *this;
2215}
2216
2217/*!
2218 Removes \a len bytes from the array, starting at index position \a
2219 pos, and returns a reference to the array.
2220
2221 If \a pos is out of range, nothing happens. If \a pos is valid,
2222 but \a pos + \a len is larger than the size of the array, the
2223 array is truncated at position \a pos.
2224
2225 Example:
2226 \snippet code/src_corelib_tools_qbytearray.cpp 18
2227
2228 \sa insert(), replace()
2229*/
2230
2231QByteArray &QByteArray::remove(int pos, int len)
2232{
2233 if (len <= 0 || uint(pos) >= uint(d->size))
2234 return *this;
2235 detach();
2236 if (len >= d->size - pos) {
2237 resize(size: pos);
2238 } else {
2239 memmove(dest: d->data() + pos, src: d->data() + pos + len, n: d->size - pos - len);
2240 resize(size: d->size - len);
2241 }
2242 return *this;
2243}
2244
2245/*!
2246 Replaces \a len bytes from index position \a pos with the byte
2247 array \a after, and returns a reference to this byte array.
2248
2249 Example:
2250 \snippet code/src_corelib_tools_qbytearray.cpp 19
2251
2252 \sa insert(), remove()
2253*/
2254
2255QByteArray &QByteArray::replace(int pos, int len, const QByteArray &after)
2256{
2257 if (len == after.d->size && (pos + len <= d->size)) {
2258 detach();
2259 memmove(dest: d->data() + pos, src: after.d->data(), n: len*sizeof(char));
2260 return *this;
2261 } else {
2262 QByteArray copy(after);
2263 // ### optimize me
2264 remove(pos, len);
2265 return insert(i: pos, ba: copy);
2266 }
2267}
2268
2269/*! \fn QByteArray &QByteArray::replace(int pos, int len, const char *after)
2270
2271 \overload
2272
2273 Replaces \a len bytes from index position \a pos with the
2274 '\\0'-terminated string \a after.
2275
2276 Notice: this can change the length of the byte array.
2277*/
2278QByteArray &QByteArray::replace(int pos, int len, const char *after)
2279{
2280 return replace(index: pos,len,s: after,alen: qstrlen(str: after));
2281}
2282
2283/*! \fn QByteArray &QByteArray::replace(int pos, int len, const char *after, int alen)
2284
2285 \overload
2286
2287 Replaces \a len bytes from index position \a pos with \a alen bytes
2288 from the string \a after. \a after is allowed to have '\\0' characters.
2289
2290 \since 4.7
2291*/
2292QByteArray &QByteArray::replace(int pos, int len, const char *after, int alen)
2293{
2294 if (len == alen && (pos + len <= d->size)) {
2295 detach();
2296 memcpy(dest: d->data() + pos, src: after, n: len*sizeof(char));
2297 return *this;
2298 } else {
2299 remove(pos, len);
2300 return qbytearray_insert(ba: this, pos, arr: after, len: alen);
2301 }
2302}
2303
2304// ### optimize all other replace method, by offering
2305// QByteArray::replace(const char *before, int blen, const char *after, int alen)
2306
2307/*!
2308 \overload
2309
2310 Replaces every occurrence of the byte array \a before with the
2311 byte array \a after.
2312
2313 Example:
2314 \snippet code/src_corelib_tools_qbytearray.cpp 20
2315*/
2316
2317QByteArray &QByteArray::replace(const QByteArray &before, const QByteArray &after)
2318{
2319 if (isNull() || before.d == after.d)
2320 return *this;
2321
2322 QByteArray aft = after;
2323 if (after.d == d)
2324 aft.detach();
2325
2326 return replace(before: before.constData(), bsize: before.size(), after: aft.constData(), asize: aft.size());
2327}
2328
2329/*!
2330 \fn QByteArray &QByteArray::replace(const char *before, const QByteArray &after)
2331 \overload
2332
2333 Replaces every occurrence of the string \a before with the
2334 byte array \a after.
2335*/
2336
2337QByteArray &QByteArray::replace(const char *c, const QByteArray &after)
2338{
2339 QByteArray aft = after;
2340 if (after.d == d)
2341 aft.detach();
2342
2343 return replace(before: c, bsize: qstrlen(str: c), after: aft.constData(), asize: aft.size());
2344}
2345
2346/*!
2347 \fn QByteArray &QByteArray::replace(const char *before, int bsize, const char *after, int asize)
2348 \overload
2349
2350 Replaces every occurrence of the string \a before with the string \a after.
2351 Since the sizes of the strings are given by \a bsize and \a asize, they
2352 may contain zero characters and do not need to be '\\0'-terminated.
2353*/
2354
2355QByteArray &QByteArray::replace(const char *before, int bsize, const char *after, int asize)
2356{
2357 if (isNull() || (before == after && bsize == asize))
2358 return *this;
2359
2360 // protect against before or after being part of this
2361 const char *a = after;
2362 const char *b = before;
2363 if (after >= d->data() && after < d->data() + d->size) {
2364 char *copy = (char *)malloc(size: asize);
2365 Q_CHECK_PTR(copy);
2366 memcpy(dest: copy, src: after, n: asize);
2367 a = copy;
2368 }
2369 if (before >= d->data() && before < d->data() + d->size) {
2370 char *copy = (char *)malloc(size: bsize);
2371 Q_CHECK_PTR(copy);
2372 memcpy(dest: copy, src: before, n: bsize);
2373 b = copy;
2374 }
2375
2376 QByteArrayMatcher matcher(before, bsize);
2377 int index = 0;
2378 int len = d->size;
2379 char *d = data();
2380
2381 if (bsize == asize) {
2382 if (bsize) {
2383 while ((index = matcher.indexIn(ba: *this, from: index)) != -1) {
2384 memcpy(dest: d + index, src: after, n: asize);
2385 index += bsize;
2386 }
2387 }
2388 } else if (asize < bsize) {
2389 uint to = 0;
2390 uint movestart = 0;
2391 uint num = 0;
2392 while ((index = matcher.indexIn(ba: *this, from: index)) != -1) {
2393 if (num) {
2394 int msize = index - movestart;
2395 if (msize > 0) {
2396 memmove(dest: d + to, src: d + movestart, n: msize);
2397 to += msize;
2398 }
2399 } else {
2400 to = index;
2401 }
2402 if (asize) {
2403 memcpy(dest: d + to, src: after, n: asize);
2404 to += asize;
2405 }
2406 index += bsize;
2407 movestart = index;
2408 num++;
2409 }
2410 if (num) {
2411 int msize = len - movestart;
2412 if (msize > 0)
2413 memmove(dest: d + to, src: d + movestart, n: msize);
2414 resize(size: len - num*(bsize-asize));
2415 }
2416 } else {
2417 // the most complex case. We don't want to lose performance by doing repeated
2418 // copies and reallocs of the string.
2419 while (index != -1) {
2420 uint indices[4096];
2421 uint pos = 0;
2422 while(pos < 4095) {
2423 index = matcher.indexIn(ba: *this, from: index);
2424 if (index == -1)
2425 break;
2426 indices[pos++] = index;
2427 index += bsize;
2428 // avoid infinite loop
2429 if (!bsize)
2430 index++;
2431 }
2432 if (!pos)
2433 break;
2434
2435 // we have a table of replacement positions, use them for fast replacing
2436 int adjust = pos*(asize-bsize);
2437 // index has to be adjusted in case we get back into the loop above.
2438 if (index != -1)
2439 index += adjust;
2440 int newlen = len + adjust;
2441 int moveend = len;
2442 if (newlen > len) {
2443 resize(size: newlen);
2444 len = newlen;
2445 }
2446 d = this->d->data();
2447
2448 while(pos) {
2449 pos--;
2450 int movestart = indices[pos] + bsize;
2451 int insertstart = indices[pos] + pos*(asize-bsize);
2452 int moveto = insertstart + asize;
2453 memmove(dest: d + moveto, src: d + movestart, n: (moveend - movestart));
2454 if (asize)
2455 memcpy(dest: d + insertstart, src: after, n: asize);
2456 moveend = movestart - bsize;
2457 }
2458 }
2459 }
2460
2461 if (a != after)
2462 ::free(ptr: const_cast<char *>(a));
2463 if (b != before)
2464 ::free(ptr: const_cast<char *>(b));
2465
2466
2467 return *this;
2468}
2469
2470
2471/*!
2472 \fn QByteArray &QByteArray::replace(const QByteArray &before, const char *after)
2473 \overload
2474
2475 Replaces every occurrence of the byte array \a before with the
2476 string \a after.
2477*/
2478
2479/*! \fn QByteArray &QByteArray::replace(const QString &before, const QByteArray &after)
2480
2481 \overload
2482 \obsolete
2483
2484 Replaces every occurrence of the string \a before with the byte
2485 array \a after. The Unicode data is converted into 8-bit
2486 characters using QString::toUtf8().
2487
2488 You can disable this function by defining \c QT_NO_CAST_TO_ASCII when you
2489 compile your applications. You then need to call QString::toUtf8() (or
2490 QString::toLatin1() or QString::toLocal8Bit()) explicitly if you want to
2491 convert the data to \c{const char *}.
2492*/
2493
2494/*! \fn QByteArray &QByteArray::replace(const QString &before, const char *after)
2495 \overload
2496 \obsolete
2497
2498 Replaces every occurrence of the string \a before with the string
2499 \a after.
2500*/
2501
2502/*! \fn QByteArray &QByteArray::replace(const char *before, const char *after)
2503
2504 \overload
2505
2506 Replaces every occurrence of the string \a before with the string
2507 \a after.
2508*/
2509
2510/*!
2511 \overload
2512
2513 Replaces every occurrence of the character \a before with the
2514 byte array \a after.
2515*/
2516
2517QByteArray &QByteArray::replace(char before, const QByteArray &after)
2518{
2519 char b[2] = { before, '\0' };
2520 QByteArray cb = fromRawData(b, size: 1);
2521 return replace(before: cb, after);
2522}
2523
2524/*! \fn QByteArray &QByteArray::replace(char before, const QString &after)
2525
2526 \overload
2527 \obsolete
2528
2529 Replaces every occurrence of the character \a before with the
2530 string \a after. The Unicode data is converted into 8-bit
2531 characters using QString::toUtf8().
2532
2533 You can disable this function by defining \c QT_NO_CAST_TO_ASCII when you
2534 compile your applications. You then need to call QString::toUtf8() (or
2535 QString::toLatin1() or QString::toLocal8Bit()) explicitly if you want to
2536 convert the data to \c{const char *}.
2537*/
2538
2539/*! \fn QByteArray &QByteArray::replace(char before, const char *after)
2540
2541 \overload
2542
2543 Replaces every occurrence of the character \a before with the
2544 string \a after.
2545*/
2546
2547/*!
2548 \overload
2549
2550 Replaces every occurrence of the character \a before with the
2551 character \a after.
2552*/
2553
2554QByteArray &QByteArray::replace(char before, char after)
2555{
2556 if (d->size) {
2557 char *i = data();
2558 char *e = i + d->size;
2559 for (; i != e; ++i)
2560 if (*i == before)
2561 * i = after;
2562 }
2563 return *this;
2564}
2565
2566/*!
2567 Splits the byte array into subarrays wherever \a sep occurs, and
2568 returns the list of those arrays. If \a sep does not match
2569 anywhere in the byte array, split() returns a single-element list
2570 containing this byte array.
2571*/
2572
2573QList<QByteArray> QByteArray::split(char sep) const
2574{
2575 QList<QByteArray> list;
2576 int start = 0;
2577 int end;
2578 while ((end = indexOf(c: sep, from: start)) != -1) {
2579 list.append(t: mid(index: start, len: end - start));
2580 start = end + 1;
2581 }
2582 list.append(t: mid(index: start));
2583 return list;
2584}
2585
2586/*!
2587 \since 4.5
2588
2589 Returns a copy of this byte array repeated the specified number of \a times.
2590
2591 If \a times is less than 1, an empty byte array is returned.
2592
2593 Example:
2594
2595 \snippet code/src_corelib_tools_qbytearray.cpp 49
2596*/
2597QByteArray QByteArray::repeated(int times) const
2598{
2599 if (d->size == 0)
2600 return *this;
2601
2602 if (times <= 1) {
2603 if (times == 1)
2604 return *this;
2605 return QByteArray();
2606 }
2607
2608 const int resultSize = times * d->size;
2609
2610 QByteArray result;
2611 result.reserve(asize: resultSize);
2612 if (result.d->alloc != uint(resultSize) + 1u)
2613 return QByteArray(); // not enough memory
2614
2615 memcpy(dest: result.d->data(), src: d->data(), n: d->size);
2616
2617 int sizeSoFar = d->size;
2618 char *end = result.d->data() + sizeSoFar;
2619
2620 const int halfResultSize = resultSize >> 1;
2621 while (sizeSoFar <= halfResultSize) {
2622 memcpy(dest: end, src: result.d->data(), n: sizeSoFar);
2623 end += sizeSoFar;
2624 sizeSoFar <<= 1;
2625 }
2626 memcpy(dest: end, src: result.d->data(), n: resultSize - sizeSoFar);
2627 result.d->data()[resultSize] = '\0';
2628 result.d->size = resultSize;
2629 return result;
2630}
2631
2632#define REHASH(a) \
2633 if (ol_minus_1 < sizeof(uint) * CHAR_BIT) \
2634 hashHaystack -= (a) << ol_minus_1; \
2635 hashHaystack <<= 1
2636
2637/*!
2638 Returns the index position of the first occurrence of the byte
2639 array \a ba in this byte array, searching forward from index
2640 position \a from. Returns -1 if \a ba could not be found.
2641
2642 Example:
2643 \snippet code/src_corelib_tools_qbytearray.cpp 21
2644
2645 \sa lastIndexOf(), contains(), count()
2646*/
2647
2648int QByteArray::indexOf(const QByteArray &ba, int from) const
2649{
2650 const int ol = ba.d->size;
2651 if (ol == 0)
2652 return from;
2653 if (ol == 1)
2654 return indexOf(c: *ba.d->data(), from);
2655
2656 const int l = d->size;
2657 if (from > d->size || ol + from > l)
2658 return -1;
2659
2660 return qFindByteArray(haystack0: d->data(), haystackLen: d->size, from, needle0: ba.d->data(), needleLen: ol);
2661}
2662
2663/*! \fn int QByteArray::indexOf(const QString &str, int from) const
2664
2665 \overload
2666 \obsolete
2667
2668 Returns the index position of the first occurrence of the string
2669 \a str in the byte array, searching forward from index position
2670 \a from. Returns -1 if \a str could not be found.
2671
2672 The Unicode data is converted into 8-bit characters using
2673 QString::toUtf8().
2674
2675 You can disable this function by defining \c QT_NO_CAST_TO_ASCII when you
2676 compile your applications. You then need to call QString::toUtf8() (or
2677 QString::toLatin1() or QString::toLocal8Bit()) explicitly if you want to
2678 convert the data to \c{const char *}.
2679*/
2680
2681/*! \fn int QByteArray::indexOf(const char *str, int from) const
2682
2683 \overload
2684
2685 Returns the index position of the first occurrence of the string
2686 \a str in the byte array, searching forward from index position \a
2687 from. Returns -1 if \a str could not be found.
2688*/
2689int QByteArray::indexOf(const char *c, int from) const
2690{
2691 const int ol = qstrlen(str: c);
2692 if (ol == 1)
2693 return indexOf(c: *c, from);
2694
2695 const int l = d->size;
2696 if (from > d->size || ol + from > l)
2697 return -1;
2698 if (ol == 0)
2699 return from;
2700
2701 return qFindByteArray(haystack0: d->data(), haystackLen: d->size, from, needle0: c, needleLen: ol);
2702}
2703
2704/*!
2705 \overload
2706
2707 Returns the index position of the first occurrence of the
2708 character \a ch in the byte array, searching forward from index
2709 position \a from. Returns -1 if \a ch could not be found.
2710
2711 Example:
2712 \snippet code/src_corelib_tools_qbytearray.cpp 22
2713
2714 \sa lastIndexOf(), contains()
2715*/
2716
2717int QByteArray::indexOf(char ch, int from) const
2718{
2719 if (from < 0)
2720 from = qMax(a: from + d->size, b: 0);
2721 if (from < d->size) {
2722 const char *n = d->data() + from - 1;
2723 const char *e = d->data() + d->size;
2724 while (++n != e)
2725 if (*n == ch)
2726 return n - d->data();
2727 }
2728 return -1;
2729}
2730
2731
2732static int lastIndexOfHelper(const char *haystack, int l, const char *needle, int ol, int from)
2733{
2734 int delta = l - ol;
2735 if (from < 0)
2736 from = delta;
2737 if (from < 0 || from > l)
2738 return -1;
2739 if (from > delta)
2740 from = delta;
2741
2742 const char *end = haystack;
2743 haystack += from;
2744 const uint ol_minus_1 = ol - 1;
2745 const char *n = needle + ol_minus_1;
2746 const char *h = haystack + ol_minus_1;
2747 uint hashNeedle = 0, hashHaystack = 0;
2748 int idx;
2749 for (idx = 0; idx < ol; ++idx) {
2750 hashNeedle = ((hashNeedle<<1) + *(n-idx));
2751 hashHaystack = ((hashHaystack<<1) + *(h-idx));
2752 }
2753 hashHaystack -= *haystack;
2754 while (haystack >= end) {
2755 hashHaystack += *haystack;
2756 if (hashHaystack == hashNeedle && memcmp(s1: needle, s2: haystack, n: ol) == 0)
2757 return haystack - end;
2758 --haystack;
2759 REHASH(*(haystack + ol));
2760 }
2761 return -1;
2762
2763}
2764
2765/*!
2766 \fn int QByteArray::lastIndexOf(const QByteArray &ba, int from) const
2767
2768 Returns the index position of the last occurrence of the byte
2769 array \a ba in this byte array, searching backward from index
2770 position \a from. If \a from is -1 (the default), the search
2771 starts at the last byte. Returns -1 if \a ba could not be found.
2772
2773 Example:
2774 \snippet code/src_corelib_tools_qbytearray.cpp 23
2775
2776 \sa indexOf(), contains(), count()
2777*/
2778
2779int QByteArray::lastIndexOf(const QByteArray &ba, int from) const
2780{
2781 const int ol = ba.d->size;
2782 if (ol == 1)
2783 return lastIndexOf(c: *ba.d->data(), from);
2784
2785 return lastIndexOfHelper(haystack: d->data(), l: d->size, needle: ba.d->data(), ol, from);
2786}
2787
2788/*! \fn int QByteArray::lastIndexOf(const QString &str, int from) const
2789
2790 \overload
2791 \obsolete
2792
2793 Returns the index position of the last occurrence of the string \a
2794 str in the byte array, searching backward from index position \a
2795 from. If \a from is -1 (the default), the search starts at the
2796 last (size() - 1) byte. Returns -1 if \a str could not be found.
2797
2798 The Unicode data is converted into 8-bit characters using
2799 QString::toUtf8().
2800
2801 You can disable this function by defining \c QT_NO_CAST_TO_ASCII when you
2802 compile your applications. You then need to call QString::toUtf8() (or
2803 QString::toLatin1() or QString::toLocal8Bit()) explicitly if you want to
2804 convert the data to \c{const char *}.
2805*/
2806
2807/*! \fn int QByteArray::lastIndexOf(const char *str, int from) const
2808 \overload
2809
2810 Returns the index position of the last occurrence of the string \a
2811 str in the byte array, searching backward from index position \a
2812 from. If \a from is -1 (the default), the search starts at the
2813 last (size() - 1) byte. Returns -1 if \a str could not be found.
2814*/
2815int QByteArray::lastIndexOf(const char *str, int from) const
2816{
2817 const int ol = qstrlen(str);
2818 if (ol == 1)
2819 return lastIndexOf(c: *str, from);
2820
2821 return lastIndexOfHelper(haystack: d->data(), l: d->size, needle: str, ol, from);
2822}
2823
2824/*!
2825 \overload
2826
2827 Returns the index position of the last occurrence of character \a
2828 ch in the byte array, searching backward from index position \a
2829 from. If \a from is -1 (the default), the search starts at the
2830 last (size() - 1) byte. Returns -1 if \a ch could not be found.
2831
2832 Example:
2833 \snippet code/src_corelib_tools_qbytearray.cpp 24
2834
2835 \sa indexOf(), contains()
2836*/
2837
2838int QByteArray::lastIndexOf(char ch, int from) const
2839{
2840 if (from < 0)
2841 from += d->size;
2842 else if (from > d->size)
2843 from = d->size-1;
2844 if (from >= 0) {
2845 const char *b = d->data();
2846 const char *n = d->data() + from + 1;
2847 while (n-- != b)
2848 if (*n == ch)
2849 return n - b;
2850 }
2851 return -1;
2852}
2853
2854/*!
2855 Returns the number of (potentially overlapping) occurrences of
2856 byte array \a ba in this byte array.
2857
2858 \sa contains(), indexOf()
2859*/
2860
2861int QByteArray::count(const QByteArray &ba) const
2862{
2863 int num = 0;
2864 int i = -1;
2865 if (d->size > 500 && ba.d->size > 5) {
2866 QByteArrayMatcher matcher(ba);
2867 while ((i = matcher.indexIn(ba: *this, from: i + 1)) != -1)
2868 ++num;
2869 } else {
2870 while ((i = indexOf(ba, from: i + 1)) != -1)
2871 ++num;
2872 }
2873 return num;
2874}
2875
2876/*!
2877 \overload
2878
2879 Returns the number of (potentially overlapping) occurrences of
2880 string \a str in the byte array.
2881*/
2882
2883int QByteArray::count(const char *str) const
2884{
2885 return count(ba: fromRawData(str, size: qstrlen(str)));
2886}
2887
2888/*!
2889 \overload
2890
2891 Returns the number of occurrences of character \a ch in the byte
2892 array.
2893
2894 \sa contains(), indexOf()
2895*/
2896
2897int QByteArray::count(char ch) const
2898{
2899 int num = 0;
2900 const char *i = d->data() + d->size;
2901 const char *b = d->data();
2902 while (i != b)
2903 if (*--i == ch)
2904 ++num;
2905 return num;
2906}
2907
2908/*! \fn int QByteArray::count() const
2909
2910 \overload
2911
2912 Same as size().
2913*/
2914
2915/*!
2916 \fn int QByteArray::compare(const char *c, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
2917 \since 5.12
2918
2919 Returns an integer less than, equal to, or greater than zero depending on
2920 whether this QByteArray sorts before, at the same position, or after the
2921 string pointed to by \a c. The comparison is performed according to case
2922 sensitivity \a cs.
2923
2924 \sa operator==
2925*/
2926
2927/*!
2928 \fn int QByteArray::compare(const QByteArray &a, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
2929 \overload
2930 \since 5.12
2931
2932 Returns an integer less than, equal to, or greater than zero depending on
2933 whether this QByteArray sorts before, at the same position, or after the
2934 QByteArray \a a. The comparison is performed according to case sensitivity
2935 \a cs.
2936
2937 \sa operator==
2938*/
2939
2940/*!
2941 Returns \c true if this byte array starts with byte array \a ba;
2942 otherwise returns \c false.
2943
2944 Example:
2945 \snippet code/src_corelib_tools_qbytearray.cpp 25
2946
2947 \sa endsWith(), left()
2948*/
2949bool QByteArray::startsWith(const QByteArray &ba) const
2950{
2951 if (d == ba.d || ba.d->size == 0)
2952 return true;
2953 if (d->size < ba.d->size)
2954 return false;
2955 return memcmp(s1: d->data(), s2: ba.d->data(), n: ba.d->size) == 0;
2956}
2957
2958/*! \overload
2959
2960 Returns \c true if this byte array starts with string \a str;
2961 otherwise returns \c false.
2962*/
2963bool QByteArray::startsWith(const char *str) const
2964{
2965 if (!str || !*str)
2966 return true;
2967 const int len = int(strlen(s: str));
2968 if (d->size < len)
2969 return false;
2970 return qstrncmp(str1: d->data(), str2: str, len) == 0;
2971}
2972
2973/*! \overload
2974
2975 Returns \c true if this byte array starts with character \a ch;
2976 otherwise returns \c false.
2977*/
2978bool QByteArray::startsWith(char ch) const
2979{
2980 if (d->size == 0)
2981 return false;
2982 return d->data()[0] == ch;
2983}
2984
2985/*!
2986 Returns \c true if this byte array ends with byte array \a ba;
2987 otherwise returns \c false.
2988
2989 Example:
2990 \snippet code/src_corelib_tools_qbytearray.cpp 26
2991
2992 \sa startsWith(), right()
2993*/
2994bool QByteArray::endsWith(const QByteArray &ba) const
2995{
2996 if (d == ba.d || ba.d->size == 0)
2997 return true;
2998 if (d->size < ba.d->size)
2999 return false;
3000 return memcmp(s1: d->data() + d->size - ba.d->size, s2: ba.d->data(), n: ba.d->size) == 0;
3001}
3002
3003/*! \overload
3004
3005 Returns \c true if this byte array ends with string \a str; otherwise
3006 returns \c false.
3007*/
3008bool QByteArray::endsWith(const char *str) const
3009{
3010 if (!str || !*str)
3011 return true;
3012 const int len = int(strlen(s: str));
3013 if (d->size < len)
3014 return false;
3015 return qstrncmp(str1: d->data() + d->size - len, str2: str, len) == 0;
3016}
3017
3018/*
3019 Returns true if \a c is an uppercase Latin1 letter.
3020 \note The multiplication sign 0xD7 and the sz ligature 0xDF are not
3021 treated as uppercase Latin1.
3022 */
3023static inline bool isUpperCaseLatin1(char c)
3024{
3025 if (c >= 'A' && c <= 'Z')
3026 return true;
3027
3028 return (uchar(c) >= 0xC0 && uchar(c) <= 0xDE && uchar(c) != 0xD7);
3029}
3030
3031/*!
3032 Returns \c true if this byte array contains only uppercase letters,
3033 otherwise returns \c false. The byte array is interpreted as a Latin-1
3034 encoded string.
3035 \since 5.12
3036
3037 \sa isLower(), toUpper()
3038*/
3039bool QByteArray::isUpper() const
3040{
3041 if (isEmpty())
3042 return false;
3043
3044 const char *d = data();
3045
3046 for (int i = 0, max = size(); i < max; ++i) {
3047 if (!isUpperCaseLatin1(c: d[i]))
3048 return false;
3049 }
3050
3051 return true;
3052}
3053
3054/*
3055 Returns true if \a c is an lowercase Latin1 letter.
3056 \note The division sign 0xF7 is not treated as lowercase Latin1,
3057 but the small y dieresis 0xFF is.
3058 */
3059static inline bool isLowerCaseLatin1(char c)
3060{
3061 if (c >= 'a' && c <= 'z')
3062 return true;
3063
3064 return (uchar(c) >= 0xD0 && uchar(c) != 0xF7);
3065}
3066
3067/*!
3068 Returns \c true if this byte array contains only lowercase letters,
3069 otherwise returns \c false. The byte array is interpreted as a Latin-1
3070 encoded string.
3071 \since 5.12
3072
3073 \sa isUpper(), toLower()
3074 */
3075bool QByteArray::isLower() const
3076{
3077 if (isEmpty())
3078 return false;
3079
3080 const char *d = data();
3081
3082 for (int i = 0, max = size(); i < max; ++i) {
3083 if (!isLowerCaseLatin1(c: d[i]))
3084 return false;
3085 }
3086
3087 return true;
3088}
3089
3090/*! \overload
3091
3092 Returns \c true if this byte array ends with character \a ch;
3093 otherwise returns \c false.
3094*/
3095bool QByteArray::endsWith(char ch) const
3096{
3097 if (d->size == 0)
3098 return false;
3099 return d->data()[d->size - 1] == ch;
3100}
3101
3102/*!
3103 Returns a byte array that contains the leftmost \a len bytes of
3104 this byte array.
3105
3106 The entire byte array is returned if \a len is greater than
3107 size().
3108
3109 Example:
3110 \snippet code/src_corelib_tools_qbytearray.cpp 27
3111
3112 \sa startsWith(), right(), mid(), chopped(), chop(), truncate()
3113*/
3114
3115QByteArray QByteArray::left(int len) const
3116{
3117 if (len >= d->size)
3118 return *this;
3119 if (len < 0)
3120 len = 0;
3121 return QByteArray(d->data(), len);
3122}
3123
3124/*!
3125 Returns a byte array that contains the rightmost \a len bytes of
3126 this byte array.
3127
3128 The entire byte array is returned if \a len is greater than
3129 size().
3130
3131 Example:
3132 \snippet code/src_corelib_tools_qbytearray.cpp 28
3133
3134 \sa endsWith(), left(), mid(), chopped(), chop(), truncate()
3135*/
3136
3137QByteArray QByteArray::right(int len) const
3138{
3139 if (len >= d->size)
3140 return *this;
3141 if (len < 0)
3142 len = 0;
3143 return QByteArray(d->data() + d->size - len, len);
3144}
3145
3146/*!
3147 Returns a byte array containing \a len bytes from this byte array,
3148 starting at position \a pos.
3149
3150 If \a len is -1 (the default), or \a pos + \a len >= size(),
3151 returns a byte array containing all bytes starting at position \a
3152 pos until the end of the byte array.
3153
3154 Example:
3155 \snippet code/src_corelib_tools_qbytearray.cpp 29
3156
3157 \sa left(), right(), chopped(), chop(), truncate()
3158*/
3159
3160QByteArray QByteArray::mid(int pos, int len) const
3161{
3162 using namespace QtPrivate;
3163 switch (QContainerImplHelper::mid(originalLength: size(), position: &pos, length: &len)) {
3164 case QContainerImplHelper::Null:
3165 return QByteArray();
3166 case QContainerImplHelper::Empty:
3167 {
3168 QByteArrayDataPtr empty = { .ptr: Data::allocate(capacity: 0) };
3169 return QByteArray(empty);
3170 }
3171 case QContainerImplHelper::Full:
3172 return *this;
3173 case QContainerImplHelper::Subset:
3174 return QByteArray(d->data() + pos, len);
3175 }
3176 Q_UNREACHABLE();
3177 return QByteArray();
3178}
3179
3180/*!
3181 \fn QByteArray::chopped(int len) const
3182 \since 5.10
3183
3184 Returns a byte array that contains the leftmost size() - \a len bytes of
3185 this byte array.
3186
3187 \note The behavior is undefined if \a len is negative or greater than size().
3188
3189 \sa endsWith(), left(), right(), mid(), chop(), truncate()
3190*/
3191
3192/*!
3193 \fn QByteArray QByteArray::toLower() const
3194
3195 Returns a lowercase copy of the byte array. The bytearray is
3196 interpreted as a Latin-1 encoded string.
3197
3198 Example:
3199 \snippet code/src_corelib_tools_qbytearray.cpp 30
3200
3201 \sa isLower(), toUpper(), {8-bit Character Comparisons}
3202*/
3203
3204// prevent the compiler from inlining the function in each of
3205// toLower and toUpper when the only difference is the table being used
3206// (even with constant propagation, there's no gain in performance).
3207template <typename T>
3208Q_NEVER_INLINE
3209static QByteArray toCase_template(T &input, const uchar * table)
3210{
3211 // find the first bad character in input
3212 const char *orig_begin = input.constBegin();
3213 const char *firstBad = orig_begin;
3214 const char *e = input.constEnd();
3215 for ( ; firstBad != e ; ++firstBad) {
3216 uchar ch = uchar(*firstBad);
3217 uchar converted = table[ch];
3218 if (ch != converted)
3219 break;
3220 }
3221
3222 if (firstBad == e)
3223 return std::move(input);
3224
3225 // transform the rest
3226 QByteArray s = std::move(input); // will copy if T is const QByteArray
3227 char *b = s.begin(); // will detach if necessary
3228 char *p = b + (firstBad - orig_begin);
3229 e = b + s.size();
3230 for ( ; p != e; ++p) {
3231 *p = char(uchar(table[uchar(*p)]));
3232 }
3233 return s;
3234}
3235
3236QByteArray QByteArray::toLower_helper(const QByteArray &a)
3237{
3238 return toCase_template(input: a, table: latin1_lowercased);
3239}
3240
3241QByteArray QByteArray::toLower_helper(QByteArray &a)
3242{
3243 return toCase_template(input&: a, table: latin1_lowercased);
3244}
3245
3246/*!
3247 \fn QByteArray QByteArray::toUpper() const
3248
3249 Returns an uppercase copy of the byte array. The bytearray is
3250 interpreted as a Latin-1 encoded string.
3251
3252 Example:
3253 \snippet code/src_corelib_tools_qbytearray.cpp 31
3254
3255 \sa isUpper(), toLower(), {8-bit Character Comparisons}
3256*/
3257
3258QByteArray QByteArray::toUpper_helper(const QByteArray &a)
3259{
3260 return toCase_template(input: a, table: latin1_uppercased);
3261}
3262
3263QByteArray QByteArray::toUpper_helper(QByteArray &a)
3264{
3265 return toCase_template(input&: a, table: latin1_uppercased);
3266}
3267
3268/*! \fn void QByteArray::clear()
3269
3270 Clears the contents of the byte array and makes it null.
3271
3272 \sa resize(), isNull()
3273*/
3274
3275void QByteArray::clear()
3276{
3277 if (!d->ref.deref())
3278 Data::deallocate(data: d);
3279 d = Data::sharedNull();
3280}
3281
3282#if !defined(QT_NO_DATASTREAM) || (defined(QT_BOOTSTRAPPED) && !defined(QT_BUILD_QMAKE))
3283
3284/*! \relates QByteArray
3285
3286 Writes byte array \a ba to the stream \a out and returns a reference
3287 to the stream.
3288
3289 \sa {Serializing Qt Data Types}
3290*/
3291
3292QDataStream &operator<<(QDataStream &out, const QByteArray &ba)
3293{
3294 if (ba.isNull() && out.version() >= 6) {
3295 out << (quint32)0xffffffff;
3296 return out;
3297 }
3298 return out.writeBytes(ba.constData(), len: ba.size());
3299}
3300
3301/*! \relates QByteArray
3302
3303 Reads a byte array into \a ba from the stream \a in and returns a
3304 reference to the stream.
3305
3306 \sa {Serializing Qt Data Types}
3307*/
3308
3309QDataStream &operator>>(QDataStream &in, QByteArray &ba)
3310{
3311 ba.clear();
3312 quint32 len;
3313 in >> len;
3314 if (len == 0xffffffff)
3315 return in;
3316
3317 const quint32 Step = 1024 * 1024;
3318 quint32 allocated = 0;
3319
3320 do {
3321 int blockSize = qMin(a: Step, b: len - allocated);
3322 ba.resize(size: allocated + blockSize);
3323 if (in.readRawData(ba.data() + allocated, len: blockSize) != blockSize) {
3324 ba.clear();
3325 in.setStatus(QDataStream::ReadPastEnd);
3326 return in;
3327 }
3328 allocated += blockSize;
3329 } while (allocated < len);
3330
3331 return in;
3332}
3333#endif // QT_NO_DATASTREAM
3334
3335/*! \fn bool QByteArray::operator==(const QString &str) const
3336
3337 Returns \c true if this byte array is equal to string \a str;
3338 otherwise returns \c false.
3339
3340 The Unicode data is converted into 8-bit characters using
3341 QString::toUtf8().
3342
3343 The comparison is case sensitive.
3344
3345 You can disable this operator by defining \c
3346 QT_NO_CAST_FROM_ASCII when you compile your applications. You
3347 then need to call QString::fromUtf8(), QString::fromLatin1(),
3348 or QString::fromLocal8Bit() explicitly if you want to convert the byte
3349 array to a QString before doing the comparison.
3350*/
3351
3352/*! \fn bool QByteArray::operator!=(const QString &str) const
3353
3354 Returns \c true if this byte array is not equal to string \a str;
3355 otherwise returns \c false.
3356
3357 The Unicode data is converted into 8-bit characters using
3358 QString::toUtf8().
3359
3360 The comparison is case sensitive.
3361
3362 You can disable this operator by defining \c
3363 QT_NO_CAST_FROM_ASCII when you compile your applications. You
3364 then need to call QString::fromUtf8(), QString::fromLatin1(),
3365 or QString::fromLocal8Bit() explicitly if you want to convert the byte
3366 array to a QString before doing the comparison.
3367*/
3368
3369/*! \fn bool QByteArray::operator<(const QString &str) const
3370
3371 Returns \c true if this byte array is lexically less than string \a
3372 str; otherwise returns \c false.
3373
3374 The Unicode data is converted into 8-bit characters using
3375 QString::toUtf8().
3376
3377 The comparison is case sensitive.
3378
3379 You can disable this operator by defining \c
3380 QT_NO_CAST_FROM_ASCII when you compile your applications. You
3381 then need to call QString::fromUtf8(), QString::fromLatin1(),
3382 or QString::fromLocal8Bit() explicitly if you want to convert the byte
3383 array to a QString before doing the comparison.
3384*/
3385
3386/*! \fn bool QByteArray::operator>(const QString &str) const
3387
3388 Returns \c true if this byte array is lexically greater than string
3389 \a str; otherwise returns \c false.
3390
3391 The Unicode data is converted into 8-bit characters using
3392 QString::toUtf8().
3393
3394 The comparison is case sensitive.
3395
3396 You can disable this operator by defining \c
3397 QT_NO_CAST_FROM_ASCII when you compile your applications. You
3398 then need to call QString::fromUtf8(), QString::fromLatin1(),
3399 or QString::fromLocal8Bit() explicitly if you want to convert the byte
3400 array to a QString before doing the comparison.
3401*/
3402
3403/*! \fn bool QByteArray::operator<=(const QString &str) const
3404
3405 Returns \c true if this byte array is lexically less than or equal
3406 to string \a str; otherwise returns \c false.
3407
3408 The Unicode data is converted into 8-bit characters using
3409 QString::toUtf8().
3410
3411 The comparison is case sensitive.
3412
3413 You can disable this operator by defining \c
3414 QT_NO_CAST_FROM_ASCII when you compile your applications. You
3415 then need to call QString::fromUtf8(), QString::fromLatin1(),
3416 or QString::fromLocal8Bit() explicitly if you want to convert the byte
3417 array to a QString before doing the comparison.
3418*/
3419
3420/*! \fn bool QByteArray::operator>=(const QString &str) const
3421
3422 Returns \c true if this byte array is greater than or equal to string
3423 \a str; otherwise returns \c false.
3424
3425 The Unicode data is converted into 8-bit characters using
3426 QString::toUtf8().
3427
3428 The comparison is case sensitive.
3429
3430 You can disable this operator by defining \c
3431 QT_NO_CAST_FROM_ASCII when you compile your applications. You
3432 then need to call QString::fromUtf8(), QString::fromLatin1(),
3433 or QString::fromLocal8Bit() explicitly if you want to convert the byte
3434 array to a QString before doing the comparison.
3435*/
3436
3437/*! \fn bool operator==(const QByteArray &a1, const QByteArray &a2)
3438 \relates QByteArray
3439
3440 \overload
3441
3442 Returns \c true if byte array \a a1 is equal to byte array \a a2;
3443 otherwise returns \c false.
3444
3445 \sa QByteArray::compare()
3446*/
3447
3448/*! \fn bool operator==(const QByteArray &a1, const char *a2)
3449 \relates QByteArray
3450
3451 \overload
3452
3453 Returns \c true if byte array \a a1 is equal to string \a a2;
3454 otherwise returns \c false.
3455
3456 \sa QByteArray::compare()
3457*/
3458
3459/*! \fn bool operator==(const char *a1, const QByteArray &a2)
3460 \relates QByteArray
3461
3462 \overload
3463
3464 Returns \c true if string \a a1 is equal to byte array \a a2;
3465 otherwise returns \c false.
3466
3467 \sa QByteArray::compare()
3468*/
3469
3470/*! \fn bool operator!=(const QByteArray &a1, const QByteArray &a2)
3471 \relates QByteArray
3472
3473 \overload
3474
3475 Returns \c true if byte array \a a1 is not equal to byte array \a a2;
3476 otherwise returns \c false.
3477
3478 \sa QByteArray::compare()
3479*/
3480
3481/*! \fn bool operator!=(const QByteArray &a1, const char *a2)
3482 \relates QByteArray
3483
3484 \overload
3485
3486 Returns \c true if byte array \a a1 is not equal to string \a a2;
3487 otherwise returns \c false.
3488
3489 \sa QByteArray::compare()
3490*/
3491
3492/*! \fn bool operator!=(const char *a1, const QByteArray &a2)
3493 \relates QByteArray
3494
3495 \overload
3496
3497 Returns \c true if string \a a1 is not equal to byte array \a a2;
3498 otherwise returns \c false.
3499
3500 \sa QByteArray::compare()
3501*/
3502
3503/*! \fn bool operator<(const QByteArray &a1, const QByteArray &a2)
3504 \relates QByteArray
3505
3506 \overload
3507
3508 Returns \c true if byte array \a a1 is lexically less than byte array
3509 \a a2; otherwise returns \c false.
3510
3511 \sa QByteArray::compare()
3512*/
3513
3514/*! \fn inline bool operator<(const QByteArray &a1, const char *a2)
3515 \relates QByteArray
3516
3517 \overload
3518
3519 Returns \c true if byte array \a a1 is lexically less than string
3520 \a a2; otherwise returns \c false.
3521
3522 \sa QByteArray::compare()
3523*/
3524
3525/*! \fn bool operator<(const char *a1, const QByteArray &a2)
3526 \relates QByteArray
3527
3528 \overload
3529
3530 Returns \c true if string \a a1 is lexically less than byte array
3531 \a a2; otherwise returns \c false.
3532
3533 \sa QByteArray::compare()
3534*/
3535
3536/*! \fn bool operator<=(const QByteArray &a1, const QByteArray &a2)
3537 \relates QByteArray
3538
3539 \overload
3540
3541 Returns \c true if byte array \a a1 is lexically less than or equal
3542 to byte array \a a2; otherwise returns \c false.
3543
3544 \sa QByteArray::compare()
3545*/
3546
3547/*! \fn bool operator<=(const QByteArray &a1, const char *a2)
3548 \relates QByteArray
3549
3550 \overload
3551
3552 Returns \c true if byte array \a a1 is lexically less than or equal
3553 to string \a a2; otherwise returns \c false.
3554
3555 \sa QByteArray::compare()
3556*/
3557
3558/*! \fn bool operator<=(const char *a1, const QByteArray &a2)
3559 \relates QByteArray
3560
3561 \overload
3562
3563 Returns \c true if string \a a1 is lexically less than or equal
3564 to byte array \a a2; otherwise returns \c false.
3565
3566 \sa QByteArray::compare()
3567*/
3568
3569/*! \fn bool operator>(const QByteArray &a1, const QByteArray &a2)
3570 \relates QByteArray
3571
3572 \overload
3573
3574 Returns \c true if byte array \a a1 is lexically greater than byte
3575 array \a a2; otherwise returns \c false.
3576
3577 \sa QByteArray::compare()
3578*/
3579
3580/*! \fn bool operator>(const QByteArray &a1, const char *a2)
3581 \relates QByteArray
3582
3583 \overload
3584
3585 Returns \c true if byte array \a a1 is lexically greater than string
3586 \a a2; otherwise returns \c false.
3587
3588 \sa QByteArray::compare()
3589*/
3590
3591/*! \fn bool operator>(const char *a1, const QByteArray &a2)
3592 \relates QByteArray
3593
3594 \overload
3595
3596 Returns \c true if string \a a1 is lexically greater than byte array
3597 \a a2; otherwise returns \c false.
3598
3599 \sa QByteArray::compare()
3600*/
3601
3602/*! \fn bool operator>=(const QByteArray &a1, const QByteArray &a2)
3603 \relates QByteArray
3604
3605 \overload
3606
3607 Returns \c true if byte array \a a1 is lexically greater than or
3608 equal to byte array \a a2; otherwise returns \c false.
3609
3610 \sa QByteArray::compare()
3611*/
3612
3613/*! \fn bool operator>=(const QByteArray &a1, const char *a2)
3614 \relates QByteArray
3615
3616 \overload
3617
3618 Returns \c true if byte array \a a1 is lexically greater than or
3619 equal to string \a a2; otherwise returns \c false.
3620
3621 \sa QByteArray::compare()
3622*/
3623
3624/*! \fn bool operator>=(const char *a1, const QByteArray &a2)
3625 \relates QByteArray
3626
3627 \overload
3628
3629 Returns \c true if string \a a1 is lexically greater than or
3630 equal to byte array \a a2; otherwise returns \c false.
3631
3632 \sa QByteArray::compare()
3633*/
3634
3635/*! \fn const QByteArray operator+(const QByteArray &a1, const QByteArray &a2)
3636 \relates QByteArray
3637
3638 Returns a byte array that is the result of concatenating byte
3639 array \a a1 and byte array \a a2.
3640
3641 \sa QByteArray::operator+=()
3642*/
3643
3644/*! \fn const QByteArray operator+(const QByteArray &a1, const char *a2)
3645 \relates QByteArray
3646
3647 \overload
3648
3649 Returns a byte array that is the result of concatenating byte
3650 array \a a1 and string \a a2.
3651*/
3652
3653/*! \fn const QByteArray operator+(const QByteArray &a1, char a2)
3654 \relates QByteArray
3655
3656 \overload
3657
3658 Returns a byte array that is the result of concatenating byte
3659 array \a a1 and character \a a2.
3660*/
3661
3662/*! \fn const QByteArray operator+(const char *a1, const QByteArray &a2)
3663 \relates QByteArray
3664
3665 \overload
3666
3667 Returns a byte array that is the result of concatenating string
3668 \a a1 and byte array \a a2.
3669*/
3670
3671/*! \fn const QByteArray operator+(char a1, const QByteArray &a2)
3672 \relates QByteArray
3673
3674 \overload
3675
3676 Returns a byte array that is the result of concatenating character
3677 \a a1 and byte array \a a2.
3678*/
3679
3680/*!
3681 \fn QByteArray QByteArray::simplified() const
3682
3683 Returns a byte array that has whitespace removed from the start
3684 and the end, and which has each sequence of internal whitespace
3685 replaced with a single space.
3686
3687 Whitespace means any character for which the standard C++
3688 \c isspace() function returns \c true in the C locale. This includes the ASCII
3689 isspace() function returns \c true in the C locale. This includes the ASCII
3690 characters '\\t', '\\n', '\\v', '\\f', '\\r', and ' '.
3691
3692 Example:
3693 \snippet code/src_corelib_tools_qbytearray.cpp 32
3694
3695 \sa trimmed()
3696*/
3697QByteArray QByteArray::simplified_helper(const QByteArray &a)
3698{
3699 return QStringAlgorithms<const QByteArray>::simplified_helper(str: a);
3700}
3701
3702QByteArray QByteArray::simplified_helper(QByteArray &a)
3703{
3704 return QStringAlgorithms<QByteArray>::simplified_helper(str&: a);
3705}
3706
3707/*!
3708 \fn QByteArray QByteArray::trimmed() const
3709
3710 Returns a byte array that has whitespace removed from the start
3711 and the end.
3712
3713 Whitespace means any character for which the standard C++
3714 \c isspace() function returns \c true in the C locale. This includes the ASCII
3715 characters '\\t', '\\n', '\\v', '\\f', '\\r', and ' '.
3716
3717 Example:
3718 \snippet code/src_corelib_tools_qbytearray.cpp 33
3719
3720 Unlike simplified(), \l {QByteArray::trimmed()}{trimmed()} leaves internal whitespace alone.
3721
3722 \sa simplified()
3723*/
3724QByteArray QByteArray::trimmed_helper(const QByteArray &a)
3725{
3726 return QStringAlgorithms<const QByteArray>::trimmed_helper(str: a);
3727}
3728
3729QByteArray QByteArray::trimmed_helper(QByteArray &a)
3730{
3731 return QStringAlgorithms<QByteArray>::trimmed_helper(str&: a);
3732}
3733
3734
3735/*!
3736 Returns a byte array of size \a width that contains this byte
3737 array padded by the \a fill character.
3738
3739 If \a truncate is false and the size() of the byte array is more
3740 than \a width, then the returned byte array is a copy of this byte
3741 array.
3742
3743 If \a truncate is true and the size() of the byte array is more
3744 than \a width, then any bytes in a copy of the byte array
3745 after position \a width are removed, and the copy is returned.
3746
3747 Example:
3748 \snippet code/src_corelib_tools_qbytearray.cpp 34
3749
3750 \sa rightJustified()
3751*/
3752
3753QByteArray QByteArray::leftJustified(int width, char fill, bool truncate) const
3754{
3755 QByteArray result;
3756 int len = d->size;
3757 int padlen = width - len;
3758 if (padlen > 0) {
3759 result.resize(size: len+padlen);
3760 if (len)
3761 memcpy(dest: result.d->data(), src: d->data(), n: len);
3762 memset(s: result.d->data()+len, c: fill, n: padlen);
3763 } else {
3764 if (truncate)
3765 result = left(len: width);
3766 else
3767 result = *this;
3768 }
3769 return result;
3770}
3771
3772/*!
3773 Returns a byte array of size \a width that contains the \a fill
3774 character followed by this byte array.
3775
3776 If \a truncate is false and the size of the byte array is more
3777 than \a width, then the returned byte array is a copy of this byte
3778 array.
3779
3780 If \a truncate is true and the size of the byte array is more
3781 than \a width, then the resulting byte array is truncated at
3782 position \a width.
3783
3784 Example:
3785 \snippet code/src_corelib_tools_qbytearray.cpp 35
3786
3787 \sa leftJustified()
3788*/
3789
3790QByteArray QByteArray::rightJustified(int width, char fill, bool truncate) const
3791{
3792 QByteArray result;
3793 int len = d->size;
3794 int padlen = width - len;
3795 if (padlen > 0) {
3796 result.resize(size: len+padlen);
3797 if (len)
3798 memcpy(dest: result.d->data()+padlen, src: data(), n: len);
3799 memset(s: result.d->data(), c: fill, n: padlen);
3800 } else {
3801 if (truncate)
3802 result = left(len: width);
3803 else
3804 result = *this;
3805 }
3806 return result;
3807}
3808
3809bool QByteArray::isNull() const { return d == QArrayData::sharedNull(); }
3810
3811static qlonglong toIntegral_helper(const char *data, bool *ok, int base, qlonglong)
3812{
3813 return QLocaleData::bytearrayToLongLong(num: data, base, ok);
3814}
3815
3816static qulonglong toIntegral_helper(const char *data, bool *ok, int base, qulonglong)
3817{
3818 return QLocaleData::bytearrayToUnsLongLong(num: data, base, ok);
3819}
3820
3821template <typename T> static inline
3822T toIntegral_helper(const char *data, bool *ok, int base)
3823{
3824 using Int64 = typename std::conditional<std::is_unsigned<T>::value, qulonglong, qlonglong>::type;
3825
3826#if defined(QT_CHECK_RANGE)
3827 if (base != 0 && (base < 2 || base > 36)) {
3828 qWarning("QByteArray::toIntegral: Invalid base %d", base);
3829 base = 10;
3830 }
3831#endif
3832
3833 // we select the right overload by the last, unused parameter
3834 Int64 val = toIntegral_helper(data, ok, base, Int64());
3835 if (T(val) != val) {
3836 if (ok)
3837 *ok = false;
3838 val = 0;
3839 }
3840 return T(val);
3841}
3842
3843/*!
3844 Returns the byte array converted to a \c {long long} using base \a
3845 base, which is 10 by default and must be between 2 and 36, or 0.
3846
3847 If \a base is 0, the base is determined automatically using the
3848 following rules: If the byte array begins with "0x", it is assumed to
3849 be hexadecimal; if it begins with "0", it is assumed to be octal;
3850 otherwise it is assumed to be decimal.
3851
3852 Returns 0 if the conversion fails.
3853
3854 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3855 to \c false, and success by setting *\a{ok} to \c true.
3856
3857 \note The conversion of the number is performed in the default C locale,
3858 irrespective of the user's locale.
3859
3860 \sa number()
3861*/
3862
3863qlonglong QByteArray::toLongLong(bool *ok, int base) const
3864{
3865 return toIntegral_helper<qlonglong>(data: nulTerminated().constData(), ok, base);
3866}
3867
3868/*!
3869 Returns the byte array converted to an \c {unsigned long long}
3870 using base \a base, which is 10 by default and must be between 2
3871 and 36, or 0.
3872
3873 If \a base is 0, the base is determined automatically using the
3874 following rules: If the byte array begins with "0x", it is assumed to
3875 be hexadecimal; if it begins with "0", it is assumed to be octal;
3876 otherwise it is assumed to be decimal.
3877
3878 Returns 0 if the conversion fails.
3879
3880 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3881 to \c false, and success by setting *\a{ok} to \c true.
3882
3883 \note The conversion of the number is performed in the default C locale,
3884 irrespective of the user's locale.
3885
3886 \sa number()
3887*/
3888
3889qulonglong QByteArray::toULongLong(bool *ok, int base) const
3890{
3891 return toIntegral_helper<qulonglong>(data: nulTerminated().constData(), ok, base);
3892}
3893
3894/*!
3895 Returns the byte array converted to an \c int using base \a
3896 base, which is 10 by default and must be between 2 and 36, or 0.
3897
3898 If \a base is 0, the base is determined automatically using the
3899 following rules: If the byte array begins with "0x", it is assumed to
3900 be hexadecimal; if it begins with "0", it is assumed to be octal;
3901 otherwise it is assumed to be decimal.
3902
3903 Returns 0 if the conversion fails.
3904
3905 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3906 to \c false, and success by setting *\a{ok} to \c true.
3907
3908 \snippet code/src_corelib_tools_qbytearray.cpp 36
3909
3910 \note The conversion of the number is performed in the default C locale,
3911 irrespective of the user's locale.
3912
3913 \sa number()
3914*/
3915
3916int QByteArray::toInt(bool *ok, int base) const
3917{
3918 return toIntegral_helper<int>(data: nulTerminated().constData(), ok, base);
3919}
3920
3921/*!
3922 Returns the byte array converted to an \c {unsigned int} using base \a
3923 base, which is 10 by default and must be between 2 and 36, or 0.
3924
3925 If \a base is 0, the base is determined automatically using the
3926 following rules: If the byte array begins with "0x", it is assumed to
3927 be hexadecimal; if it begins with "0", it is assumed to be octal;
3928 otherwise it is assumed to be decimal.
3929
3930 Returns 0 if the conversion fails.
3931
3932 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3933 to \c false, and success by setting *\a{ok} to \c true.
3934
3935 \note The conversion of the number is performed in the default C locale,
3936 irrespective of the user's locale.
3937
3938 \sa number()
3939*/
3940
3941uint QByteArray::toUInt(bool *ok, int base) const
3942{
3943 return toIntegral_helper<uint>(data: nulTerminated().constData(), ok, base);
3944}
3945
3946/*!
3947 \since 4.1
3948
3949 Returns the byte array converted to a \c long int using base \a
3950 base, which is 10 by default and must be between 2 and 36, or 0.
3951
3952 If \a base is 0, the base is determined automatically using the
3953 following rules: If the byte array begins with "0x", it is assumed to
3954 be hexadecimal; if it begins with "0", it is assumed to be octal;
3955 otherwise it is assumed to be decimal.
3956
3957 Returns 0 if the conversion fails.
3958
3959 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3960 to \c false, and success by setting *\a{ok} to \c true.
3961
3962 \snippet code/src_corelib_tools_qbytearray.cpp 37
3963
3964 \note The conversion of the number is performed in the default C locale,
3965 irrespective of the user's locale.
3966
3967 \sa number()
3968*/
3969long QByteArray::toLong(bool *ok, int base) const
3970{
3971 return toIntegral_helper<long>(data: nulTerminated().constData(), ok, base);
3972}
3973
3974/*!
3975 \since 4.1
3976
3977 Returns the byte array converted to an \c {unsigned long int} using base \a
3978 base, which is 10 by default and must be between 2 and 36, or 0.
3979
3980 If \a base is 0, the base is determined automatically using the
3981 following rules: If the byte array begins with "0x", it is assumed to
3982 be hexadecimal; if it begins with "0", it is assumed to be octal;
3983 otherwise it is assumed to be decimal.
3984
3985 Returns 0 if the conversion fails.
3986
3987 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3988 to \c false, and success by setting *\a{ok} to \c true.
3989
3990 \note The conversion of the number is performed in the default C locale,
3991 irrespective of the user's locale.
3992
3993 \sa number()
3994*/
3995ulong QByteArray::toULong(bool *ok, int base) const
3996{
3997 return toIntegral_helper<ulong>(data: nulTerminated().constData(), ok, base);
3998}
3999
4000/*!
4001 Returns the byte array converted to a \c short using base \a
4002 base, which is 10 by default and must be between 2 and 36, or 0.
4003
4004 If \a base is 0, the base is determined automatically using the
4005 following rules: If the byte array begins with "0x", it is assumed to
4006 be hexadecimal; if it begins with "0", it is assumed to be octal;
4007 otherwise it is assumed to be decimal.
4008
4009 Returns 0 if the conversion fails.
4010
4011 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
4012 to \c false, and success by setting *\a{ok} to \c true.
4013
4014 \note The conversion of the number is performed in the default C locale,
4015 irrespective of the user's locale.
4016
4017 \sa number()
4018*/
4019
4020short QByteArray::toShort(bool *ok, int base) const
4021{
4022 return toIntegral_helper<short>(data: nulTerminated().constData(), ok, base);
4023}
4024
4025/*!
4026 Returns the byte array converted to an \c {unsigned short} using base \a
4027 base, which is 10 by default and must be between 2 and 36, or 0.
4028
4029 If \a base is 0, the base is determined automatically using the
4030 following rules: If the byte array begins with "0x", it is assumed to
4031 be hexadecimal; if it begins with "0", it is assumed to be octal;
4032 otherwise it is assumed to be decimal.
4033
4034 Returns 0 if the conversion fails.
4035
4036 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
4037 to \c false, and success by setting *\a{ok} to \c true.
4038
4039 \note The conversion of the number is performed in the default C locale,
4040 irrespective of the user's locale.
4041
4042 \sa number()
4043*/
4044
4045ushort QByteArray::toUShort(bool *ok, int base) const
4046{
4047 return toIntegral_helper<ushort>(data: nulTerminated().constData(), ok, base);
4048}
4049
4050
4051/*!
4052 Returns the byte array converted to a \c double value.
4053
4054 Returns an infinity if the conversion overflows or 0.0 if the
4055 conversion fails for other reasons (e.g. underflow).
4056
4057 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
4058 to \c false, and success by setting *\a{ok} to \c true.
4059
4060 \snippet code/src_corelib_tools_qbytearray.cpp 38
4061
4062 \warning The QByteArray content may only contain valid numerical characters
4063 which includes the plus/minus sign, the character e used in scientific
4064 notation, and the decimal point. Including the unit or additional characters
4065 leads to a conversion error.
4066
4067 \note The conversion of the number is performed in the default C locale,
4068 irrespective of the user's locale.
4069
4070 This function ignores leading and trailing whitespace.
4071
4072 \sa number()
4073*/
4074
4075double QByteArray::toDouble(bool *ok) const
4076{
4077 bool nonNullOk = false;
4078 int processed = 0;
4079 double d = qt_asciiToDouble(num: constData(), numLen: size(),
4080 ok&: nonNullOk, processed, strayCharMode: WhitespacesAllowed);
4081 if (ok)
4082 *ok = nonNullOk;
4083 return d;
4084}
4085
4086/*!
4087 Returns the byte array converted to a \c float value.
4088
4089 Returns an infinity if the conversion overflows or 0.0 if the
4090 conversion fails for other reasons (e.g. underflow).
4091
4092 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
4093 to \c false, and success by setting *\a{ok} to \c true.
4094
4095 \snippet code/src_corelib_tools_qbytearray.cpp 38float
4096
4097 \warning The QByteArray content may only contain valid numerical characters
4098 which includes the plus/minus sign, the character e used in scientific
4099 notation, and the decimal point. Including the unit or additional characters
4100 leads to a conversion error.
4101
4102 \note The conversion of the number is performed in the default C locale,
4103 irrespective of the user's locale.
4104
4105 This function ignores leading and trailing whitespace.
4106
4107 \sa number()
4108*/
4109
4110float QByteArray::toFloat(bool *ok) const
4111{
4112 return QLocaleData::convertDoubleToFloat(d: toDouble(ok), ok);
4113}
4114
4115/*!
4116 Returns a copy of the byte array, encoded as Base64.
4117
4118 \snippet code/src_corelib_tools_qbytearray.cpp 39
4119
4120 The algorithm used to encode Base64-encoded data is defined in \l{RFC 4648}.
4121
4122 \sa fromBase64()
4123*/
4124QByteArray QByteArray::toBase64() const
4125{
4126 return toBase64(options: Base64Encoding);
4127}
4128
4129/*!
4130 \since 5.2
4131 \overload
4132
4133 Returns a copy of the byte array, encoded using the options \a options.
4134
4135 \snippet code/src_corelib_tools_qbytearray.cpp 39bis
4136
4137 The algorithm used to encode Base64-encoded data is defined in \l{RFC 4648}.
4138
4139 \sa fromBase64()
4140*/
4141QByteArray QByteArray::toBase64(Base64Options options) const
4142{
4143 const char alphabet_base64[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
4144 "ghijklmn" "opqrstuv" "wxyz0123" "456789+/";
4145 const char alphabet_base64url[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
4146 "ghijklmn" "opqrstuv" "wxyz0123" "456789-_";
4147 const char *const alphabet = options & Base64UrlEncoding ? alphabet_base64url : alphabet_base64;
4148 const char padchar = '=';
4149 int padlen = 0;
4150
4151 QByteArray tmp((d->size + 2) / 3 * 4, Qt::Uninitialized);
4152
4153 int i = 0;
4154 char *out = tmp.data();
4155 while (i < d->size) {
4156 // encode 3 bytes at a time
4157 int chunk = 0;
4158 chunk |= int(uchar(d->data()[i++])) << 16;
4159 if (i == d->size) {
4160 padlen = 2;
4161 } else {
4162 chunk |= int(uchar(d->data()[i++])) << 8;
4163 if (i == d->size)
4164 padlen = 1;
4165 else
4166 chunk |= int(uchar(data()[i++]));
4167 }
4168
4169 int j = (chunk & 0x00fc0000) >> 18;
4170 int k = (chunk & 0x0003f000) >> 12;
4171 int l = (chunk & 0x00000fc0) >> 6;
4172 int m = (chunk & 0x0000003f);
4173 *out++ = alphabet[j];
4174 *out++ = alphabet[k];
4175
4176 if (padlen > 1) {
4177 if ((options & OmitTrailingEquals) == 0)
4178 *out++ = padchar;
4179 } else {
4180 *out++ = alphabet[l];
4181 }
4182 if (padlen > 0) {
4183 if ((options & OmitTrailingEquals) == 0)
4184 *out++ = padchar;
4185 } else {
4186 *out++ = alphabet[m];
4187 }
4188 }
4189 Q_ASSERT((options & OmitTrailingEquals) || (out == tmp.size() + tmp.data()));
4190 if (options & OmitTrailingEquals)
4191 tmp.truncate(pos: out - tmp.data());
4192 return tmp;
4193}
4194
4195/*!
4196 \fn QByteArray &QByteArray::setNum(int n, int base)
4197
4198 Sets the byte array to the printed value of \a n in base \a base (10
4199 by default) and returns a reference to the byte array. The \a base can
4200 be any value between 2 and 36. For bases other than 10, n is treated
4201 as an unsigned integer.
4202
4203 Example:
4204 \snippet code/src_corelib_tools_qbytearray.cpp 40
4205
4206 \note The format of the number is not localized; the default C locale
4207 is used irrespective of the user's locale.
4208
4209 \sa number(), toInt()
4210*/
4211
4212/*!
4213 \fn QByteArray &QByteArray::setNum(uint n, int base)
4214 \overload
4215
4216 \sa toUInt()
4217*/
4218
4219/*!
4220 \fn QByteArray &QByteArray::setNum(short n, int base)
4221 \overload
4222
4223 \sa toShort()
4224*/
4225
4226/*!
4227 \fn QByteArray &QByteArray::setNum(ushort n, int base)
4228 \overload
4229
4230 \sa toUShort()
4231*/
4232
4233static char *qulltoa2(char *p, qulonglong n, int base)
4234{
4235#if defined(QT_CHECK_RANGE)
4236 if (base < 2 || base > 36) {
4237 qWarning("QByteArray::setNum: Invalid base %d", base);
4238 base = 10;
4239 }
4240#endif
4241 const char b = 'a' - 10;
4242 do {
4243 const int c = n % base;
4244 n /= base;
4245 *--p = c + (c < 10 ? '0' : b);
4246 } while (n);
4247
4248 return p;
4249}
4250
4251/*!
4252 \overload
4253
4254 \sa toLongLong()
4255*/
4256QByteArray &QByteArray::setNum(qlonglong n, int base)
4257{
4258 const int buffsize = 66; // big enough for MAX_ULLONG in base 2
4259 char buff[buffsize];
4260 char *p;
4261
4262 if (n < 0 && base == 10) {
4263 p = qulltoa2(p: buff + buffsize, n: qulonglong(-(1 + n)) + 1, base);
4264 *--p = '-';
4265 } else {
4266 p = qulltoa2(p: buff + buffsize, n: qulonglong(n), base);
4267 }
4268
4269 clear();
4270 append(str: p, len: buffsize - (p - buff));
4271 return *this;
4272}
4273
4274/*!
4275 \overload
4276
4277 \sa toULongLong()
4278*/
4279
4280QByteArray &QByteArray::setNum(qulonglong n, int base)
4281{
4282 const int buffsize = 66; // big enough for MAX_ULLONG in base 2
4283 char buff[buffsize];
4284 char *p = qulltoa2(p: buff + buffsize, n, base);
4285
4286 clear();
4287 append(str: p, len: buffsize - (p - buff));
4288 return *this;
4289}
4290
4291/*!
4292 \overload
4293
4294 Sets the byte array to the printed value of \a n, formatted in format
4295 \a f with precision \a prec, and returns a reference to the
4296 byte array.
4297
4298 The format \a f can be any of the following:
4299
4300 \table
4301 \header \li Format \li Meaning
4302 \row \li \c e \li format as [-]9.9e[+|-]999
4303 \row \li \c E \li format as [-]9.9E[+|-]999
4304 \row \li \c f \li format as [-]9.9
4305 \row \li \c g \li use \c e or \c f format, whichever is the most concise
4306 \row \li \c G \li use \c E or \c f format, whichever is the most concise
4307 \endtable
4308
4309 With 'e', 'E', and 'f', \a prec is the number of digits after the
4310 decimal point. With 'g' and 'G', \a prec is the maximum number of
4311 significant digits (trailing zeroes are omitted).
4312
4313 \note The format of the number is not localized; the default C locale
4314 is used irrespective of the user's locale.
4315
4316 \sa toDouble()
4317*/
4318
4319QByteArray &QByteArray::setNum(double n, char f, int prec)
4320{
4321 QLocaleData::DoubleForm form = QLocaleData::DFDecimal;
4322 uint flags = QLocaleData::ZeroPadExponent;
4323
4324 char lower = latin1_lowercased[uchar(f)];
4325 if (f != lower)
4326 flags |= QLocaleData::CapitalEorX;
4327 f = lower;
4328
4329 switch (f) {
4330 case 'f':
4331 form = QLocaleData::DFDecimal;
4332 break;
4333 case 'e':
4334 form = QLocaleData::DFExponent;
4335 break;
4336 case 'g':
4337 form = QLocaleData::DFSignificantDigits;
4338 break;
4339 default:
4340#if defined(QT_CHECK_RANGE)
4341 qWarning("QByteArray::setNum: Invalid format char '%c'", f);
4342#endif
4343 break;
4344 }
4345
4346 *this = QLocaleData::c()->doubleToString(d: n, precision: prec, form, width: -1, flags).toLatin1();
4347 return *this;
4348}
4349
4350/*!
4351 \fn QByteArray &QByteArray::setNum(float n, char f, int prec)
4352 \overload
4353
4354 Sets the byte array to the printed value of \a n, formatted in format
4355 \a f with precision \a prec, and returns a reference to the
4356 byte array.
4357
4358 \note The format of the number is not localized; the default C locale
4359 is used irrespective of the user's locale.
4360
4361 \sa toFloat()
4362*/
4363
4364/*!
4365 Returns a byte array containing the string equivalent of the
4366 number \a n to base \a base (10 by default). The \a base can be
4367 any value between 2 and 36.
4368
4369 Example:
4370 \snippet code/src_corelib_tools_qbytearray.cpp 41
4371
4372 \note The format of the number is not localized; the default C locale
4373 is used irrespective of the user's locale.
4374
4375 \sa setNum(), toInt()
4376*/
4377QByteArray QByteArray::number(int n, int base)
4378{
4379 QByteArray s;
4380 s.setNum(n, base);
4381 return s;
4382}
4383
4384/*!
4385 \overload
4386
4387 \sa toUInt()
4388*/
4389QByteArray QByteArray::number(uint n, int base)
4390{
4391 QByteArray s;
4392 s.setNum(n, base);
4393 return s;
4394}
4395
4396/*!
4397 \overload
4398
4399 \sa toLongLong()
4400*/
4401QByteArray QByteArray::number(qlonglong n, int base)
4402{
4403 QByteArray s;
4404 s.setNum(n, base);
4405 return s;
4406}
4407
4408/*!
4409 \overload
4410
4411 \sa toULongLong()
4412*/
4413QByteArray QByteArray::number(qulonglong n, int base)
4414{
4415 QByteArray s;
4416 s.setNum(n, base);
4417 return s;
4418}
4419
4420/*!
4421 \overload
4422
4423 Returns a byte array that contains the printed value of \a n,
4424 formatted in format \a f with precision \a prec.
4425
4426 Argument \a n is formatted according to the \a f format specified,
4427 which is \c g by default, and can be any of the following:
4428
4429 \table
4430 \header \li Format \li Meaning
4431 \row \li \c e \li format as [-]9.9e[+|-]999
4432 \row \li \c E \li format as [-]9.9E[+|-]999
4433 \row \li \c f \li format as [-]9.9
4434 \row \li \c g \li use \c e or \c f format, whichever is the most concise
4435 \row \li \c G \li use \c E or \c f format, whichever is the most concise
4436 \endtable
4437
4438 With 'e', 'E', and 'f', \a prec is the number of digits after the
4439 decimal point. With 'g' and 'G', \a prec is the maximum number of
4440 significant digits (trailing zeroes are omitted).
4441
4442 \snippet code/src_corelib_tools_qbytearray.cpp 42
4443
4444 \note The format of the number is not localized; the default C locale
4445 is used irrespective of the user's locale.
4446
4447 \sa toDouble()
4448*/
4449QByteArray QByteArray::number(double n, char f, int prec)
4450{
4451 QByteArray s;
4452 s.setNum(n, f, prec);
4453 return s;
4454}
4455
4456/*!
4457 Constructs a QByteArray that uses the first \a size bytes of the
4458 \a data array. The bytes are \e not copied. The QByteArray will
4459 contain the \a data pointer. The caller guarantees that \a data
4460 will not be deleted or modified as long as this QByteArray and any
4461 copies of it exist that have not been modified. In other words,
4462 because QByteArray is an \l{implicitly shared} class and the
4463 instance returned by this function contains the \a data pointer,
4464 the caller must not delete \a data or modify it directly as long
4465 as the returned QByteArray and any copies exist. However,
4466 QByteArray does not take ownership of \a data, so the QByteArray
4467 destructor will never delete the raw \a data, even when the
4468 last QByteArray referring to \a data is destroyed.
4469
4470 A subsequent attempt to modify the contents of the returned
4471 QByteArray or any copy made from it will cause it to create a deep
4472 copy of the \a data array before doing the modification. This
4473 ensures that the raw \a data array itself will never be modified
4474 by QByteArray.
4475
4476 Here is an example of how to read data using a QDataStream on raw
4477 data in memory without copying the raw data into a QByteArray:
4478
4479 \snippet code/src_corelib_tools_qbytearray.cpp 43
4480
4481 \warning A byte array created with fromRawData() is \e not
4482 '\\0'-terminated, unless the raw data contains a 0 character at
4483 position \a size. While that does not matter for QDataStream or
4484 functions like indexOf(), passing the byte array to a function
4485 accepting a \c{const char *} expected to be '\\0'-terminated will
4486 fail.
4487
4488 \sa setRawData(), data(), constData()
4489*/
4490
4491QByteArray QByteArray::fromRawData(const char *data, int size)
4492{
4493 Data *x;
4494 if (!data) {
4495 x = Data::sharedNull();
4496 } else if (!size) {
4497 x = Data::allocate(capacity: 0);
4498 } else {
4499 x = Data::fromRawData(data, n: size);
4500 Q_CHECK_PTR(x);
4501 }
4502 QByteArrayDataPtr dataPtr = { .ptr: x };
4503 return QByteArray(dataPtr);
4504}
4505
4506/*!
4507 \since 4.7
4508
4509 Resets the QByteArray to use the first \a size bytes of the
4510 \a data array. The bytes are \e not copied. The QByteArray will
4511 contain the \a data pointer. The caller guarantees that \a data
4512 will not be deleted or modified as long as this QByteArray and any
4513 copies of it exist that have not been modified.
4514
4515 This function can be used instead of fromRawData() to re-use
4516 existing QByteArray objects to save memory re-allocations.
4517
4518 \sa fromRawData(), data(), constData()
4519*/
4520QByteArray &QByteArray::setRawData(const char *data, uint size)
4521{
4522 if (d->ref.isShared() || d->alloc) {
4523 *this = fromRawData(data, size);
4524 } else {
4525 if (data) {
4526 d->size = size;
4527 d->offset = data - reinterpret_cast<char *>(d);
4528 } else {
4529 d->offset = sizeof(QByteArrayData);
4530 d->size = 0;
4531 }
4532 }
4533 return *this;
4534}
4535
4536namespace {
4537struct fromBase64_helper_result {
4538 qsizetype decodedLength;
4539 QByteArray::Base64DecodingStatus status;
4540};
4541
4542fromBase64_helper_result fromBase64_helper(const char *input, qsizetype inputSize,
4543 char *output /* may alias input */,
4544 QByteArray::Base64Options options)
4545{
4546 fromBase64_helper_result result{ .decodedLength: 0, .status: QByteArray::Base64DecodingStatus::Ok };
4547
4548 unsigned int buf = 0;
4549 int nbits = 0;
4550
4551 qsizetype offset = 0;
4552 for (qsizetype i = 0; i < inputSize; ++i) {
4553 int ch = input[i];
4554 int d;
4555
4556 if (ch >= 'A' && ch <= 'Z') {
4557 d = ch - 'A';
4558 } else if (ch >= 'a' && ch <= 'z') {
4559 d = ch - 'a' + 26;
4560 } else if (ch >= '0' && ch <= '9') {
4561 d = ch - '0' + 52;
4562 } else if (ch == '+' && (options & QByteArray::Base64UrlEncoding) == 0) {
4563 d = 62;
4564 } else if (ch == '-' && (options & QByteArray::Base64UrlEncoding) != 0) {
4565 d = 62;
4566 } else if (ch == '/' && (options & QByteArray::Base64UrlEncoding) == 0) {
4567 d = 63;
4568 } else if (ch == '_' && (options & QByteArray::Base64UrlEncoding) != 0) {
4569 d = 63;
4570 } else {
4571 if (options & QByteArray::AbortOnBase64DecodingErrors) {
4572 if (ch == '=') {
4573 // can have 1 or 2 '=' signs, in both cases padding base64Size to
4574 // a multiple of 4. Any other case is illegal.
4575 if ((inputSize % 4) != 0) {
4576 result.status = QByteArray::Base64DecodingStatus::IllegalInputLength;
4577 return result;
4578 } else if ((i == inputSize - 1) ||
4579 (i == inputSize - 2 && input[++i] == '=')) {
4580 d = -1; // ... and exit the loop, normally
4581 } else {
4582 result.status = QByteArray::Base64DecodingStatus::IllegalPadding;
4583 return result;
4584 }
4585 } else {
4586 result.status = QByteArray::Base64DecodingStatus::IllegalCharacter;
4587 return result;
4588 }
4589 } else {
4590 d = -1;
4591 }
4592 }
4593
4594 if (d != -1) {
4595 buf = (buf << 6) | d;
4596 nbits += 6;
4597 if (nbits >= 8) {
4598 nbits -= 8;
4599 Q_ASSERT(offset < i);
4600 output[offset++] = buf >> nbits;
4601 buf &= (1 << nbits) - 1;
4602 }
4603 }
4604 }
4605
4606 result.decodedLength = offset;
4607 return result;
4608}
4609} // anonymous namespace
4610
4611/*!
4612 \fn QByteArray::FromBase64Result QByteArray::fromBase64Encoding(QByteArray &&base64, Base64Options options)
4613 \fn QByteArray::FromBase64Result QByteArray::fromBase64Encoding(const QByteArray &base64, Base64Options options)
4614 \since 5.15
4615 \overload
4616
4617 Decodes the Base64 array \a base64, using the options
4618 defined by \a options. If \a options contains \c{IgnoreBase64DecodingErrors}
4619 (the default), the input is not checked for validity; invalid
4620 characters in the input are skipped, enabling the decoding process to
4621 continue with subsequent characters. If \a options contains
4622 \c{AbortOnBase64DecodingErrors}, then decoding will stop at the first
4623 invalid character.
4624
4625 For example:
4626
4627 \snippet code/src_corelib_tools_qbytearray.cpp 44ter
4628
4629 The algorithm used to decode Base64-encoded data is defined in \l{RFC 4648}.
4630
4631 Returns a QByteArrayFromBase64Result object, containing the decoded
4632 data and a flag telling whether decoding was successful. If the
4633 \c{AbortOnBase64DecodingErrors} option was passed and the input
4634 data was invalid, it is unspecified what the decoded data contains.
4635
4636 \sa toBase64()
4637*/
4638QByteArray::FromBase64Result QByteArray::fromBase64Encoding(QByteArray &&base64, Base64Options options)
4639{
4640 // try to avoid a detach when calling data(), as it would over-allocate
4641 // (we need less space when decoding than the one required by the full copy)
4642 if (base64.isDetached()) {
4643 const auto base64result = fromBase64_helper(input: base64.data(),
4644 inputSize: base64.size(),
4645 output: base64.data(), // in-place
4646 options);
4647 base64.truncate(pos: int(base64result.decodedLength));
4648 return { .decoded: std::move(base64), .decodingStatus: base64result.status };
4649 }
4650
4651 return fromBase64Encoding(base64, options);
4652}
4653
4654
4655QByteArray::FromBase64Result QByteArray::fromBase64Encoding(const QByteArray &base64, Base64Options options)
4656{
4657 const auto base64Size = base64.size();
4658 QByteArray result((base64Size * 3) / 4, Qt::Uninitialized);
4659 const auto base64result = fromBase64_helper(input: base64.data(),
4660 inputSize: base64Size,
4661 output: const_cast<char *>(result.constData()),
4662 options);
4663 result.truncate(pos: int(base64result.decodedLength));
4664 return { .decoded: std::move(result), .decodingStatus: base64result.status };
4665}
4666
4667/*!
4668 \overload
4669
4670 Returns a decoded copy of the Base64 array \a base64. Input is not checked
4671 for validity; invalid characters in the input are skipped, enabling the
4672 decoding process to continue with subsequent characters.
4673
4674 For example:
4675
4676 \snippet code/src_corelib_tools_qbytearray.cpp 44
4677
4678 The algorithm used to decode Base64-encoded data is defined in \l{RFC 4648}.
4679
4680 \note The fromBase64Encoding() function is recommended in new code.
4681
4682 \sa toBase64(), fromBase64Encoding()
4683*/
4684QByteArray QByteArray::fromBase64(const QByteArray &base64)
4685{
4686 if (auto result = fromBase64Encoding(base64, options: Base64Encoding))
4687 return std::move(result.decoded);
4688 return QByteArray();
4689}
4690
4691/*!
4692 \since 5.2
4693 \overload
4694
4695 Returns a decoded copy of the Base64 array \a base64, using the options
4696 defined by \a options. If \a options contains \c{IgnoreBase64DecodingErrors}
4697 (the default), the input is not checked for validity; invalid
4698 characters in the input are skipped, enabling the decoding process to
4699 continue with subsequent characters. If \a options contains
4700 \c{AbortOnBase64DecodingErrors}, then decoding will stop at the first
4701 invalid character.
4702
4703 For example:
4704
4705 \snippet code/src_corelib_tools_qbytearray.cpp 44bis
4706
4707 The algorithm used to decode Base64-encoded data is defined in \l{RFC 4648}.
4708
4709 Returns the decoded data, or, if the \c{AbortOnBase64DecodingErrors}
4710 option was passed and the input data was invalid, an empty byte array.
4711
4712 \note The fromBase64Encoding() function is recommended in new code.
4713
4714 \sa toBase64(), fromBase64Encoding()
4715*/
4716QByteArray QByteArray::fromBase64(const QByteArray &base64, Base64Options options)
4717{
4718 if (auto result = fromBase64Encoding(base64, options))
4719 return std::move(result.decoded);
4720 return QByteArray();
4721}
4722
4723/*!
4724 Returns a decoded copy of the hex encoded array \a hexEncoded. Input is not checked
4725 for validity; invalid characters in the input are skipped, enabling the
4726 decoding process to continue with subsequent characters.
4727
4728 For example:
4729
4730 \snippet code/src_corelib_tools_qbytearray.cpp 45
4731
4732 \sa toHex()
4733*/
4734QByteArray QByteArray::fromHex(const QByteArray &hexEncoded)
4735{
4736 QByteArray res((hexEncoded.size() + 1)/ 2, Qt::Uninitialized);
4737 uchar *result = (uchar *)res.data() + res.size();
4738
4739 bool odd_digit = true;
4740 for (int i = hexEncoded.size() - 1; i >= 0; --i) {
4741 uchar ch = uchar(hexEncoded.at(i));
4742 int tmp = QtMiscUtils::fromHex(c: ch);
4743 if (tmp == -1)
4744 continue;
4745 if (odd_digit) {
4746 --result;
4747 *result = tmp;
4748 odd_digit = false;
4749 } else {
4750 *result |= tmp << 4;
4751 odd_digit = true;
4752 }
4753 }
4754
4755 res.remove(pos: 0, len: result - (const uchar *)res.constData());
4756 return res;
4757}
4758
4759/*!
4760 Returns a hex encoded copy of the byte array. The hex encoding uses the numbers 0-9 and
4761 the letters a-f.
4762
4763 \sa fromHex()
4764*/
4765QByteArray QByteArray::toHex() const
4766{
4767 return toHex(separator: '\0');
4768}
4769
4770/*! \overload
4771 \since 5.9
4772
4773 Returns a hex encoded copy of the byte array. The hex encoding uses the numbers 0-9 and
4774 the letters a-f.
4775
4776 If \a separator is not '\0', the separator character is inserted between the hex bytes.
4777
4778 Example:
4779 \snippet code/src_corelib_tools_qbytearray.cpp 50
4780
4781 \sa fromHex()
4782*/
4783QByteArray QByteArray::toHex(char separator) const
4784{
4785 if (!d->size)
4786 return QByteArray();
4787
4788 const int length = separator ? (d->size * 3 - 1) : (d->size * 2);
4789 QByteArray hex(length, Qt::Uninitialized);
4790 char *hexData = hex.data();
4791 const uchar *data = (const uchar *)d->data();
4792 for (int i = 0, o = 0; i < d->size; ++i) {
4793 hexData[o++] = QtMiscUtils::toHexLower(value: data[i] >> 4);
4794 hexData[o++] = QtMiscUtils::toHexLower(value: data[i] & 0xf);
4795
4796 if ((separator) && (o < length))
4797 hexData[o++] = separator;
4798 }
4799 return hex;
4800}
4801
4802static void q_fromPercentEncoding(QByteArray *ba, char percent)
4803{
4804 if (ba->isEmpty())
4805 return;
4806
4807 char *data = ba->data();
4808 const char *inputPtr = data;
4809
4810 int i = 0;
4811 int len = ba->count();
4812 int outlen = 0;
4813 int a, b;
4814 char c;
4815 while (i < len) {
4816 c = inputPtr[i];
4817 if (c == percent && i + 2 < len) {
4818 a = inputPtr[++i];
4819 b = inputPtr[++i];
4820
4821 if (a >= '0' && a <= '9') a -= '0';
4822 else if (a >= 'a' && a <= 'f') a = a - 'a' + 10;
4823 else if (a >= 'A' && a <= 'F') a = a - 'A' + 10;
4824
4825 if (b >= '0' && b <= '9') b -= '0';
4826 else if (b >= 'a' && b <= 'f') b = b - 'a' + 10;
4827 else if (b >= 'A' && b <= 'F') b = b - 'A' + 10;
4828
4829 *data++ = (char)((a << 4) | b);
4830 } else {
4831 *data++ = c;
4832 }
4833
4834 ++i;
4835 ++outlen;
4836 }
4837
4838 if (outlen != len)
4839 ba->truncate(pos: outlen);
4840}
4841
4842void q_fromPercentEncoding(QByteArray *ba)
4843{
4844 q_fromPercentEncoding(ba, percent: '%');
4845}
4846
4847/*!
4848 \since 4.4
4849
4850 Returns a decoded copy of the URI/URL-style percent-encoded \a input.
4851 The \a percent parameter allows you to replace the '%' character for
4852 another (for instance, '_' or '=').
4853
4854 For example:
4855 \snippet code/src_corelib_tools_qbytearray.cpp 51
4856
4857 \note Given invalid input (such as a string containing the sequence "%G5",
4858 which is not a valid hexadecimal number) the output will be invalid as
4859 well. As an example: the sequence "%G5" could be decoded to 'W'.
4860
4861 \sa toPercentEncoding(), QUrl::fromPercentEncoding()
4862*/
4863QByteArray QByteArray::fromPercentEncoding(const QByteArray &input, char percent)
4864{
4865 if (input.isNull())
4866 return QByteArray(); // preserve null
4867 if (input.isEmpty())
4868 return QByteArray(input.data(), 0);
4869
4870 QByteArray tmp = input;
4871 q_fromPercentEncoding(ba: &tmp, percent);
4872 return tmp;
4873}
4874
4875/*! \fn QByteArray QByteArray::fromStdString(const std::string &str)
4876 \since 5.4
4877
4878 Returns a copy of the \a str string as a QByteArray.
4879
4880 \sa toStdString(), QString::fromStdString()
4881*/
4882
4883/*!
4884 \fn std::string QByteArray::toStdString() const
4885 \since 5.4
4886
4887 Returns a std::string object with the data contained in this
4888 QByteArray.
4889
4890 This operator is mostly useful to pass a QByteArray to a function
4891 that accepts a std::string object.
4892
4893 \sa fromStdString(), QString::toStdString()
4894*/
4895
4896static inline bool q_strchr(const char str[], char chr)
4897{
4898 if (!str) return false;
4899
4900 const char *ptr = str;
4901 char c;
4902 while ((c = *ptr++))
4903 if (c == chr)
4904 return true;
4905 return false;
4906}
4907
4908static void q_toPercentEncoding(QByteArray *ba, const char *dontEncode, const char *alsoEncode, char percent)
4909{
4910 if (ba->isEmpty())
4911 return;
4912
4913 QByteArray input = *ba;
4914 int len = input.count();
4915 const char *inputData = input.constData();
4916 char *output = nullptr;
4917 int length = 0;
4918
4919 for (int i = 0; i < len; ++i) {
4920 unsigned char c = *inputData++;
4921 if (((c >= 0x61 && c <= 0x7A) // ALPHA
4922 || (c >= 0x41 && c <= 0x5A) // ALPHA
4923 || (c >= 0x30 && c <= 0x39) // DIGIT
4924 || c == 0x2D // -
4925 || c == 0x2E // .
4926 || c == 0x5F // _
4927 || c == 0x7E // ~
4928 || q_strchr(str: dontEncode, chr: c))
4929 && !q_strchr(str: alsoEncode, chr: c)) {
4930 if (output)
4931 output[length] = c;
4932 ++length;
4933 } else {
4934 if (!output) {
4935 // detach now
4936 ba->resize(size: len*3); // worst case
4937 output = ba->data();
4938 }
4939 output[length++] = percent;
4940 output[length++] = QtMiscUtils::toHexUpper(value: (c & 0xf0) >> 4);
4941 output[length++] = QtMiscUtils::toHexUpper(value: c & 0xf);
4942 }
4943 }
4944 if (output)
4945 ba->truncate(pos: length);
4946}
4947
4948void q_toPercentEncoding(QByteArray *ba, const char *exclude, const char *include)
4949{
4950 q_toPercentEncoding(ba, dontEncode: exclude, alsoEncode: include, percent: '%');
4951}
4952
4953void q_normalizePercentEncoding(QByteArray *ba, const char *exclude)
4954{
4955 q_fromPercentEncoding(ba, percent: '%');
4956 q_toPercentEncoding(ba, dontEncode: exclude, alsoEncode: nullptr, percent: '%');
4957}
4958
4959/*!
4960 \since 4.4
4961
4962 Returns a URI/URL-style percent-encoded copy of this byte array. The
4963 \a percent parameter allows you to override the default '%'
4964 character for another.
4965
4966 By default, this function will encode all characters that are not
4967 one of the following:
4968
4969 ALPHA ("a" to "z" and "A" to "Z") / DIGIT (0 to 9) / "-" / "." / "_" / "~"
4970
4971 To prevent characters from being encoded pass them to \a
4972 exclude. To force characters to be encoded pass them to \a
4973 include. The \a percent character is always encoded.
4974
4975 Example:
4976
4977 \snippet code/src_corelib_tools_qbytearray.cpp 52
4978
4979 The hex encoding uses the numbers 0-9 and the uppercase letters A-F.
4980
4981 \sa fromPercentEncoding(), QUrl::toPercentEncoding()
4982*/
4983QByteArray QByteArray::toPercentEncoding(const QByteArray &exclude, const QByteArray &include,
4984 char percent) const
4985{
4986 if (isNull())
4987 return QByteArray(); // preserve null
4988 if (isEmpty())
4989 return QByteArray(data(), 0);
4990
4991 QByteArray include2 = include;
4992 if (percent != '%') // the default
4993 if ((percent >= 0x61 && percent <= 0x7A) // ALPHA
4994 || (percent >= 0x41 && percent <= 0x5A) // ALPHA
4995 || (percent >= 0x30 && percent <= 0x39) // DIGIT
4996 || percent == 0x2D // -
4997 || percent == 0x2E // .
4998 || percent == 0x5F // _
4999 || percent == 0x7E) // ~
5000 include2 += percent;
5001
5002 QByteArray result = *this;
5003 q_toPercentEncoding(ba: &result, dontEncode: exclude.nulTerminated().constData(), alsoEncode: include2.nulTerminated().constData(), percent);
5004
5005 return result;
5006}
5007
5008/*! \typedef QByteArray::ConstIterator
5009 \internal
5010*/
5011
5012/*! \typedef QByteArray::Iterator
5013 \internal
5014*/
5015
5016/*! \typedef QByteArray::const_iterator
5017
5018 This typedef provides an STL-style const iterator for QByteArray.
5019
5020 \sa QByteArray::const_reverse_iterator, QByteArray::iterator
5021*/
5022
5023/*! \typedef QByteArray::iterator
5024
5025 This typedef provides an STL-style non-const iterator for QByteArray.
5026
5027 \sa QByteArray::reverse_iterator, QByteArray::const_iterator
5028*/
5029
5030/*! \typedef QByteArray::const_reverse_iterator
5031 \since 5.6
5032
5033 This typedef provides an STL-style const reverse iterator for QByteArray.
5034
5035 \sa QByteArray::reverse_iterator, QByteArray::const_iterator
5036*/
5037
5038/*! \typedef QByteArray::reverse_iterator
5039 \since 5.6
5040
5041 This typedef provides an STL-style non-const reverse iterator for QByteArray.
5042
5043 \sa QByteArray::const_reverse_iterator, QByteArray::iterator
5044*/
5045
5046/*! \typedef QByteArray::size_type
5047 \internal
5048*/
5049
5050/*! \typedef QByteArray::difference_type
5051 \internal
5052*/
5053
5054/*! \typedef QByteArray::const_reference
5055 \internal
5056*/
5057
5058/*! \typedef QByteArray::reference
5059 \internal
5060*/
5061
5062/*! \typedef QByteArray::const_pointer
5063 \internal
5064*/
5065
5066/*! \typedef QByteArray::pointer
5067 \internal
5068*/
5069
5070/*! \typedef QByteArray::value_type
5071 \internal
5072 */
5073
5074/*!
5075 \fn DataPtr &QByteArray::data_ptr()
5076 \internal
5077*/
5078
5079/*!
5080 \typedef QByteArray::DataPtr
5081 \internal
5082*/
5083
5084/*!
5085 \macro QByteArrayLiteral(ba)
5086 \relates QByteArray
5087
5088 The macro generates the data for a QByteArray out of the string literal
5089 \a ba at compile time. Creating a QByteArray from it is free in this case, and
5090 the generated byte array data is stored in the read-only segment of the
5091 compiled object file.
5092
5093 For instance:
5094
5095 \snippet code/src_corelib_tools_qbytearray.cpp 53
5096
5097 Using QByteArrayLiteral instead of a double quoted plain C++ string literal
5098 can significantly speed up creation of QByteArray instances from data known
5099 at compile time.
5100
5101 \sa QStringLiteral
5102*/
5103
5104namespace QtPrivate {
5105namespace DeprecatedRefClassBehavior {
5106void warn(WarningType w, EmittingClass c)
5107{
5108 const char *deprecatedBehaviorString =
5109 "The corresponding behavior is deprecated, and will be changed"
5110 " in a future version of Qt.";
5111
5112 const char *emittingClassName = nullptr;
5113
5114 switch (c) {
5115 case EmittingClass::QByteRef:
5116 emittingClassName = "QByteRef";
5117 break;
5118 case EmittingClass::QCharRef:
5119 emittingClassName = "QCharRef";
5120 break;
5121 }
5122
5123 const char *containerClassName = nullptr;
5124
5125 switch (c) {
5126 case EmittingClass::QByteRef:
5127 containerClassName = "QByteArray";
5128 break;
5129 case EmittingClass::QCharRef:
5130 containerClassName = "QString";
5131 break;
5132 }
5133
5134 switch (w) {
5135 case WarningType::OutOfRange:
5136 qWarning(msg: "Using %s with an index pointing outside the valid range of a %s. %s",
5137 emittingClassName, containerClassName, deprecatedBehaviorString);
5138 break;
5139 case WarningType::DelayedDetach:
5140 qWarning(msg: "Using %s on a %s that is not already detached. %s",
5141 emittingClassName, containerClassName, deprecatedBehaviorString);
5142 break;
5143 }
5144}
5145} // namespace DeprecatedRefClassBehavior
5146} // namespace QtPrivate
5147
5148/*!
5149 \class QByteArray::FromBase64Result
5150 \inmodule QtCore
5151 \ingroup tools
5152 \since 5.15
5153
5154 \brief The QByteArray::FromBase64Result class holds the result of
5155 a call to QByteArray::fromBase64Encoding.
5156
5157 Objects of this class can be used to check whether the conversion
5158 was successful, and if so, retrieve the decoded QByteArray. The
5159 conversion operators defined for QByteArray::FromBase64Result make
5160 its usage straightforward:
5161
5162 \snippet code/src_corelib_tools_qbytearray.cpp 44ter
5163
5164 Alternatively, it is possible to access the conversion status
5165 and the decoded data directly:
5166
5167 \snippet code/src_corelib_tools_qbytearray.cpp 44quater
5168
5169 \sa QByteArray::fromBase64
5170*/
5171
5172/*!
5173 \variable QByteArray::FromBase64Result::decoded
5174
5175 Contains the decoded byte array.
5176*/
5177
5178/*!
5179 \variable QByteArray::FromBase64Result::decodingStatus
5180
5181 Contains whether the decoding was successful, expressed as a value
5182 of type QByteArray::Base64DecodingStatus.
5183*/
5184
5185/*!
5186 \fn QByteArray::FromBase64Result::operator bool() const
5187
5188 Returns whether the decoding was successful. This is equivalent
5189 to checking whether the \c{decodingStatus} member is equal to
5190 QByteArray::Base64DecodingStatus::Ok.
5191*/
5192
5193/*!
5194 \fn QByteArray &QByteArray::FromBase64Result::operator*() const
5195
5196 Returns the decoded byte array.
5197*/
5198
5199/*!
5200 \fn bool operator==(const QByteArray::FromBase64Result &lhs, const QByteArray::FromBase64Result &rhs) noexcept
5201 \relates QByteArray::FromBase64Result
5202
5203 Returns \c true if \a lhs and \a rhs are equal, otherwise returns \c false.
5204
5205 \a lhs and \a rhs are equal if and only if they contain the same decoding
5206 status and, if the status is QByteArray::Base64DecodingStatus::Ok, if and
5207 only if they contain the same decoded data.
5208*/
5209
5210/*!
5211 \fn bool operator!=(const QByteArray::FromBase64Result &lhs, const QByteArray::FromBase64Result &rhs) noexcept
5212 \relates QByteArray::FromBase64Result
5213
5214 Returns \c true if \a lhs and \a rhs are different, otherwise returns \c false.
5215*/
5216
5217/*!
5218 \relates QByteArray::FromBase64Result
5219
5220 Returns the hash value for \a key, using
5221 \a seed to seed the calculation.
5222*/
5223uint qHash(const QByteArray::FromBase64Result &key, uint seed) noexcept
5224{
5225 QtPrivate::QHashCombine hash;
5226 seed = hash(seed, key.decoded);
5227 seed = hash(seed, static_cast<int>(key.decodingStatus));
5228 return seed;
5229}
5230
5231QT_END_NAMESPACE
5232

source code of qtbase/src/corelib/text/qbytearray.cpp