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

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