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