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