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 QStringAlgorithms<QByteArray>::remove_helper(*this, pos, len);
2427 return *this;
2428}
2429
2430/*!
2431 \fn QByteArray &QByteArray::removeAt(qsizetype pos)
2432
2433 \since 6.5
2434
2435 Removes the character at index \a pos. If \a pos is out of bounds
2436 (i.e. \a pos >= size()) this function does nothing.
2437
2438 \sa remove()
2439*/
2440
2441/*!
2442 \fn QByteArray &QByteArray::removeFirst()
2443
2444 \since 6.5
2445
2446 Removes the first character in this byte array. If the byte array is empty,
2447 this function does nothing.
2448
2449 \sa remove()
2450*/
2451/*!
2452 \fn QByteArray &QByteArray::removeLast()
2453
2454 \since 6.5
2455
2456 Removes the last character in this byte array. If the byte array is empty,
2457 this function does nothing.
2458
2459 \sa remove()
2460*/
2461
2462/*!
2463 \fn template <typename Predicate> QByteArray &QByteArray::removeIf(Predicate pred)
2464 \since 6.1
2465
2466 Removes all bytes for which the predicate \a pred returns true
2467 from the byte array. Returns a reference to the byte array.
2468
2469 \sa remove()
2470*/
2471
2472/*!
2473 Replaces \a len bytes from index position \a pos with the byte
2474 array \a after, and returns a reference to this byte array.
2475
2476 Example:
2477 \snippet code/src_corelib_text_qbytearray.cpp 19
2478
2479 \sa insert(), remove()
2480*/
2481
2482QByteArray &QByteArray::replace(qsizetype pos, qsizetype len, QByteArrayView after)
2483{
2484 if (size_t(pos) > size_t(this->size()))
2485 return *this;
2486 if (len > this->size() - pos)
2487 len = this->size() - pos;
2488 // Historic behavior, negative len was the equivalent of:
2489 // remove(pos, len); // does nothing
2490 // insert(pos, after);
2491 if (len <= 0)
2492 return insert(pos, after);
2493
2494 if (after.isEmpty())
2495 return remove(pos, len);
2496
2497 using A = QStringAlgorithms<QByteArray>;
2498 const qsizetype newlen = A::newSize(*this, len, after, {pos});
2499 if (data_ptr().needsDetach() || A::needsReallocate(*this, newlen)) {
2500 A::replace_into_copy(*this, len, after, {pos}, newlen);
2501 return *this;
2502 }
2503
2504 // No detaching or reallocation -> change in-place
2505 char *const begin = data_ptr().data(); // data(), without the detach() check
2506 char *const before = begin + pos;
2507 const char *beforeEnd = before + len;
2508 if (len >= after.size()) {
2509 memmove(before , after.cbegin(), after.size()); // sizeof(char) == 1
2510
2511 if (len > after.size()) {
2512 memmove(before + after.size(), beforeEnd, d.size - (beforeEnd - begin));
2513 A::setSize(*this, newlen);
2514 }
2515 } else { // len < after.size()
2516 char *oldEnd = begin + d.size;
2517 const qsizetype adjust = newlen - d.size;
2518 A::setSize(*this, newlen);
2519
2520 QByteArrayView tail{beforeEnd, oldEnd};
2521 QByteArrayView prefix = after;
2522 QByteArrayView suffix;
2523 if (QtPrivate::q_points_into_range(after.cend() - 1, tail)) {
2524 if (QtPrivate::q_points_into_range(after.cbegin(), tail)) {
2525 // `after` fully contained inside `tail`
2526 prefix = {};
2527 suffix = QByteArrayView{after.cbegin(), after.cend()};
2528 } else { // after.cbegin() is in [begin, beforeEnd)
2529 prefix = QByteArrayView{after.cbegin(), beforeEnd};
2530 suffix = QByteArrayView{beforeEnd, after.cend()};
2531 }
2532 }
2533 memmove(before + after.size(), tail.cbegin(), tail.size());
2534 if (!prefix.isEmpty())
2535 memmove(before, prefix.cbegin(), prefix.size()); // `prefix` may overlap `before`
2536 if (!suffix.isEmpty()) // adjust suffix after calling memcpy() above
2537 memcpy(before + prefix.size(), suffix.cbegin() + adjust, suffix.size()); // no overlap
2538 }
2539 return *this;
2540}
2541
2542/*! \fn QByteArray &QByteArray::replace(qsizetype pos, qsizetype len, const char *after, qsizetype alen)
2543
2544 \overload
2545
2546 Replaces \a len bytes from index position \a pos with \a alen bytes starting
2547 at position \a after. The bytes inserted may include '\\0' bytes.
2548
2549 \since 4.7
2550*/
2551
2552/*!
2553 \fn QByteArray &QByteArray::replace(const char *before, qsizetype bsize, const char *after, qsizetype asize)
2554 \overload
2555
2556 Replaces every occurrence of the \a bsize bytes starting at \a before with
2557 the \a asize bytes starting at \a after. Since the sizes of the strings are
2558 given by \a bsize and \a asize, they may contain '\\0' bytes and do not need
2559 to be '\\0'-terminated.
2560*/
2561
2562/*!
2563 \overload
2564 \since 6.0
2565
2566 Replaces every occurrence of the byte array \a before with the
2567 byte array \a after.
2568
2569 Example:
2570 \snippet code/src_corelib_text_qbytearray.cpp 20
2571*/
2572
2573QByteArray &QByteArray::replace(QByteArrayView before, QByteArrayView after)
2574{
2575 const char *b = before.data();
2576 qsizetype bsize = before.size();
2577 const char *a = after.data();
2578 qsizetype asize = after.size();
2579
2580 if (isEmpty()) {
2581 if (bsize)
2582 return *this;
2583 } else {
2584 if (b == a && bsize == asize)
2585 return *this;
2586 }
2587 if (asize == 0 && bsize == 0)
2588 return *this;
2589
2590 if (bsize == 1 && asize == 1)
2591 return replace(*b, *a); // use the fast char-char algorithm
2592
2593 // protect against `after` being part of this
2594 std::string pinnedReplacement;
2595 if (QtPrivate::q_points_into_range(a, d)) {
2596 pinnedReplacement.assign(a, a + asize);
2597 after = pinnedReplacement;
2598 }
2599
2600 QByteArrayMatcher matcher(b, bsize);
2601 // - create a table of replacement positions
2602 // - figure out the needed size; modify in place; or allocate a new byte array
2603 // and copy characters to it as needed
2604 // - do the replacements
2605 QVarLengthArray<qsizetype> indices;
2606 qsizetype index = 0;
2607 while ((index = matcher.indexIn(*this, index)) != -1) {
2608 indices.push_back(index);
2609 if (bsize > 0)
2610 index += bsize; // Step over before
2611 else
2612 ++index; // avoid infinite loop
2613 }
2614
2615 QStringAlgorithms<QByteArray>::replace_helper(*this, bsize, after, indices);
2616 return *this;
2617}
2618
2619/*!
2620 \fn QByteArray &QByteArray::replace(char before, QByteArrayView after)
2621 \overload
2622
2623 Replaces every occurrence of the byte \a before with the byte array \a
2624 after.
2625*/
2626
2627/*!
2628 \overload
2629
2630 Replaces every occurrence of the byte \a before with the byte \a after.
2631*/
2632
2633QByteArray &QByteArray::replace(char before, char after)
2634{
2635 if (before != after) {
2636 if (const auto pos = indexOf(before); pos >= 0) {
2637 if (d.needsDetach()) {
2638 QByteArray tmp(size(), Qt::Uninitialized);
2639 auto dst = tmp.d.data();
2640 dst = std::copy(d.data(), d.data() + pos, dst);
2641 *dst++ = after;
2642 std::replace_copy(d.data() + pos + 1, d.end(), dst, before, after);
2643 swap(tmp);
2644 } else {
2645 // in-place
2646 d.data()[pos] = after;
2647 std::replace(d.data() + pos + 1, d.end(), before, after);
2648 }
2649 }
2650 }
2651 return *this;
2652}
2653
2654/*!
2655 Splits the byte array into subarrays wherever \a sep occurs, and
2656 returns the list of those arrays. If \a sep does not match
2657 anywhere in the byte array, split() returns a single-element list
2658 containing this byte array.
2659*/
2660
2661QList<QByteArray> QByteArray::split(char sep) const
2662{
2663 QList<QByteArray> list;
2664 qsizetype start = 0;
2665 qsizetype end;
2666 while ((end = indexOf(sep, start)) != -1) {
2667 list.append(mid(start, end - start));
2668 start = end + 1;
2669 }
2670 list.append(mid(start));
2671 return list;
2672}
2673
2674/*!
2675 \since 4.5
2676
2677 Returns a copy of this byte array repeated the specified number of \a times.
2678
2679 If \a times is less than 1, an empty byte array is returned.
2680
2681 Example:
2682
2683 \snippet code/src_corelib_text_qbytearray.cpp 49
2684*/
2685QByteArray QByteArray::repeated(qsizetype times) const
2686{
2687 if (isEmpty())
2688 return *this;
2689
2690 if (times <= 1) {
2691 if (times == 1)
2692 return *this;
2693 return QByteArray();
2694 }
2695
2696 const qsizetype resultSize = [&] {
2697 auto r = times;
2698 if (mul_overflow(r, size(), &r))
2699 qBadAlloc();
2700 return r;
2701 }();
2702
2703 QByteArray result;
2704 result.reserve(resultSize);
2705 if (result.capacity() != resultSize)
2706 return QByteArray(); // not enough memory
2707
2708 memcpy(result.d.data(), data(), size());
2709
2710 qsizetype sizeSoFar = size();
2711 char *end = result.d.data() + sizeSoFar;
2712
2713 const qsizetype halfResultSize = resultSize >> 1;
2714 while (sizeSoFar <= halfResultSize) {
2715 memcpy(end, result.d.data(), sizeSoFar);
2716 end += sizeSoFar;
2717 sizeSoFar <<= 1;
2718 }
2719 memcpy(end, result.d.data(), resultSize - sizeSoFar);
2720 result.d.data()[resultSize] = '\0';
2721 result.d.size = resultSize;
2722 return result;
2723}
2724
2725/*! \fn qsizetype QByteArray::indexOf(QByteArrayView bv, qsizetype from) const
2726 \since 6.0
2727
2728 Returns the index position of the start of the first occurrence of the
2729 sequence of bytes viewed by \a bv in this byte array, searching forward
2730 from index position \a from. Returns -1 if no match is found.
2731
2732 Example:
2733 \snippet code/src_corelib_text_qbytearray.cpp 21
2734
2735 \sa lastIndexOf(), contains(), count()
2736*/
2737
2738/*!
2739 \fn qsizetype QByteArray::indexOf(char ch, qsizetype from) const
2740 \overload
2741
2742 Returns the index position of the start of the first occurrence of the
2743 byte \a ch in this byte array, searching forward from index position \a from.
2744 Returns -1 if no match is found.
2745
2746 Example:
2747 \snippet code/src_corelib_text_qbytearray.cpp 22
2748
2749 \sa lastIndexOf(), contains()
2750*/
2751
2752static qsizetype lastIndexOfHelper(const char *haystack, qsizetype l, const char *needle,
2753 qsizetype ol, qsizetype from)
2754{
2755 auto delta = l - ol;
2756 if (from > l)
2757 return -1;
2758 if (from < 0 || from > delta)
2759 from = delta;
2760 if (from < 0)
2761 return -1;
2762
2763 const char *end = haystack;
2764 haystack += from;
2765 const qregisteruint ol_minus_1 = ol - 1;
2766 const char *n = needle + ol_minus_1;
2767 const char *h = haystack + ol_minus_1;
2768 qregisteruint hashNeedle = 0, hashHaystack = 0;
2769 qsizetype idx;
2770 for (idx = 0; idx < ol; ++idx) {
2771 hashNeedle = ((hashNeedle<<1) + *(n-idx));
2772 hashHaystack = ((hashHaystack<<1) + *(h-idx));
2773 }
2774 hashHaystack -= *haystack;
2775 while (haystack >= end) {
2776 hashHaystack += *haystack;
2777 if (hashHaystack == hashNeedle && memcmp(needle, haystack, ol) == 0)
2778 return haystack - end;
2779 --haystack;
2780 if (ol_minus_1 < sizeof(ol_minus_1) * CHAR_BIT)
2781 hashHaystack -= qregisteruint(*(haystack + ol)) << ol_minus_1;
2782 hashHaystack <<= 1;
2783 }
2784 return -1;
2785}
2786
2787qsizetype QtPrivate::lastIndexOf(QByteArrayView haystack, qsizetype from, QByteArrayView needle) noexcept
2788{
2789 if (haystack.isEmpty()) {
2790 if (needle.isEmpty() && from == 0)
2791 return 0;
2792 return -1;
2793 }
2794 const auto ol = needle.size();
2795 if (ol == 1)
2796 return QtPrivate::lastIndexOf(haystack, from, needle.front());
2797
2798 return lastIndexOfHelper(haystack.data(), haystack.size(), needle.data(), ol, from);
2799}
2800
2801/*! \fn qsizetype QByteArray::lastIndexOf(QByteArrayView bv, qsizetype from) const
2802 \since 6.0
2803
2804 Returns the index position of the start of the last occurrence of the
2805 sequence of bytes viewed by \a bv in this byte array, searching backward
2806 from index position \a from.
2807
2808 \include qstring.qdocinc negative-index-start-search-from-end
2809
2810 Returns -1 if no match is found.
2811
2812 Example:
2813 \snippet code/src_corelib_text_qbytearray.cpp 23
2814
2815 \note When searching for a 0-length \a bv, the match at the end of
2816 the data is excluded from the search by a negative \a from, even
2817 though \c{-1} is normally thought of as searching from the end of
2818 the byte array: the match at the end is \e after the last character, so
2819 it is excluded. To include such a final empty match, either give a
2820 positive value for \a from or omit the \a from parameter entirely.
2821
2822 \sa indexOf(), contains(), count()
2823*/
2824
2825/*! \fn qsizetype QByteArray::lastIndexOf(QByteArrayView bv) const
2826 \since 6.2
2827 \overload
2828
2829 Returns the index position of the start of the last occurrence of the
2830 sequence of bytes viewed by \a bv in this byte array, searching backward
2831 from the end of the byte array. Returns -1 if no match is found.
2832
2833 Example:
2834 \snippet code/src_corelib_text_qbytearray.cpp 23
2835
2836 \sa indexOf(), contains(), count()
2837*/
2838
2839/*!
2840 \fn qsizetype QByteArray::lastIndexOf(char ch, qsizetype from) const
2841 \overload
2842
2843 Returns the index position of the start of the last occurrence of byte \a ch
2844 in this byte array, searching backward from index position \a from.
2845 If \a from is -1 (the default), the search starts at the last byte
2846 (at index size() - 1). Returns -1 if no match is found.
2847
2848 Example:
2849 \snippet code/src_corelib_text_qbytearray.cpp 24
2850
2851 \sa indexOf(), contains()
2852*/
2853
2854static inline qsizetype countCharHelper(QByteArrayView haystack, char needle) noexcept
2855{
2856 qsizetype num = 0;
2857 for (char ch : haystack) {
2858 if (ch == needle)
2859 ++num;
2860 }
2861 return num;
2862}
2863
2864qsizetype QtPrivate::count(QByteArrayView haystack, QByteArrayView needle) noexcept
2865{
2866 if (needle.size() == 0)
2867 return haystack.size() + 1;
2868
2869 if (needle.size() == 1)
2870 return countCharHelper(haystack, needle[0]);
2871
2872 qsizetype num = 0;
2873 qsizetype i = -1;
2874 if (haystack.size() > 500 && needle.size() > 5) {
2875 QByteArrayMatcher matcher(needle);
2876 while ((i = matcher.indexIn(haystack, i + 1)) != -1)
2877 ++num;
2878 } else {
2879 while ((i = haystack.indexOf(needle, i + 1)) != -1)
2880 ++num;
2881 }
2882 return num;
2883}
2884
2885/*! \fn qsizetype QByteArray::count(QByteArrayView bv) const
2886 \since 6.0
2887
2888 Returns the number of (potentially overlapping) occurrences of the
2889 sequence of bytes viewed by \a bv in this byte array.
2890
2891 \sa contains(), indexOf()
2892*/
2893
2894/*!
2895 \overload
2896
2897 Returns the number of occurrences of byte \a ch in the byte array.
2898
2899 \sa contains(), indexOf()
2900*/
2901
2902qsizetype QByteArray::count(char ch) const
2903{
2904 return countCharHelper(*this, ch);
2905}
2906
2907#if QT_DEPRECATED_SINCE(6, 4)
2908/*! \fn qsizetype QByteArray::count() const
2909 \deprecated [6.4] Use size() or length() instead.
2910 \overload
2911
2912 Same as size().
2913*/
2914#endif
2915
2916/*!
2917 \fn int QByteArray::compare(QByteArrayView bv, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
2918 \since 6.0
2919
2920 Returns an integer less than, equal to, or greater than zero depending on
2921 whether this QByteArray sorts before, at the same position as, or after the
2922 QByteArrayView \a bv. The comparison is performed according to case
2923 sensitivity \a cs.
2924
2925 \sa operator==, {Character Case}
2926*/
2927
2928bool QtPrivate::startsWith(QByteArrayView haystack, QByteArrayView needle) noexcept
2929{
2930 if (haystack.size() < needle.size())
2931 return false;
2932 if (haystack.data() == needle.data() || needle.size() == 0)
2933 return true;
2934 return memcmp(haystack.data(), needle.data(), needle.size()) == 0;
2935}
2936
2937/*! \fn bool QByteArray::startsWith(QByteArrayView bv) const
2938 \since 6.0
2939
2940 Returns \c true if this byte array starts with the sequence of bytes
2941 viewed by \a bv; otherwise returns \c false.
2942
2943 Example:
2944 \snippet code/src_corelib_text_qbytearray.cpp 25
2945
2946 \sa endsWith(), first()
2947*/
2948
2949/*!
2950 \fn bool QByteArray::startsWith(char ch) const
2951 \overload
2952
2953 Returns \c true if this byte array starts with byte \a ch; otherwise returns
2954 \c false.
2955*/
2956
2957bool QtPrivate::endsWith(QByteArrayView haystack, QByteArrayView needle) noexcept
2958{
2959 if (haystack.size() < needle.size())
2960 return false;
2961 if (haystack.end() == needle.end() || needle.size() == 0)
2962 return true;
2963 return memcmp(haystack.end() - needle.size(), needle.data(), needle.size()) == 0;
2964}
2965
2966/*!
2967 \fn bool QByteArray::endsWith(QByteArrayView bv) const
2968 \since 6.0
2969
2970 Returns \c true if this byte array ends with the sequence of bytes
2971 viewed by \a bv; otherwise returns \c false.
2972
2973 Example:
2974 \snippet code/src_corelib_text_qbytearray.cpp 26
2975
2976 \sa startsWith(), last()
2977*/
2978
2979/*!
2980 \fn bool QByteArray::endsWith(char ch) const
2981 \overload
2982
2983 Returns \c true if this byte array ends with byte \a ch;
2984 otherwise returns \c false.
2985*/
2986
2987/*
2988 Returns true if \a c is an uppercase ASCII letter.
2989 */
2990static constexpr inline bool isUpperCaseAscii(char c)
2991{
2992 return c >= 'A' && c <= 'Z';
2993}
2994
2995/*
2996 Returns true if \a c is an lowercase ASCII letter.
2997 */
2998static constexpr inline bool isLowerCaseAscii(char c)
2999{
3000 return c >= 'a' && c <= 'z';
3001}
3002
3003/*!
3004 Returns \c true if this byte array is uppercase, that is, if
3005 it's identical to its toUpper() folding.
3006
3007 Note that this does \e not mean that the byte array only contains
3008 uppercase letters; only that it contains no ASCII lowercase letters.
3009
3010 \since 5.12
3011
3012 \sa isLower(), toUpper()
3013*/
3014bool QByteArray::isUpper() const
3015{
3016 return std::none_of(begin(), end(), isLowerCaseAscii);
3017}
3018
3019/*!
3020 Returns \c true if this byte array is lowercase, that is, if
3021 it's identical to its toLower() folding.
3022
3023 Note that this does \e not mean that the byte array only contains
3024 lowercase letters; only that it contains no ASCII uppercase letters.
3025
3026 \since 5.12
3027
3028 \sa isUpper(), toLower()
3029 */
3030bool QByteArray::isLower() const
3031{
3032 return std::none_of(begin(), end(), isUpperCaseAscii);
3033}
3034
3035/*!
3036 \fn QByteArray::isValidUtf8() const
3037
3038 Returns \c true if this byte array contains valid UTF-8 encoded data,
3039 or \c false otherwise.
3040
3041 \since 6.3
3042*/
3043
3044/*!
3045 \fn QByteArray QByteArray::left(qsizetype len) const &
3046 \fn QByteArray QByteArray::left(qsizetype len) &&
3047
3048 Returns a byte array that contains the first \a len bytes of this byte
3049 array.
3050
3051 If you know that \a len cannot be out of bounds, use first() instead in new
3052 code, because it is faster.
3053
3054 The entire byte array is returned if \a len is greater than
3055 size().
3056
3057 Returns an empty QByteArray if \a len is smaller than 0.
3058
3059 \sa first(), last(), startsWith(), chopped(), chop(), truncate()
3060*/
3061
3062/*!
3063 \fn QByteArray QByteArray::right(qsizetype len) const &
3064 \fn QByteArray QByteArray::right(qsizetype len) &&
3065
3066 Returns a byte array that contains the last \a len bytes of this byte array.
3067
3068 If you know that \a len cannot be out of bounds, use last() instead in new
3069 code, because it is faster.
3070
3071 The entire byte array is returned if \a len is greater than
3072 size().
3073
3074 Returns an empty QByteArray if \a len is smaller than 0.
3075
3076 \sa endsWith(), last(), first(), sliced(), chopped(), chop(), truncate(), slice()
3077*/
3078
3079/*!
3080 \fn QByteArray QByteArray::mid(qsizetype pos, qsizetype len) const &
3081 \fn QByteArray QByteArray::mid(qsizetype pos, qsizetype len) &&
3082
3083 Returns a byte array containing \a len bytes from this byte array,
3084 starting at position \a pos.
3085
3086 If you know that \a pos and \a len cannot be out of bounds, use sliced()
3087 instead in new code, because it is faster.
3088
3089 If \a len is -1 (the default), or \a pos + \a len >= size(),
3090 returns a byte array containing all bytes starting at position \a
3091 pos until the end of the byte array.
3092
3093 \sa first(), last(), sliced(), chopped(), chop(), truncate(), slice()
3094*/
3095
3096QByteArray QByteArray::mid(qsizetype pos, qsizetype len) const &
3097{
3098 qsizetype p = pos;
3099 qsizetype l = len;
3100 using namespace QtPrivate;
3101 switch (QContainerImplHelper::mid(size(), &p, &l)) {
3102 case QContainerImplHelper::Null:
3103 return QByteArray();
3104 case QContainerImplHelper::Empty:
3105 {
3106 return QByteArray(DataPointer::fromRawData(&_empty, 0));
3107 }
3108 case QContainerImplHelper::Full:
3109 return *this;
3110 case QContainerImplHelper::Subset:
3111 return sliced(p, l);
3112 }
3113 Q_UNREACHABLE_RETURN(QByteArray());
3114}
3115
3116QByteArray QByteArray::mid(qsizetype pos, qsizetype len) &&
3117{
3118 qsizetype p = pos;
3119 qsizetype l = len;
3120 using namespace QtPrivate;
3121 switch (QContainerImplHelper::mid(size(), &p, &l)) {
3122 case QContainerImplHelper::Null:
3123 return QByteArray();
3124 case QContainerImplHelper::Empty:
3125 resize(0); // keep capacity if we've reserve()d
3126 [[fallthrough]];
3127 case QContainerImplHelper::Full:
3128 return std::move(*this);
3129 case QContainerImplHelper::Subset:
3130 return std::move(*this).sliced(p, l);
3131 }
3132 Q_UNREACHABLE_RETURN(QByteArray());
3133}
3134
3135/*!
3136 \fn QByteArray QByteArray::first(qsizetype n) const &
3137 \fn QByteArray QByteArray::first(qsizetype n) &&
3138 \since 6.0
3139
3140 Returns the first \a n bytes of the byte array.
3141
3142 \note The behavior is undefined when \a n < 0 or \a n > size().
3143
3144 Example:
3145 \snippet code/src_corelib_text_qbytearray.cpp 27
3146
3147 \sa last(), sliced(), startsWith(), chopped(), chop(), truncate(), slice()
3148*/
3149
3150/*!
3151 \fn QByteArray QByteArray::last(qsizetype n) const &
3152 \fn QByteArray QByteArray::last(qsizetype n) &&
3153 \since 6.0
3154
3155 Returns the last \a n bytes of the byte array.
3156
3157 \note The behavior is undefined when \a n < 0 or \a n > size().
3158
3159 Example:
3160 \snippet code/src_corelib_text_qbytearray.cpp 28
3161
3162 \sa first(), sliced(), endsWith(), chopped(), chop(), truncate(), slice()
3163*/
3164
3165/*!
3166 \fn QByteArray QByteArray::sliced(qsizetype pos, qsizetype n) const &
3167 \fn QByteArray QByteArray::sliced(qsizetype pos, qsizetype n) &&
3168 \since 6.0
3169
3170 Returns a byte array containing the \a n bytes of this object starting
3171 at position \a pos.
3172
3173 \note The behavior is undefined when \a pos < 0, \a n < 0,
3174 or \a pos + \a n > size().
3175
3176 Example:
3177 \snippet code/src_corelib_text_qbytearray.cpp 29
3178
3179 \sa first(), last(), chopped(), chop(), truncate(), slice()
3180*/
3181QByteArray QByteArray::sliced_helper(QByteArray &a, qsizetype pos, qsizetype n)
3182{
3183 if (n == 0)
3184 return fromRawData(&_empty, 0);
3185 DataPointer d = std::move(a.d).sliced(pos, n);
3186 d.data()[n] = 0;
3187 return QByteArray(std::move(d));
3188}
3189
3190/*!
3191 \fn QByteArray QByteArray::sliced(qsizetype pos) const &
3192 \fn QByteArray QByteArray::sliced(qsizetype pos) &&
3193 \since 6.0
3194 \overload
3195
3196 Returns a byte array containing the bytes starting at position \a pos
3197 in this object, and extending to the end of this object.
3198
3199 \note The behavior is undefined when \a pos < 0 or \a pos > size().
3200
3201 \sa first(), last(), chopped(), chop(), truncate(), slice()
3202*/
3203
3204/*!
3205 \fn QByteArray &QByteArray::slice(qsizetype pos, qsizetype n)
3206 \since 6.8
3207
3208 Modifies this byte array to start at position \a pos, extending for \a n
3209 bytes, and returns a reference to this byte array.
3210
3211 \note The behavior is undefined if \a pos < 0, \a n < 0,
3212 or \a pos + \a n > size().
3213
3214 Example:
3215 \snippet code/src_corelib_text_qbytearray.cpp 57
3216
3217 \sa sliced(), first(), last(), chopped(), chop(), truncate()
3218*/
3219
3220/*!
3221 \fn QByteArray &QByteArray::slice(qsizetype pos)
3222 \since 6.8
3223 \overload
3224
3225 Modifies this byte array to start at position \a pos, extending to its
3226 end, and returns a reference to this byte array.
3227
3228 \note The behavior is undefined if \a pos < 0 or \a pos > size().
3229
3230 \sa sliced(), first(), last(), chopped(), chop(), truncate()
3231*/
3232
3233/*!
3234 \fn QByteArray QByteArray::chopped(qsizetype len) const &
3235 \fn QByteArray QByteArray::chopped(qsizetype len) &&
3236 \since 5.10
3237
3238 Returns a byte array that contains the leftmost size() - \a len bytes of
3239 this byte array.
3240
3241 \note The behavior is undefined if \a len is negative or greater than size().
3242
3243 \sa endsWith(), first(), last(), sliced(), chop(), truncate(), slice()
3244*/
3245
3246/*!
3247 \fn QByteArray QByteArray::toLower() const
3248
3249 Returns a copy of the byte array in which each ASCII uppercase letter
3250 converted to lowercase.
3251
3252 Example:
3253 \snippet code/src_corelib_text_qbytearray.cpp 30
3254
3255 \sa isLower(), toUpper(), {Character Case}
3256*/
3257
3258static QByteArray toCase(const QByteArray &input, QByteArray *rvalue, uchar (*lookup)(uchar))
3259{
3260 // find the first bad character in input
3261 const char *orig_begin = input.constBegin();
3262 const char *firstBad = orig_begin;
3263 const char *e = input.constEnd();
3264 for ( ; firstBad != e ; ++firstBad) {
3265 uchar ch = uchar(*firstBad);
3266 uchar converted = lookup(ch);
3267 if (ch != converted)
3268 break;
3269 }
3270
3271 if (firstBad == e)
3272 return q_choose_copy_move(input, rvalue);
3273
3274 // transform the rest
3275 QByteArray s = q_choose_copy_move(input, rvalue);
3276 char *b = s.begin(); // will detach if necessary
3277 char *p = b + (firstBad - orig_begin);
3278 e = b + s.size();
3279 for ( ; p != e; ++p)
3280 *p = char(lookup(uchar(*p)));
3281 return s;
3282}
3283
3284QByteArray QByteArray::toLower_helper(const QByteArray &a)
3285{
3286 return toCase(a, nullptr, asciiLower);
3287}
3288
3289QByteArray QByteArray::toLower_helper(QByteArray &a)
3290{
3291 return toCase(a, &a, asciiLower);
3292}
3293
3294/*!
3295 \fn QByteArray QByteArray::toUpper() const
3296
3297 Returns a copy of the byte array in which each ASCII lowercase letter
3298 converted to uppercase.
3299
3300 Example:
3301 \snippet code/src_corelib_text_qbytearray.cpp 31
3302
3303 \sa isUpper(), toLower(), {Character Case}
3304*/
3305
3306QByteArray QByteArray::toUpper_helper(const QByteArray &a)
3307{
3308 return toCase(a, nullptr, asciiUpper);
3309}
3310
3311QByteArray QByteArray::toUpper_helper(QByteArray &a)
3312{
3313 return toCase(a, &a, asciiUpper);
3314}
3315
3316/*! \fn void QByteArray::clear()
3317
3318 Clears the contents of the byte array and makes it null.
3319
3320 \sa resize(), isNull()
3321*/
3322
3323void QByteArray::clear()
3324{
3325 d.clear();
3326}
3327
3328#if !defined(QT_NO_DATASTREAM)
3329
3330/*! \relates QByteArray
3331
3332 Writes byte array \a ba to the stream \a out and returns a reference
3333 to the stream.
3334
3335 \sa {Serializing Qt Data Types}
3336*/
3337
3338QDataStream &operator<<(QDataStream &out, const QByteArray &ba)
3339{
3340 if (ba.isNull() && out.version() >= 6) {
3341 QDataStream::writeQSizeType(out, -1);
3342 return out;
3343 }
3344 return out.writeBytes(ba.constData(), ba.size());
3345}
3346
3347/*! \relates QByteArray
3348
3349 Reads a byte array into \a ba from the stream \a in and returns a
3350 reference to the stream.
3351
3352 \sa {Serializing Qt Data Types}
3353*/
3354
3355QDataStream &operator>>(QDataStream &in, QByteArray &ba)
3356{
3357 ba.clear();
3358
3359 qint64 size = QDataStream::readQSizeType(in);
3360 if (in.status() != QDataStream::Ok)
3361 return in;
3362
3363 qsizetype len = size;
3364 if (size != len || size < -1) {
3365 ba.clear();
3366 in.setStatus(QDataStream::SizeLimitExceeded);
3367 return in;
3368 }
3369 if (len == -1) { // null byte-array
3370 ba = QByteArray();
3371 return in;
3372 }
3373
3374 constexpr qsizetype Step = 1024 * 1024;
3375 qsizetype allocated = 0;
3376
3377 do {
3378 qsizetype blockSize = qMin(Step, len - allocated);
3379 ba.resize(allocated + blockSize);
3380 if (in.readRawData(ba.data() + allocated, blockSize) != blockSize) {
3381 ba.clear();
3382 in.setStatus(QDataStream::ReadPastEnd);
3383 return in;
3384 }
3385 allocated += blockSize;
3386 } while (allocated < len);
3387
3388 return in;
3389}
3390#endif // QT_NO_DATASTREAM
3391
3392/*! \fn bool QByteArray::operator==(const QByteArray &lhs, const QByteArray &rhs)
3393 \overload
3394
3395 Returns \c true if byte array \a lhs is equal to byte array \a rhs;
3396 otherwise returns \c false.
3397
3398 \sa QByteArray::compare()
3399*/
3400
3401/*! \fn bool QByteArray::operator==(const QByteArray &lhs, const char * const &rhs)
3402 \overload
3403
3404 Returns \c true if byte array \a lhs is equal to the '\\0'-terminated string
3405 \a rhs; otherwise returns \c false.
3406
3407 \sa QByteArray::compare()
3408*/
3409
3410/*! \fn bool QByteArray::operator==(const char * const &lhs, const QByteArray &rhs)
3411 \overload
3412
3413 Returns \c true if '\\0'-terminated string \a lhs is equal to byte array \a
3414 rhs; otherwise returns \c false.
3415
3416 \sa QByteArray::compare()
3417*/
3418
3419/*! \fn bool QByteArray::operator!=(const QByteArray &lhs, const QByteArray &rhs)
3420 \overload
3421
3422 Returns \c true if byte array \a lhs is not equal to byte array \a rhs;
3423 otherwise returns \c false.
3424
3425 \sa QByteArray::compare()
3426*/
3427
3428/*! \fn bool QByteArray::operator!=(const QByteArray &lhs, const char * const &rhs)
3429 \overload
3430
3431 Returns \c true if byte array \a lhs is not equal to the '\\0'-terminated
3432 string \a rhs; otherwise returns \c false.
3433
3434 \sa QByteArray::compare()
3435*/
3436
3437/*! \fn bool QByteArray::operator!=(const char * const &lhs, const QByteArray &rhs)
3438 \overload
3439
3440 Returns \c true if '\\0'-terminated string \a lhs is not equal to byte array
3441 \a rhs; otherwise returns \c false.
3442
3443 \sa QByteArray::compare()
3444*/
3445
3446/*! \fn bool QByteArray::operator<(const QByteArray &lhs, const QByteArray &rhs)
3447 \overload
3448
3449 Returns \c true if byte array \a lhs is lexically less than 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 char * const &rhs)
3456 \overload
3457
3458 Returns \c true if byte array \a lhs is lexically less than the
3459 '\\0'-terminated string \a rhs; otherwise returns \c false.
3460
3461 \sa QByteArray::compare()
3462*/
3463
3464/*! \fn bool QByteArray::operator<(const char * const &lhs, const QByteArray &rhs)
3465 \overload
3466
3467 Returns \c true if '\\0'-terminated string \a lhs is lexically less than byte
3468 array \a rhs; otherwise returns \c false.
3469
3470 \sa QByteArray::compare()
3471*/
3472
3473/*! \fn bool QByteArray::operator<=(const QByteArray &lhs, const QByteArray &rhs)
3474 \overload
3475
3476 Returns \c true if byte array \a lhs is lexically less than or equal
3477 to byte array \a rhs; otherwise returns \c false.
3478
3479 \sa QByteArray::compare()
3480*/
3481
3482/*! \fn bool QByteArray::operator<=(const QByteArray &lhs, const char * const &rhs)
3483 \overload
3484
3485 Returns \c true if byte array \a lhs is lexically less than or equal to the
3486 '\\0'-terminated string \a rhs; otherwise returns \c false.
3487
3488 \sa QByteArray::compare()
3489*/
3490
3491/*! \fn bool QByteArray::operator<=(const char * const &lhs, const QByteArray &rhs)
3492 \overload
3493
3494 Returns \c true if '\\0'-terminated string \a lhs is lexically less than or
3495 equal to byte array \a rhs; otherwise returns \c false.
3496
3497 \sa QByteArray::compare()
3498*/
3499
3500/*! \fn bool QByteArray::operator>(const QByteArray &lhs, const QByteArray &rhs)
3501 \overload
3502
3503 Returns \c true if byte array \a lhs is lexically greater than byte
3504 array \a rhs; otherwise returns \c false.
3505
3506 \sa QByteArray::compare()
3507*/
3508
3509/*! \fn bool QByteArray::operator>(const QByteArray &lhs, const char * const &rhs)
3510 \overload
3511
3512 Returns \c true if byte array \a lhs is lexically greater than the
3513 '\\0'-terminated string \a rhs; otherwise returns \c false.
3514
3515 \sa QByteArray::compare()
3516*/
3517
3518/*! \fn bool QByteArray::operator>(const char * const &lhs, const QByteArray &rhs)
3519 \overload
3520
3521 Returns \c true if '\\0'-terminated string \a lhs is lexically greater than
3522 byte array \a rhs; otherwise returns \c false.
3523
3524 \sa QByteArray::compare()
3525*/
3526
3527/*! \fn bool QByteArray::operator>=(const QByteArray &lhs, const QByteArray &rhs)
3528 \overload
3529
3530 Returns \c true if byte array \a lhs is lexically greater than or
3531 equal to byte array \a rhs; otherwise returns \c false.
3532
3533 \sa QByteArray::compare()
3534*/
3535
3536/*! \fn bool QByteArray::operator>=(const QByteArray &lhs, const char * const &rhs)
3537 \overload
3538
3539 Returns \c true if byte array \a lhs is lexically greater than or equal to
3540 the '\\0'-terminated string \a rhs; otherwise returns \c false.
3541
3542 \sa QByteArray::compare()
3543*/
3544
3545/*! \fn bool QByteArray::operator>=(const char * const &lhs, const QByteArray &rhs)
3546 \overload
3547
3548 Returns \c true if '\\0'-terminated string \a lhs is lexically greater than
3549 or equal to byte array \a rhs; otherwise returns \c false.
3550
3551 \sa QByteArray::compare()
3552*/
3553
3554/*! \fn QByteArray operator+(const QByteArray &a1, const QByteArray &a2)
3555 \relates QByteArray
3556
3557 Returns a byte array that is the result of concatenating byte
3558 array \a a1 and byte array \a a2.
3559
3560 \sa QByteArray::operator+=()
3561*/
3562
3563/*! \fn QByteArray operator+(const QByteArray &a1, const char *a2)
3564 \relates QByteArray
3565
3566 \overload
3567
3568 Returns a byte array that is the result of concatenating byte array \a a1
3569 and '\\0'-terminated string \a a2.
3570*/
3571
3572/*! \fn QByteArray operator+(const QByteArray &a1, char a2)
3573 \relates QByteArray
3574
3575 \overload
3576
3577 Returns a byte array that is the result of concatenating byte
3578 array \a a1 and byte \a a2.
3579*/
3580
3581/*! \fn QByteArray operator+(const char *a1, const QByteArray &a2)
3582 \relates QByteArray
3583
3584 \overload
3585
3586 Returns a byte array that is the result of concatenating '\\0'-terminated
3587 string \a a1 and byte array \a a2.
3588*/
3589
3590/*! \fn QByteArray operator+(char a1, const QByteArray &a2)
3591 \relates QByteArray
3592
3593 \overload
3594
3595 Returns a byte array that is the result of concatenating byte \a a1 and byte
3596 array \a a2.
3597*/
3598
3599/*! \fn QByteArray operator+(const QByteArray &lhs, QByteArrayView rhs)
3600 \fn QByteArray operator+(QByteArrayView lhs, const QByteArray &rhs)
3601 \overload
3602 \since 6.9
3603 \relates QByteArray
3604
3605 Returns a byte array that is the result of concatenating \a lhs and \a rhs.
3606
3607 \sa QByteArray::operator+=()
3608*/
3609
3610/*!
3611 \fn QByteArray QByteArray::simplified() const
3612
3613 Returns a copy of this byte array that has spacing characters removed from
3614 the start and end, and in which each sequence of internal spacing characters
3615 is replaced with a single space.
3616
3617 The spacing characters are those for which the standard C++ \c isspace()
3618 function returns \c true in the C locale; these are the ASCII characters
3619 tabulation '\\t', line feed '\\n', carriage return '\\r', vertical
3620 tabulation '\\v', form feed '\\f', and space ' '.
3621
3622 Example:
3623 \snippet code/src_corelib_text_qbytearray.cpp 32
3624
3625 \sa trimmed(), QChar::SpecialCharacter, {Spacing Characters}
3626*/
3627QByteArray QByteArray::simplified_helper(const QByteArray &a)
3628{
3629 return QStringAlgorithms<const QByteArray>::simplified_helper(a);
3630}
3631
3632QByteArray QByteArray::simplified_helper(QByteArray &a)
3633{
3634 return QStringAlgorithms<QByteArray>::simplified_helper(a);
3635}
3636
3637/*!
3638 \fn QByteArray QByteArray::trimmed() const
3639
3640 Returns a copy of this byte array with spacing characters removed from the
3641 start and end.
3642
3643 The spacing characters are those for which the standard C++ \c isspace()
3644 function returns \c true in the C locale; these are the ASCII characters
3645 tabulation '\\t', line feed '\\n', carriage return '\\r', vertical
3646 tabulation '\\v', form feed '\\f', and space ' '.
3647
3648 Example:
3649 \snippet code/src_corelib_text_qbytearray.cpp 33
3650
3651 Unlike simplified(), \l {QByteArray::trimmed()}{trimmed()} leaves internal
3652 spacing unchanged.
3653
3654 \sa simplified(), QChar::SpecialCharacter, {Spacing Characters}
3655*/
3656QByteArray QByteArray::trimmed_helper(const QByteArray &a)
3657{
3658 return QStringAlgorithms<const QByteArray>::trimmed_helper(a);
3659}
3660
3661QByteArray QByteArray::trimmed_helper(QByteArray &a)
3662{
3663 return QStringAlgorithms<QByteArray>::trimmed_helper(a);
3664}
3665
3666QByteArrayView QtPrivate::trimmed(QByteArrayView view) noexcept
3667{
3668 const auto [start, stop] = QStringAlgorithms<QByteArrayView>::trimmed_helper_positions(view);
3669 return QByteArrayView(start, stop);
3670}
3671
3672/*!
3673 Returns a byte array of size \a width that contains this byte array padded
3674 with the \a fill byte.
3675
3676 If \a truncate is false and the size() of the byte array is more
3677 than \a width, then the returned byte array is a copy of this byte
3678 array.
3679
3680 If \a truncate is true and the size() of the byte array is more
3681 than \a width, then any bytes in a copy of the byte array
3682 after position \a width are removed, and the copy is returned.
3683
3684 Example:
3685 \snippet code/src_corelib_text_qbytearray.cpp 34
3686
3687 \sa rightJustified()
3688*/
3689
3690QByteArray QByteArray::leftJustified(qsizetype width, char fill, bool truncate) const
3691{
3692 return QStringAlgorithms<QByteArray>::aligned(*this, width, fill, Qt::AlignLeft, truncate);
3693}
3694
3695/*!
3696 Returns a byte array of size \a width that contains the \a fill byte
3697 followed by this byte array.
3698
3699 If \a truncate is false and the size of the byte array is more
3700 than \a width, then the returned byte array is a copy of this byte
3701 array.
3702
3703 If \a truncate is true and the size of the byte array is more
3704 than \a width, then the resulting byte array is truncated at
3705 position \a width.
3706
3707 Example:
3708 \snippet code/src_corelib_text_qbytearray.cpp 35
3709
3710 \sa leftJustified()
3711*/
3712
3713QByteArray QByteArray::rightJustified(qsizetype width, char fill, bool truncate) const
3714{
3715 return QStringAlgorithms<QByteArray>::aligned(*this, width, fill, Qt::AlignRight, truncate);
3716}
3717
3718auto QtPrivate::toSignedInteger(QByteArrayView data, int base) -> ParsedNumber<qlonglong>
3719{
3720#if defined(QT_CHECK_RANGE)
3721 if (base != 0 && (base < 2 || base > 36)) {
3722 qWarning("QByteArray::toIntegral: Invalid base %d", base);
3723 base = 10;
3724 }
3725#endif
3726 if (data.isEmpty())
3727 return {};
3728
3729 const QSimpleParsedNumber r = QLocaleData::bytearrayToLongLong(data, base);
3730 if (r.ok())
3731 return ParsedNumber(r.result);
3732 return {};
3733}
3734
3735auto QtPrivate::toUnsignedInteger(QByteArrayView data, int base) -> ParsedNumber<qulonglong>
3736{
3737#if defined(QT_CHECK_RANGE)
3738 if (base != 0 && (base < 2 || base > 36)) {
3739 qWarning("QByteArray::toIntegral: Invalid base %d", base);
3740 base = 10;
3741 }
3742#endif
3743 if (data.isEmpty())
3744 return {};
3745
3746 const QSimpleParsedNumber r = QLocaleData::bytearrayToUnsLongLong(data, base);
3747 if (r.ok())
3748 return ParsedNumber(r.result);
3749 return {};
3750}
3751
3752/*!
3753 Returns the byte array converted to a \c {long long} using base \a base,
3754 which is ten by default. Bases 0 and 2 through 36 are supported, using
3755 letters for digits beyond 9; A is ten, B is eleven and so on.
3756
3757 If \a base is 0, the base is determined automatically using the following
3758 rules: If the byte array begins with "0x", it is assumed to be hexadecimal
3759 (base 16); otherwise, if it begins with "0b", it is assumed to be binary
3760 (base 2); otherwise, if it begins with "0", it is assumed to be octal
3761 (base 8); otherwise it is assumed to be decimal.
3762
3763 Returns 0 if the conversion fails.
3764
3765 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3766 to \c false, and success by setting *\a{ok} to \c true.
3767
3768 \note The conversion of the number is performed in the default C locale,
3769 regardless of the user's locale. Use QLocale to perform locale-aware
3770 conversions between numbers and strings.
3771
3772 \note Support for the "0b" prefix was added in Qt 6.4.
3773
3774 \sa number()
3775*/
3776
3777qlonglong QByteArray::toLongLong(bool *ok, int base) const
3778{
3779 return QtPrivate::toIntegral<qlonglong>(qToByteArrayViewIgnoringNull(*this), ok, base);
3780}
3781
3782/*!
3783 Returns the byte array converted to an \c {unsigned long long} using base \a
3784 base, which is ten by default. Bases 0 and 2 through 36 are supported, using
3785 letters for digits beyond 9; A is ten, B is eleven and so on.
3786
3787 If \a base is 0, the base is determined automatically using the following
3788 rules: If the byte array begins with "0x", it is assumed to be hexadecimal
3789 (base 16); otherwise, if it begins with "0b", it is assumed to be binary
3790 (base 2); otherwise, if it begins with "0", it is assumed to be octal
3791 (base 8); otherwise it is assumed to be decimal.
3792
3793 Returns 0 if the conversion fails.
3794
3795 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3796 to \c false, and success by setting *\a{ok} to \c true.
3797
3798 \note The conversion of the number is performed in the default C locale,
3799 regardless of the user's locale. Use QLocale to perform locale-aware
3800 conversions between numbers and strings.
3801
3802 \note Support for the "0b" prefix was added in Qt 6.4.
3803
3804 \sa number()
3805*/
3806
3807qulonglong QByteArray::toULongLong(bool *ok, int base) const
3808{
3809 return QtPrivate::toIntegral<qulonglong>(qToByteArrayViewIgnoringNull(*this), ok, base);
3810}
3811
3812/*!
3813 Returns the byte array converted to an \c int using base \a base, which is
3814 ten by default. Bases 0 and 2 through 36 are supported, using letters for
3815 digits beyond 9; A is ten, B is eleven and so on.
3816
3817 If \a base is 0, the base is determined automatically using the following
3818 rules: If the byte array begins with "0x", it is assumed to be hexadecimal
3819 (base 16); otherwise, if it begins with "0b", it is assumed to be binary
3820 (base 2); otherwise, if it begins with "0", it is assumed to be octal
3821 (base 8); otherwise it is assumed to be decimal.
3822
3823 Returns 0 if the conversion fails.
3824
3825 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3826 to \c false, and success by setting *\a{ok} to \c true.
3827
3828 \snippet code/src_corelib_text_qbytearray.cpp 36
3829
3830 \note The conversion of the number is performed in the default C locale,
3831 regardless of the user's locale. Use QLocale to perform locale-aware
3832 conversions between numbers and strings.
3833
3834 \note Support for the "0b" prefix was added in Qt 6.4.
3835
3836 \sa number()
3837*/
3838
3839int QByteArray::toInt(bool *ok, int base) const
3840{
3841 return QtPrivate::toIntegral<int>(qToByteArrayViewIgnoringNull(*this), ok, base);
3842}
3843
3844/*!
3845 Returns the byte array converted to an \c {unsigned int} using base \a base,
3846 which is ten by default. Bases 0 and 2 through 36 are supported, using
3847 letters for digits beyond 9; A is ten, B is eleven and so on.
3848
3849 If \a base is 0, the base is determined automatically using the following
3850 rules: If the byte array begins with "0x", it is assumed to be hexadecimal
3851 (base 16); otherwise, if it begins with "0b", it is assumed to be binary
3852 (base 2); otherwise, if it begins with "0", it is assumed to be octal
3853 (base 8); otherwise it is assumed to be decimal.
3854
3855 Returns 0 if the conversion fails.
3856
3857 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3858 to \c false, and success by setting *\a{ok} to \c true.
3859
3860 \note The conversion of the number is performed in the default C locale,
3861 regardless of the user's locale. Use QLocale to perform locale-aware
3862 conversions between numbers and strings.
3863
3864 \note Support for the "0b" prefix was added in Qt 6.4.
3865
3866 \sa number()
3867*/
3868
3869uint QByteArray::toUInt(bool *ok, int base) const
3870{
3871 return QtPrivate::toIntegral<uint>(qToByteArrayViewIgnoringNull(*this), ok, base);
3872}
3873
3874/*!
3875 \since 4.1
3876
3877 Returns the byte array converted to a \c long int using base \a base, which
3878 is ten by default. Bases 0 and 2 through 36 are supported, using letters for
3879 digits beyond 9; A is ten, B is eleven and so on.
3880
3881 If \a base is 0, the base is determined automatically using the following
3882 rules: If the byte array begins with "0x", it is assumed to be hexadecimal
3883 (base 16); otherwise, if it begins with "0b", it is assumed to be binary
3884 (base 2); otherwise, if it begins with "0", it is assumed to be octal
3885 (base 8); otherwise it is assumed to be decimal.
3886
3887 Returns 0 if the conversion fails.
3888
3889 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3890 to \c false, and success by setting *\a{ok} to \c true.
3891
3892 \snippet code/src_corelib_text_qbytearray.cpp 37
3893
3894 \note The conversion of the number is performed in the default C locale,
3895 regardless of the user's locale. Use QLocale to perform locale-aware
3896 conversions between numbers and strings.
3897
3898 \note Support for the "0b" prefix was added in Qt 6.4.
3899
3900 \sa number()
3901*/
3902long QByteArray::toLong(bool *ok, int base) const
3903{
3904 return QtPrivate::toIntegral<long>(qToByteArrayViewIgnoringNull(*this), ok, base);
3905}
3906
3907/*!
3908 \since 4.1
3909
3910 Returns the byte array converted to an \c {unsigned long int} using base \a
3911 base, which is ten by default. Bases 0 and 2 through 36 are supported, using
3912 letters for digits beyond 9; A is ten, B is eleven and so on.
3913
3914 If \a base is 0, the base is determined automatically using the following
3915 rules: If the byte array begins with "0x", it is assumed to be hexadecimal
3916 (base 16); otherwise, if it begins with "0b", it is assumed to be binary
3917 (base 2); otherwise, if it begins with "0", it is assumed to be octal
3918 (base 8); otherwise it is assumed to be decimal.
3919
3920 Returns 0 if the conversion fails.
3921
3922 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3923 to \c false, and success by setting *\a{ok} to \c true.
3924
3925 \note The conversion of the number is performed in the default C locale,
3926 regardless of the user's locale. Use QLocale to perform locale-aware
3927 conversions between numbers and strings.
3928
3929 \note Support for the "0b" prefix was added in Qt 6.4.
3930
3931 \sa number()
3932*/
3933ulong QByteArray::toULong(bool *ok, int base) const
3934{
3935 return QtPrivate::toIntegral<ulong>(qToByteArrayViewIgnoringNull(*this), ok, base);
3936}
3937
3938/*!
3939 Returns the byte array converted to a \c short using base \a base, which is
3940 ten by default. Bases 0 and 2 through 36 are supported, using letters for
3941 digits beyond 9; A is ten, B is eleven and so on.
3942
3943 If \a base is 0, the base is determined automatically using the following
3944 rules: If the byte array begins with "0x", it is assumed to be hexadecimal
3945 (base 16); otherwise, if it begins with "0b", it is assumed to be binary
3946 (base 2); otherwise, if it begins with "0", it is assumed to be octal
3947 (base 8); otherwise it is assumed to be decimal.
3948
3949 Returns 0 if the conversion fails.
3950
3951 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3952 to \c false, and success by setting *\a{ok} to \c true.
3953
3954 \note The conversion of the number is performed in the default C locale,
3955 regardless of the user's locale. Use QLocale to perform locale-aware
3956 conversions between numbers and strings.
3957
3958 \note Support for the "0b" prefix was added in Qt 6.4.
3959
3960 \sa number()
3961*/
3962
3963short QByteArray::toShort(bool *ok, int base) const
3964{
3965 return QtPrivate::toIntegral<short>(qToByteArrayViewIgnoringNull(*this), ok, base);
3966}
3967
3968/*!
3969 Returns the byte array converted to an \c {unsigned short} using base \a
3970 base, which is ten by default. Bases 0 and 2 through 36 are supported, using
3971 letters for digits beyond 9; A is ten, B is eleven and so on.
3972
3973 If \a base is 0, the base is determined automatically using the following
3974 rules: If the byte array begins with "0x", it is assumed to be hexadecimal
3975 (base 16); otherwise, if it begins with "0b", it is assumed to be binary
3976 (base 2); otherwise, if it begins with "0", it is assumed to be octal
3977 (base 8); otherwise it is assumed to be decimal.
3978
3979 Returns 0 if the conversion fails.
3980
3981 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3982 to \c false, and success by setting *\a{ok} to \c true.
3983
3984 \note The conversion of the number is performed in the default C locale,
3985 regardless of the user's locale. Use QLocale to perform locale-aware
3986 conversions between numbers and strings.
3987
3988 \note Support for the "0b" prefix was added in Qt 6.4.
3989
3990 \sa number()
3991*/
3992
3993ushort QByteArray::toUShort(bool *ok, int base) const
3994{
3995 return QtPrivate::toIntegral<ushort>(qToByteArrayViewIgnoringNull(*this), ok, base);
3996}
3997
3998/*!
3999 Returns the byte array converted to a \c double value.
4000
4001 Returns an infinity if the conversion overflows or 0.0 if the
4002 conversion fails for other reasons (e.g. underflow).
4003
4004 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
4005 to \c false, and success by setting *\a{ok} to \c true.
4006
4007 \snippet code/src_corelib_text_qbytearray.cpp 38
4008
4009 \warning The QByteArray content may only contain valid numerical characters
4010 which includes the plus/minus sign, the character e used in scientific
4011 notation, and the decimal point. Including the unit or additional characters
4012 leads to a conversion error.
4013
4014 \note The conversion of the number is performed in the default C locale,
4015 regardless of the user's locale. Use QLocale to perform locale-aware
4016 conversions between numbers and strings.
4017
4018 This function ignores leading and trailing whitespace.
4019
4020 \sa number()
4021*/
4022
4023double QByteArray::toDouble(bool *ok) const
4024{
4025 return QByteArrayView(*this).toDouble(ok);
4026}
4027
4028auto QtPrivate::toDouble(QByteArrayView a) noexcept -> ParsedNumber<double>
4029{
4030 a = a.trimmed();
4031 auto r = qt_asciiToDouble(a.data(), a.size());
4032 if (r.ok())
4033 return ParsedNumber{r.result};
4034 else
4035 return {};
4036}
4037
4038/*!
4039 Returns the byte array converted to a \c float value.
4040
4041 Returns an infinity if the conversion overflows or 0.0 if the
4042 conversion fails for other reasons (e.g. underflow).
4043
4044 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
4045 to \c false, and success by setting *\a{ok} to \c true.
4046
4047 \snippet code/src_corelib_text_qbytearray.cpp 38float
4048
4049 \warning The QByteArray content may only contain valid numerical characters
4050 which includes the plus/minus sign, the character e used in scientific
4051 notation, and the decimal point. Including the unit or additional characters
4052 leads to a conversion error.
4053
4054 \note The conversion of the number is performed in the default C locale,
4055 regardless of the user's locale. Use QLocale to perform locale-aware
4056 conversions between numbers and strings.
4057
4058 This function ignores leading and trailing whitespace.
4059
4060 \sa number()
4061*/
4062
4063float QByteArray::toFloat(bool *ok) const
4064{
4065 return QLocaleData::convertDoubleToFloat(toDouble(ok), ok);
4066}
4067
4068auto QtPrivate::toFloat(QByteArrayView a) noexcept -> ParsedNumber<float>
4069{
4070 if (const auto r = toDouble(a)) {
4071 bool ok = true;
4072 const auto f = QLocaleData::convertDoubleToFloat(*r, &ok);
4073 if (ok)
4074 return ParsedNumber(f);
4075 }
4076 return {};
4077}
4078
4079template <typename S>
4081{
4082 // calculate ⌈n / 3⌉ * 4, saturating when final result overflows
4083 constexpr auto fail = (std::numeric_limits<S>::max)(); // causes allocations to fail
4084 if (add_overflow(n, S{2}, &n))
4085 return fail;
4086 n /= 3;
4087 if (mul_overflow(n, S{4}, &n))
4088 return fail;
4089 return n;
4090}
4091
4092/*!
4093 \since 5.2
4094
4095 Returns a copy of the byte array, encoded using the options \a options.
4096
4097 \snippet code/src_corelib_text_qbytearray.cpp 39
4098
4099 The algorithm used to encode Base64-encoded data is defined in \l{RFC 4648}.
4100
4101 \sa fromBase64()
4102*/
4103QByteArray QByteArray::toBase64(Base64Options options) const
4104{
4105 constexpr char alphabet_base64[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
4106 "ghijklmn" "opqrstuv" "wxyz0123" "456789+/";
4107 constexpr char alphabet_base64url[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
4108 "ghijklmn" "opqrstuv" "wxyz0123" "456789-_";
4109 const char *const alphabet = options & Base64UrlEncoding ? alphabet_base64url : alphabet_base64;
4110 constexpr char padchar = '=';
4111 qsizetype padlen = 0;
4112
4113 const qsizetype sz = size();
4114
4115 QByteArray tmp(b64_to_encoded_size_saturated(sz), Qt::Uninitialized);
4116
4117 qsizetype i = 0;
4118 char *out = tmp.data();
4119 while (i < sz) {
4120 // encode 3 bytes at a time
4121 int chunk = 0;
4122 chunk |= int(uchar(data()[i++])) << 16;
4123 if (i == sz) {
4124 padlen = 2;
4125 } else {
4126 chunk |= int(uchar(data()[i++])) << 8;
4127 if (i == sz)
4128 padlen = 1;
4129 else
4130 chunk |= int(uchar(data()[i++]));
4131 }
4132
4133 int j = (chunk & 0x00fc0000) >> 18;
4134 int k = (chunk & 0x0003f000) >> 12;
4135 int l = (chunk & 0x00000fc0) >> 6;
4136 int m = (chunk & 0x0000003f);
4137 *out++ = alphabet[j];
4138 *out++ = alphabet[k];
4139
4140 if (padlen > 1) {
4141 if ((options & OmitTrailingEquals) == 0)
4142 *out++ = padchar;
4143 } else {
4144 *out++ = alphabet[l];
4145 }
4146 if (padlen > 0) {
4147 if ((options & OmitTrailingEquals) == 0)
4148 *out++ = padchar;
4149 } else {
4150 *out++ = alphabet[m];
4151 }
4152 }
4153 Q_ASSERT((options & OmitTrailingEquals) || (out == tmp.size() + tmp.data()));
4154 if (options & OmitTrailingEquals)
4155 tmp.truncate(out - tmp.data());
4156 return tmp;
4157}
4158
4159/*!
4160 \fn QByteArray &QByteArray::setNum(int n, int base)
4161
4162 Represent the whole number \a n as text.
4163
4164 Sets this byte array to a string representing \a n in base \a base (ten by
4165 default) and returns a reference to this byte array. Bases 2 through 36 are
4166 supported, using letters for digits beyond 9; A is ten, B is eleven and so
4167 on.
4168
4169 Example:
4170 \snippet code/src_corelib_text_qbytearray.cpp 40
4171
4172 \note The format of the number is not localized; the default C locale is
4173 used regardless of the user's locale. Use QLocale to perform locale-aware
4174 conversions between numbers and strings.
4175
4176 \sa number(), toInt()
4177*/
4178
4179/*!
4180 \fn QByteArray &QByteArray::setNum(uint n, int base)
4181 \overload
4182
4183 \sa toUInt()
4184*/
4185
4186/*!
4187 \fn QByteArray &QByteArray::setNum(long n, int base)
4188 \overload
4189
4190 \sa toLong()
4191*/
4192
4193/*!
4194 \fn QByteArray &QByteArray::setNum(ulong n, int base)
4195 \overload
4196
4197 \sa toULong()
4198*/
4199
4200/*!
4201 \fn QByteArray &QByteArray::setNum(short n, int base)
4202 \overload
4203
4204 \sa toShort()
4205*/
4206
4207/*!
4208 \fn QByteArray &QByteArray::setNum(ushort n, int base)
4209 \overload
4210
4211 \sa toUShort()
4212*/
4213
4214/*!
4215 \overload
4216
4217 \sa toLongLong()
4218*/
4219QByteArray &QByteArray::setNum(qlonglong n, int base)
4220{
4221 constexpr int buffsize = 66; // big enough for MAX_ULLONG in base 2
4222 char buff[buffsize];
4223 char *p;
4224
4225 if (n < 0) {
4226 // Take care to avoid overflow on negating min value:
4227 p = qulltoa2(buff + buffsize, qulonglong(-(1 + n)) + 1, base);
4228 *--p = '-';
4229 } else {
4230 p = qulltoa2(buff + buffsize, qulonglong(n), base);
4231 }
4232
4233 return assign(QByteArrayView{p, buff + buffsize});
4234}
4235
4236/*!
4237 \overload
4238
4239 \sa toULongLong()
4240*/
4241
4242QByteArray &QByteArray::setNum(qulonglong n, int base)
4243{
4244 constexpr int buffsize = 66; // big enough for MAX_ULLONG in base 2
4245 char buff[buffsize];
4246 char *p = qulltoa2(buff + buffsize, n, base);
4247
4248 return assign(QByteArrayView{p, buff + buffsize});
4249}
4250
4251/*!
4252 \overload
4253//! [set-num]
4254 Represent the floating-point number \a n as text.
4255
4256 Sets this byte array to a string representing \a n, with a given \a format
4257 and \a precision (with the same meanings as for \l {QLocale::toString(double,
4258 char, int)}), and returns a reference to this byte array.
4259//! [set-num]
4260 \sa toDouble(), QLocale::FloatingPointPrecisionOption
4261*/
4262
4263QByteArray &QByteArray::setNum(double n, char format, int precision)
4264{
4265 return *this = QByteArray::number(n, format, precision);
4266}
4267
4268/*!
4269 \overload
4270 \fn QByteArray &QByteArray::setNum(float n, char format, int precision)
4271
4272 \include qbytearray.cpp set-num
4273
4274 \sa toFloat(), QLocale::FloatingPointPrecisionOption
4275*/
4276
4277/*!
4278 Returns a byte-array representing the whole number \a n as text.
4279
4280 Returns a byte array containing a string representing \a n, using the
4281 specified \a base (ten by default). Bases 2 through 36 are supported, using
4282 letters for digits beyond 9: A is ten, B is eleven and so on.
4283
4284 Example:
4285 \snippet code/src_corelib_text_qbytearray.cpp 41
4286
4287 \note The format of the number is not localized; the default C locale is
4288 used regardless of the user's locale. Use QLocale to perform locale-aware
4289 conversions between numbers and strings.
4290
4291 \sa setNum(), toInt()
4292*/
4293QByteArray QByteArray::number(int n, int base)
4294{
4295 QByteArray s;
4296 s.setNum(n, base);
4297 return s;
4298}
4299
4300/*!
4301 \overload
4302
4303 \sa toUInt()
4304*/
4305QByteArray QByteArray::number(uint n, int base)
4306{
4307 QByteArray s;
4308 s.setNum(n, base);
4309 return s;
4310}
4311
4312/*!
4313 \overload
4314
4315 \sa toLong()
4316*/
4317QByteArray QByteArray::number(long n, int base)
4318{
4319 QByteArray s;
4320 s.setNum(n, base);
4321 return s;
4322}
4323
4324/*!
4325 \overload
4326
4327 \sa toULong()
4328*/
4329QByteArray QByteArray::number(ulong n, int base)
4330{
4331 QByteArray s;
4332 s.setNum(n, base);
4333 return s;
4334}
4335
4336/*!
4337 \overload
4338
4339 \sa toLongLong()
4340*/
4341QByteArray QByteArray::number(qlonglong n, int base)
4342{
4343 QByteArray s;
4344 s.setNum(n, base);
4345 return s;
4346}
4347
4348/*!
4349 \overload
4350
4351 \sa toULongLong()
4352*/
4353QByteArray QByteArray::number(qulonglong n, int base)
4354{
4355 QByteArray s;
4356 s.setNum(n, base);
4357 return s;
4358}
4359
4360/*!
4361 \overload
4362 Returns a byte-array representing the floating-point number \a n as text.
4363
4364 Returns a byte array containing a string representing \a n, with a given \a
4365 format and \a precision, with the same meanings as for \l
4366 {QLocale::toString(double, char, int)}. For example:
4367
4368 \snippet code/src_corelib_text_qbytearray.cpp 42
4369
4370 \sa toDouble(), QLocale::FloatingPointPrecisionOption
4371*/
4372QByteArray QByteArray::number(double n, char format, int precision)
4373{
4375
4376 switch (QtMiscUtils::toAsciiLower(format)) {
4377 case 'f':
4379 break;
4380 case 'e':
4382 break;
4383 case 'g':
4385 break;
4386 default:
4387#if defined(QT_CHECK_RANGE)
4388 qWarning("QByteArray::setNum: Invalid format char '%c'", format);
4389#endif
4390 break;
4391 }
4392
4393 return qdtoAscii(n, form, precision, isUpperCaseAscii(format));
4394}
4395
4396/*!
4397 \fn QByteArray QByteArray::fromRawData(const char *data, qsizetype size) constexpr
4398
4399 Constructs a QByteArray that uses the first \a size bytes of the
4400 \a data array. The bytes are \e not copied. The QByteArray will
4401 contain the \a data pointer. The caller guarantees that \a data
4402 will not be deleted or modified as long as this QByteArray and any
4403 copies of it exist that have not been modified. In other words,
4404 because QByteArray is an \l{implicitly shared} class and the
4405 instance returned by this function contains the \a data pointer,
4406 the caller must not delete \a data or modify it directly as long
4407 as the returned QByteArray and any copies exist. However,
4408 QByteArray does not take ownership of \a data, so the QByteArray
4409 destructor will never delete the raw \a data, even when the
4410 last QByteArray referring to \a data is destroyed.
4411
4412 A subsequent attempt to modify the contents of the returned
4413 QByteArray or any copy made from it will cause it to create a deep
4414 copy of the \a data array before doing the modification. This
4415 ensures that the raw \a data array itself will never be modified
4416 by QByteArray.
4417
4418 Here is an example of how to read data using a QDataStream on raw
4419 data in memory without copying the raw data into a QByteArray:
4420
4421 \snippet code/src_corelib_text_qbytearray.cpp 43
4422
4423 \warning A byte array created with fromRawData() is \e not '\\0'-terminated,
4424 unless the raw data contains a '\\0' byte at position \a size. While that
4425 does not matter for QDataStream or functions like indexOf(), passing the
4426 byte array to a function accepting a \c{const char *} expected to be
4427 '\\0'-terminated will fail.
4428
4429 \sa setRawData(), data(), constData(), nullTerminate(), nullTerminated()
4430*/
4431
4432/*!
4433 \since 4.7
4434
4435 Resets the QByteArray to use the first \a size bytes of the
4436 \a data array. The bytes are \e not copied. The QByteArray will
4437 contain the \a data pointer. The caller guarantees that \a data
4438 will not be deleted or modified as long as this QByteArray and any
4439 copies of it exist that have not been modified.
4440
4441 This function can be used instead of fromRawData() to re-use
4442 existing QByteArray objects to save memory re-allocations.
4443
4444 \sa fromRawData(), data(), constData(), nullTerminate(), nullTerminated()
4445*/
4446QByteArray &QByteArray::setRawData(const char *data, qsizetype size)
4447{
4448 if (!data || !size)
4449 clear();
4450 else
4451 *this = fromRawData(data, size);
4452 return *this;
4453}
4454
4455namespace {
4456struct fromBase64_helper_result {
4457 qsizetype decodedLength;
4458 QByteArray::Base64DecodingStatus status;
4459};
4460
4461fromBase64_helper_result fromBase64_helper(const char *input, qsizetype inputSize,
4462 char *output /* may alias input */,
4463 QByteArray::Base64Options options)
4464{
4465 fromBase64_helper_result result{ 0, QByteArray::Base64DecodingStatus::Ok };
4466
4467 unsigned int buf = 0;
4468 int nbits = 0;
4469
4470 qsizetype offset = 0;
4471 for (qsizetype i = 0; i < inputSize; ++i) {
4472 int ch = input[i];
4473 int d;
4474
4475 if (ch >= 'A' && ch <= 'Z') {
4476 d = ch - 'A';
4477 } else if (ch >= 'a' && ch <= 'z') {
4478 d = ch - 'a' + 26;
4479 } else if (ch >= '0' && ch <= '9') {
4480 d = ch - '0' + 52;
4481 } else if (ch == '+' && (options & QByteArray::Base64UrlEncoding) == 0) {
4482 d = 62;
4483 } else if (ch == '-' && (options & QByteArray::Base64UrlEncoding) != 0) {
4484 d = 62;
4485 } else if (ch == '/' && (options & QByteArray::Base64UrlEncoding) == 0) {
4486 d = 63;
4487 } else if (ch == '_' && (options & QByteArray::Base64UrlEncoding) != 0) {
4488 d = 63;
4489 } else {
4490 if (options & QByteArray::AbortOnBase64DecodingErrors) {
4491 if (ch == '=') {
4492 // can have 1 or 2 '=' signs, in both cases padding base64Size to
4493 // a multiple of 4. Any other case is illegal.
4494 if ((inputSize % 4) != 0) {
4495 result.status = QByteArray::Base64DecodingStatus::IllegalInputLength;
4496 return result;
4497 } else if ((i == inputSize - 1) ||
4498 (i == inputSize - 2 && input[++i] == '=')) {
4499 d = -1; // ... and exit the loop, normally
4500 } else {
4501 result.status = QByteArray::Base64DecodingStatus::IllegalPadding;
4502 return result;
4503 }
4504 } else {
4505 result.status = QByteArray::Base64DecodingStatus::IllegalCharacter;
4506 return result;
4507 }
4508 } else {
4509 d = -1;
4510 }
4511 }
4512
4513 if (d != -1) {
4514 buf = (buf << 6) | d;
4515 nbits += 6;
4516 if (nbits >= 8) {
4517 nbits -= 8;
4518 Q_ASSERT(offset < i);
4519 output[offset++] = buf >> nbits;
4520 buf &= (1 << nbits) - 1;
4521 }
4522 }
4523 }
4524
4525 result.decodedLength = offset;
4526 return result;
4527}
4528} // anonymous namespace
4529
4530/*!
4531 \fn QByteArray::FromBase64Result QByteArray::fromBase64Encoding(QByteArray &&base64, Base64Options options)
4532 \fn QByteArray::FromBase64Result QByteArray::fromBase64Encoding(const QByteArray &base64, Base64Options options)
4533 \since 5.15
4534 \overload
4535
4536 Decodes the Base64 array \a base64, using the options
4537 defined by \a options. If \a options contains \c{IgnoreBase64DecodingErrors}
4538 (the default), the input is not checked for validity; invalid
4539 characters in the input are skipped, enabling the decoding process to
4540 continue with subsequent characters. If \a options contains
4541 \c{AbortOnBase64DecodingErrors}, then decoding will stop at the first
4542 invalid character.
4543
4544 For example:
4545
4546 \snippet code/src_corelib_text_qbytearray.cpp 44ter
4547
4548 The algorithm used to decode Base64-encoded data is defined in \l{RFC 4648}.
4549
4550 Returns a QByteArrayFromBase64Result object, containing the decoded
4551 data and a flag telling whether decoding was successful. If the
4552 \c{AbortOnBase64DecodingErrors} option was passed and the input
4553 data was invalid, it is unspecified what the decoded data contains.
4554
4555 \sa toBase64()
4556*/
4557QByteArray::FromBase64Result QByteArray::fromBase64Encoding(QByteArray &&base64, Base64Options options)
4558{
4559 // try to avoid a detach when calling data(), as it would over-allocate
4560 // (we need less space when decoding than the one required by the full copy)
4561 if (base64.isDetached()) {
4562 const auto base64result = fromBase64_helper(base64.data(),
4563 base64.size(),
4564 base64.data(), // in-place
4565 options);
4566 base64.truncate(base64result.decodedLength);
4567 return { std::move(base64), base64result.status };
4568 }
4569
4570 return fromBase64Encoding(base64, options);
4571}
4572
4573template <typename S>
4575{
4576 Q_ASSERT(n >= 0);
4577 // Calculate n * 3 / 4 w/o overflow, as ¾ = 1 - ¼, taking rounding into account:
4578 // floor(3 * n /4) == n - ceil(n / 4) == n - (n / 4 + (n % 4 ? 1 : 0))
4579 return n - (n / 4 + bool(n % 4));
4580}
4581
4582QByteArray::FromBase64Result QByteArray::fromBase64Encoding(const QByteArray &base64, Base64Options options)
4583{
4584 const auto base64Size = base64.size();
4585 QByteArray result(b64_to_decoded_size(base64Size), Qt::Uninitialized);
4586 const auto base64result = fromBase64_helper(base64.data(),
4587 base64Size,
4588 const_cast<char *>(result.constData()),
4589 options);
4590 result.truncate(base64result.decodedLength);
4591 return { std::move(result), base64result.status };
4592}
4593
4594/*!
4595 \since 5.2
4596
4597 Returns a decoded copy of the Base64 array \a base64, using the options
4598 defined by \a options. If \a options contains \c{IgnoreBase64DecodingErrors}
4599 (the default), the input is not checked for validity; invalid
4600 characters in the input are skipped, enabling the decoding process to
4601 continue with subsequent characters. If \a options contains
4602 \c{AbortOnBase64DecodingErrors}, then decoding will stop at the first
4603 invalid character.
4604
4605 For example:
4606
4607 \snippet code/src_corelib_text_qbytearray.cpp 44
4608
4609 The algorithm used to decode Base64-encoded data is defined in \l{RFC 4648}.
4610
4611 Returns the decoded data, or, if the \c{AbortOnBase64DecodingErrors}
4612 option was passed and the input data was invalid, an empty byte array.
4613
4614 \note The fromBase64Encoding() function is recommended in new code.
4615
4616 \sa toBase64(), fromBase64Encoding()
4617*/
4618QByteArray QByteArray::fromBase64(const QByteArray &base64, Base64Options options)
4619{
4620 if (auto result = fromBase64Encoding(base64, options))
4621 return std::move(result.decoded);
4622 return QByteArray();
4623}
4624
4625/*!
4626 Returns a decoded copy of the hex encoded array \a hexEncoded. Input is not
4627 checked for validity; invalid characters in the input are skipped, enabling
4628 the decoding process to continue with subsequent characters.
4629
4630 For example:
4631
4632 \snippet code/src_corelib_text_qbytearray.cpp 45
4633
4634 \sa toHex()
4635*/
4636QByteArray QByteArray::fromHex(const QByteArray &hexEncoded)
4637{
4638 QByteArray res((hexEncoded.size() + 1)/ 2, Qt::Uninitialized);
4639 uchar *result = (uchar *)res.data() + res.size();
4640
4641 bool odd_digit = true;
4642 for (qsizetype i = hexEncoded.size() - 1; i >= 0; --i) {
4643 uchar ch = uchar(hexEncoded.at(i));
4644 int tmp = QtMiscUtils::fromHex(ch);
4645 if (tmp == -1)
4646 continue;
4647 if (odd_digit) {
4648 --result;
4649 *result = tmp;
4650 odd_digit = false;
4651 } else {
4652 *result |= tmp << 4;
4653 odd_digit = true;
4654 }
4655 }
4656
4657 res.remove(0, result - (const uchar *)res.constData());
4658 return res;
4659}
4660
4661/*!
4662 Returns a hex encoded copy of the byte array.
4663
4664 The hex encoding uses the numbers 0-9 and the letters a-f.
4665
4666 If \a separator is not '\0', the separator character is inserted between
4667 the hex bytes.
4668
4669 Example:
4670 \snippet code/src_corelib_text_qbytearray.cpp 50
4671
4672 \since 5.9
4673 \sa fromHex()
4674*/
4675QByteArray QByteArray::toHex(char separator) const
4676{
4677 if (isEmpty())
4678 return QByteArray();
4679
4680 const auto length = [&] {
4681 using S = QByteArray::size_type;
4682 constexpr auto fail = (std::numeric_limits<S>::max)(); // will cause alloc failure
4683 auto r = size();
4684 if (separator) { // 3 * size() - 1
4685 if (mul_overflow(r, S{3}, &r))
4686 return fail;
4687 return r - 1;
4688 } else { // 2 * size()
4689 if (mul_overflow(r, S{2}, &r))
4690 return fail;
4691 return r;
4692 }
4693 }();
4694 QByteArray hex(length, Qt::Uninitialized);
4695 char *hexData = hex.data();
4696 const uchar *data = (const uchar *)this->data();
4697 for (qsizetype i = 0, o = 0; i < size(); ++i) {
4698 hexData[o++] = QtMiscUtils::toHexLower(data[i] >> 4);
4699 hexData[o++] = QtMiscUtils::toHexLower(data[i] & 0xf);
4700
4701 if ((separator) && (o < length))
4702 hexData[o++] = separator;
4703 }
4704 return hex;
4705}
4706
4707static qsizetype q_fromPercentEncoding(QByteArrayView src, char percent, QSpan<char> buffer)
4708{
4709 char *data = buffer.begin();
4710 const char *inputPtr = src.begin();
4711
4712 qsizetype i = 0;
4713 const qsizetype len = src.size();
4714 while (i < len) {
4715 char c = inputPtr[i];
4716 if (c == percent && i + 2 < len) {
4717 int a = QtMiscUtils::fromHex(uchar(inputPtr[++i]));
4718 int b = QtMiscUtils::fromHex(uchar(inputPtr[++i]));
4719 // don't check for validity; GIGO applies
4720 *data = uchar(a << 4) | uchar(b);
4721 } else {
4722 *data = c;
4723 }
4724 ++data;
4725 ++i;
4726 }
4727
4728 return data - buffer.begin();
4729}
4730
4731/*!
4732 \fn QByteArray QByteArray::percentDecoded(char percent) const &
4733 \since 6.4
4734
4735 Decodes URI/URL-style percent-encoding.
4736
4737 Returns a byte array containing the decoded text. The \a percent parameter
4738 allows use of a different character than '%' (for instance, '_' or '=') as
4739 the escape character.
4740
4741 For example:
4742 \snippet code/src_corelib_text_qbytearray.cpp 54
4743
4744 \note Given invalid input (such as a string containing the sequence "%G5",
4745 which is not a valid hexadecimal number) the output will be invalid as
4746 well. As an example: the sequence "%G5" could be decoded to 'W'.
4747
4748 \sa toPercentEncoding(), QUrl::fromPercentEncoding()
4749*/
4750
4751/*!
4752 \fn QByteArray QByteArray::percentDecoded(char percent) &&
4753 \since 6.11
4754 \overload
4755*/
4756
4757/*!
4758 \since 4.4
4759
4760 Decodes \a input from URI/URL-style percent-encoding.
4761
4762 Returns a byte array containing the decoded text. The \a percent parameter
4763 allows use of a different character than '%' (for instance, '_' or '=') as
4764 the escape character. Equivalent to input.percentDecoded(percent).
4765
4766 For example:
4767 \snippet code/src_corelib_text_qbytearray.cpp 51
4768
4769 \sa percentDecoded()
4770*/
4771QByteArray QByteArray::fromPercentEncoding(const QByteArray &input, char percent)
4772{
4773 if (input.isEmpty())
4774 return input; // Preserves isNull().
4775
4776 QByteArray out{input.size(), Qt::Uninitialized};
4777 qsizetype len = q_fromPercentEncoding(input, percent, out);
4778 out.truncate(len);
4779 return out;
4780}
4781
4782/*!
4783 \overload
4784 \since 6.11
4785*/
4786QByteArray QByteArray::fromPercentEncoding(QByteArray &&input, char percent)
4787{
4788 if (input.d.needsDetach())
4789 return fromPercentEncoding(input, percent); // lvalue overload
4790
4791 if (input.isEmpty())
4792 return std::move(input); // Preserves isNull().
4793
4794 qsizetype len = q_fromPercentEncoding(input, percent, input);
4795 input.truncate(len);
4796 return std::move(input);
4797}
4798
4799/*! \fn QByteArray QByteArray::fromStdString(const std::string &str)
4800 \since 5.4
4801
4802 Returns a copy of the \a str string as a QByteArray.
4803
4804 \sa toStdString(), QString::fromStdString()
4805*/
4806QByteArray QByteArray::fromStdString(const std::string &s)
4807{
4808 return QByteArray(s.data(), qsizetype(s.size()));
4809}
4810
4811/*!
4812 \fn std::string QByteArray::toStdString() const
4813 \since 5.4
4814
4815 Returns a std::string object with the data contained in this
4816 QByteArray.
4817
4818 This operator is mostly useful to pass a QByteArray to a function
4819 that accepts a std::string object.
4820
4821 \sa fromStdString(), QString::toStdString()
4822*/
4823std::string QByteArray::toStdString() const
4824{
4825 return std::string(data(), size_t(size()));
4826}
4827
4828/*!
4829 \fn QByteArray::operator std::string_view() const noexcept
4830 \target qbytearray-operator-std-string_view
4831 \since 6.10
4832
4833 Converts this QByteArray object to a \c{std::string_view} object.
4834 The returned string view will span over the entirety of the byte
4835 array.
4836*/
4837
4838/*!
4839 \since 4.4
4840
4841 Returns a URI/URL-style percent-encoded copy of this byte array. The
4842 \a percent parameter allows you to override the default '%'
4843 character for another.
4844
4845 By default, this function will encode all bytes that are not one of the
4846 following:
4847
4848 ALPHA ("a" to "z" and "A" to "Z") / DIGIT (0 to 9) / "-" / "." / "_" / "~"
4849
4850 To prevent bytes from being encoded pass them to \a exclude. To force bytes
4851 to be encoded pass them to \a include. The \a percent character is always
4852 encoded.
4853
4854 Example:
4855
4856 \snippet code/src_corelib_text_qbytearray.cpp 52
4857
4858 The hex encoding uses the numbers 0-9 and the uppercase letters A-F.
4859
4860 \sa fromPercentEncoding(), QUrl::toPercentEncoding()
4861*/
4862QByteArray QByteArray::toPercentEncoding(const QByteArray &exclude, const QByteArray &include,
4863 char percent) const
4864{
4865 if (isNull())
4866 return QByteArray(); // preserve null
4867 if (isEmpty())
4868 return QByteArray(data(), 0);
4869
4870 const auto contains = [](const QByteArray &view, char c) {
4871 // As view.contains(c), but optimised to bypass a lot of overhead:
4872 return view.size() > 0 && memchr(view.data(), c, view.size()) != nullptr;
4873 };
4874
4875 QByteArray result = *this;
4876 char *output = nullptr;
4877 qsizetype length = 0;
4878
4879 for (unsigned char c : *this) {
4880 if (char(c) != percent
4881 && ((c >= 0x61 && c <= 0x7A) // ALPHA
4882 || (c >= 0x41 && c <= 0x5A) // ALPHA
4883 || (c >= 0x30 && c <= 0x39) // DIGIT
4884 || c == 0x2D // -
4885 || c == 0x2E // .
4886 || c == 0x5F // _
4887 || c == 0x7E // ~
4888 || contains(exclude, c))
4889 && !contains(include, c)) {
4890 if (output)
4891 output[length] = c;
4892 ++length;
4893 } else {
4894 if (!output) {
4895 // detach now
4896 size_type n = size();
4897 if (mul_overflow(n, size_type{3}, &n)) // worst case: 3×
4898 n = (std::numeric_limits<size_type>::max)(); // will cause resize() to fail
4899 result.resize(n);
4900 output = result.data();
4901 }
4902 output[length++] = percent;
4903 output[length++] = QtMiscUtils::toHexUpper((c & 0xf0) >> 4);
4904 output[length++] = QtMiscUtils::toHexUpper(c & 0xf);
4905 }
4906 }
4907 if (output)
4908 result.truncate(length);
4909
4910 return result;
4911}
4912
4913#if defined(Q_OS_WASM) || defined(Q_QDOC)
4914
4915/*!
4916 Constructs a new QByteArray containing a copy of the Uint8Array \a uint8array.
4917
4918 This function transfers data from a JavaScript data buffer - which
4919 is not addressable from C++ code - to heap memory owned by a QByteArray.
4920 The Uint8Array can be released once this function returns and a copy
4921 has been made.
4922
4923 The \a uint8array argument must an emscripten::val referencing an Uint8Array
4924 object, e.g. obtained from a global JavaScript variable:
4925
4926 \snippet code/src_corelib_text_qbytearray.cpp 55
4927
4928 This function returns a null QByteArray if the size of the Uint8Array
4929 exceeds the maximum capacity of QByteArray, or if the \a uint8array
4930 argument is not of the Uint8Array type.
4931
4932 \since 6.5
4933 \ingroup platform-type-conversions
4934
4935 \sa toEcmaUint8Array()
4936*/
4937
4938QByteArray QByteArray::fromEcmaUint8Array(emscripten::val uint8array)
4939{
4940 return qstdweb::Uint8Array(uint8array).copyToQByteArray();
4941}
4942
4943/*!
4944 Creates a Uint8Array from a QByteArray.
4945
4946 This function transfers data from heap memory owned by a QByteArray
4947 to a JavaScript data buffer. The function allocates and copies into an
4948 ArrayBuffer, and returns a Uint8Array view to that buffer.
4949
4950 The JavaScript objects own a copy of the data, and this
4951 QByteArray can be safely deleted after the copy has been made.
4952
4953 \snippet code/src_corelib_text_qbytearray.cpp 56
4954
4955 \since 6.5
4956 \ingroup platform-type-conversions
4957
4958 \sa fromEcmaUint8Array()
4959*/
4960emscripten::val QByteArray::toEcmaUint8Array()
4961{
4962 return qstdweb::Uint8Array::copyFrom(*this).val();
4963}
4964
4965#endif
4966
4967/*! \typedef QByteArray::ConstIterator
4968 \internal
4969*/
4970
4971/*! \typedef QByteArray::Iterator
4972 \internal
4973*/
4974
4975/*! \typedef QByteArray::const_iterator
4976
4977 This typedef provides an STL-style const iterator for QByteArray.
4978
4979 \sa QByteArray::const_reverse_iterator, QByteArray::iterator
4980*/
4981
4982/*! \typedef QByteArray::iterator
4983
4984 This typedef provides an STL-style non-const iterator for QByteArray.
4985
4986 \sa QByteArray::reverse_iterator, QByteArray::const_iterator
4987*/
4988
4989/*! \typedef QByteArray::const_reverse_iterator
4990 \since 5.6
4991
4992 This typedef provides an STL-style const reverse iterator for QByteArray.
4993
4994 \sa QByteArray::reverse_iterator, QByteArray::const_iterator
4995*/
4996
4997/*! \typedef QByteArray::reverse_iterator
4998 \since 5.6
4999
5000 This typedef provides an STL-style non-const reverse iterator for QByteArray.
5001
5002 \sa QByteArray::const_reverse_iterator, QByteArray::iterator
5003*/
5004
5005/*! \typedef QByteArray::size_type
5006 \internal
5007*/
5008
5009/*! \typedef QByteArray::difference_type
5010 \internal
5011*/
5012
5013/*! \typedef QByteArray::const_reference
5014 \internal
5015*/
5016
5017/*! \typedef QByteArray::reference
5018 \internal
5019*/
5020
5021/*! \typedef QByteArray::const_pointer
5022 \internal
5023*/
5024
5025/*! \typedef QByteArray::pointer
5026 \internal
5027*/
5028
5029/*! \typedef QByteArray::value_type
5030 \internal
5031 */
5032
5033/*!
5034 \fn DataPtr &QByteArray::data_ptr()
5035 \internal
5036*/
5037
5038/*!
5039 \typedef QByteArray::DataPtr
5040 \internal
5041*/
5042
5043/*!
5044 \macro QByteArrayLiteral(ba)
5045 \relates QByteArray
5046
5047 The macro generates the data for a QByteArray out of the string literal \a
5048 ba at compile time. Creating a QByteArray from it is free in this case, and
5049 the generated byte array data is stored in the read-only segment of the
5050 compiled object file.
5051
5052 For instance:
5053
5054 \snippet code/src_corelib_text_qbytearray.cpp 53
5055
5056 Using QByteArrayLiteral instead of a double quoted plain C++ string literal
5057 can significantly speed up creation of QByteArray instances from data known
5058 at compile time.
5059
5060 \sa QStringLiteral
5061*/
5062
5063#if QT_DEPRECATED_SINCE(6, 8)
5064/*!
5065 \fn QtLiterals::operator""_qba(const char *str, size_t size)
5066
5067 \relates QByteArray
5068 \since 6.2
5069 \deprecated [6.8] Use \c _ba from Qt::StringLiterals namespace instead.
5070
5071 Literal operator that creates a QByteArray out of the first \a size characters
5072 in the char string literal \a str.
5073
5074 The QByteArray is created at compile time, and the generated string data is stored
5075 in the read-only segment of the compiled object file. Duplicate literals may share
5076 the same read-only memory. This functionality is interchangeable with
5077 QByteArrayLiteral, but saves typing when many string literals are present in the
5078 code.
5079
5080 The following code creates a QByteArray:
5081 \code
5082 auto str = "hello"_qba;
5083 \endcode
5084
5085 \sa QByteArrayLiteral, QtLiterals::operator""_qs(const char16_t *str, size_t size)
5086*/
5087#endif // QT_DEPRECATED_SINCE(6, 8)
5088
5089/*!
5090 \fn Qt::Literals::StringLiterals::operator""_ba(const char *str, size_t size)
5091
5092 \relates QByteArray
5093 \since 6.4
5094
5095 Literal operator that creates a QByteArray out of the first \a size characters
5096 in the char string literal \a str.
5097
5098 The QByteArray is created at compile time, and the generated string data is stored
5099 in the read-only segment of the compiled object file. Duplicate literals may share
5100 the same read-only memory. This functionality is interchangeable with
5101 QByteArrayLiteral, but saves typing when many string literals are present in the
5102 code.
5103
5104 The following code creates a QByteArray:
5105 \code
5106 using namespace Qt::StringLiterals;
5107
5108 auto str = "hello"_ba;
5109 \endcode
5110
5111 \sa Qt::Literals::StringLiterals
5112*/
5113
5114/*!
5115 \class QByteArray::FromBase64Result
5116 \inmodule QtCore
5117 \ingroup tools
5118 \since 5.15
5119
5120 \brief The QByteArray::FromBase64Result class holds the result of
5121 a call to QByteArray::fromBase64Encoding.
5122
5123 Objects of this class can be used to check whether the conversion
5124 was successful, and if so, retrieve the decoded QByteArray. The
5125 conversion operators defined for QByteArray::FromBase64Result make
5126 its usage straightforward:
5127
5128 \snippet code/src_corelib_text_qbytearray.cpp 44ter
5129
5130 Alternatively, it is possible to access the conversion status
5131 and the decoded data directly:
5132
5133 \snippet code/src_corelib_text_qbytearray.cpp 44quater
5134
5135 \sa QByteArray::fromBase64
5136*/
5137
5138/*!
5139 \variable QByteArray::FromBase64Result::decoded
5140
5141 Contains the decoded byte array.
5142*/
5143
5144/*!
5145 \variable QByteArray::FromBase64Result::decodingStatus
5146
5147 Contains whether the decoding was successful, expressed as a value
5148 of type QByteArray::Base64DecodingStatus.
5149*/
5150
5151/*!
5152 \fn QByteArray::FromBase64Result::operator bool() const
5153
5154 Returns whether the decoding was successful. This is equivalent
5155 to checking whether the \c{decodingStatus} member is equal to
5156 QByteArray::Base64DecodingStatus::Ok.
5157*/
5158
5159/*!
5160 \fn const QByteArray &QByteArray::FromBase64Result::operator*() const &
5161 \fn const QByteArray &&QByteArray::FromBase64Result::operator*() const &&
5162 \fn QByteArray &QByteArray::FromBase64Result::operator*() &
5163 \fn QByteArray &&QByteArray::FromBase64Result::operator*() &&
5164
5165 Returns the decoded byte array.
5166*/
5167
5168/*!
5169 \fn bool QByteArray::FromBase64Result::operator==(const QByteArray::FromBase64Result &lhs, const QByteArray::FromBase64Result &rhs) noexcept
5170
5171 Returns \c true if \a lhs and \a rhs are equal, otherwise returns \c false.
5172
5173 \a lhs and \a rhs are equal if and only if they contain the same decoding
5174 status and, if the status is QByteArray::Base64DecodingStatus::Ok, if and
5175 only if they contain the same decoded data.
5176*/
5177
5178/*!
5179 \fn bool QByteArray::FromBase64Result::operator!=(const QByteArray::FromBase64Result &lhs, const QByteArray::FromBase64Result &rhs) noexcept
5180
5181 Returns \c true if \a lhs and \a rhs are different, otherwise
5182 returns \c false.
5183*/
5184
5185/*!
5186 \qhashold{QByteArray::FromBase64Result}
5187*/
5188size_t qHash(const QByteArray::FromBase64Result &key, size_t seed) noexcept
5189{
5190 return qHashMulti(seed, key.decoded, static_cast<int>(key.decodingStatus));
5191}
5192
5193/*! \fn template <typename T> qsizetype erase(QByteArray &ba, const T &t)
5194 \relates QByteArray
5195 \since 6.1
5196
5197 Removes all elements that compare equal to \a t from the
5198 byte array \a ba. Returns the number of elements removed, if any.
5199
5200 \sa erase_if
5201*/
5202
5203/*! \fn template <typename Predicate> qsizetype erase_if(QByteArray &ba, Predicate pred)
5204 \relates QByteArray
5205 \since 6.1
5206
5207 Removes all elements for which the predicate \a pred returns true
5208 from the byte array \a ba. Returns the number of elements removed, if
5209 any.
5210
5211 \sa erase
5212*/
5213
5214QT_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