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