Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qbytearray.cpp
Go to the documentation of this file.
1// Copyright (C) 2022 The Qt Company Ltd.
2// Copyright (C) 2016 Intel Corporation.
3// Copyright (C) 2019 Klarälvdalens Datakonsult AB, a KDAB Group company, info@kdab.com, author Giuseppe D'Angelo <giuseppe.dangelo@kdab.com>
4// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
5// Qt-Security score:critical reason:data-parser
6
7#include "qbytearray.h"
9#include "private/qtools_p.h"
10#include "qhashfunctions.h"
11#include "qlist.h"
12#include "qlocale_p.h"
14#include "private/qnumeric_p.h"
15#include "private/qsimd_p.h"
17#include "qscopedpointer.h"
19#include <qdatastream.h>
20#include <qmath.h>
21#if defined(Q_OS_WASM)
22#include "private/qstdweb_p.h"
23#endif
24#include <QtCore/private/qtclasshelper_p.h>
25
26#ifndef QT_NO_COMPRESS
27#include <zconf.h>
28#include <zlib.h>
29#include <qxpfunctional.h>
30#endif
31#include <ctype.h>
32#include <limits.h>
33#include <string.h>
34#include <stdlib.h>
35
36#include <algorithm>
37#include <QtCore/q26numeric.h>
38#include <string>
39
40#ifdef Q_OS_WIN
41# if !defined(QT_BOOTSTRAPPED) && (defined(QT_NO_CAST_FROM_ASCII) || defined(QT_NO_CAST_FROM_BYTEARRAY))
42// MSVC requires this, but let's apply it to MinGW compilers too, just in case
43# error "This file cannot be compiled with QT_NO_CAST_{TO,FROM}_ASCII, "
44 "otherwise some QByteArray functions will not get exported."
45# endif
46#endif
47
48QT_BEGIN_NAMESPACE
49
50Q_CONSTINIT const char QByteArray::_empty = '\0';
51
52// ASCII case system, used by QByteArray::to{Upper,Lower}() and qstr(n)icmp():
53static constexpr inline uchar asciiUpper(uchar c)
54{
55 return c >= 'a' && c <= 'z' ? c & ~0x20 : c;
56}
57
58static constexpr inline uchar asciiLower(uchar c)
59{
60 return c >= 'A' && c <= 'Z' ? c | 0x20 : c;
61}
62
63/*****************************************************************************
64 Safe and portable C string functions; extensions to standard string.h
65 *****************************************************************************/
66
67/*! \relates QByteArray
68 \internal
69
70 Wrapper around memrchr() for systems that don't have it. It's provided in
71 every system because, as a GNU extension, memrchr() may not be declared in
72 string.h depending on how strict the compiler was asked to be.
73
74 Used in QByteArrayView::lastIndexOf() overload for a single char.
75*/
76const void *qmemrchr(const void *s, int needle, size_t size) noexcept
77{
78#if QT_CONFIG(memrchr)
79 return memrchr(s, needle, size);
80#endif
81 auto b = static_cast<const uchar *>(s);
82 const uchar *n = b + size;
83 while (n-- != b) {
84 if (*n == uchar(needle))
85 return n;
86 }
87 return nullptr;
88}
89
90
91/*! \relates QByteArray
92
93 Returns a duplicate string.
94
95 Allocates space for a copy of \a src, copies it, and returns a
96 pointer to the copy. If \a src is \nullptr, it immediately returns
97 \nullptr.
98
99 Ownership is passed to the caller, so the returned string must be
100 deleted using \c delete[].
101*/
102
103char *qstrdup(const char *src)
104{
105 if (!src)
106 return nullptr;
107 char *dst = new char[strlen(src) + 1];
108 return qstrcpy(dst, src);
109}
110
111/*! \relates QByteArray
112
113 Copies all the characters up to and including the '\\0' from \a
114 src into \a dst and returns a pointer to \a dst. If \a src is
115 \nullptr, it immediately returns \nullptr.
116
117 This function assumes that \a dst is large enough to hold the
118 contents of \a src.
119
120 \note If \a dst and \a src overlap, the behavior is undefined.
121
122 \sa qstrncpy()
123*/
124
125char *qstrcpy(char *dst, const char *src)
126{
127 if (!src)
128 return nullptr;
129#ifdef Q_CC_MSVC
130 const size_t len = strlen(src);
131 // This is actually not secure!!! It will be fixed
132 // properly in a later release!
133 if (len >= 0 && strcpy_s(dst, len+1, src) == 0)
134 return dst;
135 return nullptr;
136#else
137 return strcpy(dst, src);
138#endif
139}
140
141/*! \relates QByteArray
142
143 A safe \c strncpy() function.
144
145 Copies at most \a len bytes from \a src (stopping at \a len or the
146 terminating '\\0' whichever comes first) into \a dst. Guarantees that \a
147 dst is '\\0'-terminated, except when \a dst is \nullptr or \a len is 0. If
148 \a src is \nullptr, returns \nullptr, otherwise returns \a dst.
149
150 This function assumes that \a dst is at least \a len characters
151 long.
152
153 \note If \a dst and \a src overlap, the behavior is undefined.
154
155 \note Unlike strncpy(), this function does \e not write '\\0' to all \a
156 len bytes of \a dst, but stops after the terminating '\\0'. In this sense,
157 it's similar to C11's strncpy_s().
158
159 \sa qstrcpy()
160*/
161
162char *qstrncpy(char *dst, const char *src, size_t len)
163{
164 if (dst && len > 0) {
165 *dst = '\0';
166 if (src)
167 std::strncat(dst, src, len - 1);
168 }
169 return src ? dst : nullptr;
170}
171
172/*! \fn size_t qstrlen(const char *str)
173 \relates QByteArray
174
175 A safe \c strlen() function.
176
177 Returns the number of characters that precede the terminating '\\0',
178 or 0 if \a str is \nullptr.
179
180 \sa qstrnlen()
181*/
182
183/*! \fn size_t qstrnlen(const char *str, size_t maxlen)
184 \relates QByteArray
185 \since 4.2
186
187 A safe \c strnlen() function.
188
189 Returns the number of characters that precede the terminating '\\0', but
190 at most \a maxlen. If \a str is \nullptr, returns 0.
191
192 \sa qstrlen()
193*/
194
195/*!
196 \relates QByteArray
197
198 A safe \c strcmp() function.
199
200 Compares \a str1 and \a str2. Returns a negative value if \a str1
201 is less than \a str2, 0 if \a str1 is equal to \a str2 or a
202 positive value if \a str1 is greater than \a str2.
203
204 If both strings are \nullptr, they are deemed equal; otherwise, if either is
205 \nullptr, it is treated as less than the other (even if the other is an
206 empty string).
207
208 \sa qstrncmp(), qstricmp(), qstrnicmp(), {Character Case},
209 QByteArray::compare()
210*/
211int qstrcmp(const char *str1, const char *str2)
212{
213 return (str1 && str2) ? strcmp(str1, str2)
214 : (str1 ? 1 : (str2 ? -1 : 0));
215}
216
217/*! \fn int qstrncmp(const char *str1, const char *str2, size_t len);
218
219 \relates QByteArray
220
221 A safe \c strncmp() function.
222
223 Compares at most \a len bytes of \a str1 and \a str2.
224
225 Returns a negative value if \a str1 is less than \a str2, 0 if \a
226 str1 is equal to \a str2 or a positive value if \a str1 is greater
227 than \a str2.
228
229 If both strings are \nullptr, they are deemed equal; otherwise, if either is
230 \nullptr, it is treated as less than the other (even if the other is an
231 empty string or \a len is 0).
232
233 \sa qstrcmp(), qstricmp(), qstrnicmp(), {Character Case},
234 QByteArray::compare()
235*/
236
237/*! \relates QByteArray
238
239 A safe \c stricmp() function.
240
241 Compares \a str1 and \a str2, ignoring differences in the case of any ASCII
242 characters.
243
244 Returns a negative value if \a str1 is less than \a str2, 0 if \a
245 str1 is equal to \a str2 or a positive value if \a str1 is greater
246 than \a str2.
247
248 If both strings are \nullptr, they are deemed equal; otherwise, if either is
249 \nullptr, it is treated as less than the other (even if the other is an
250 empty string).
251
252 \sa qstrcmp(), qstrncmp(), qstrnicmp(), {Character Case},
253 QByteArray::compare()
254*/
255
256int qstricmp(const char *str1, const char *str2)
257{
258 const uchar *s1 = reinterpret_cast<const uchar *>(str1);
259 const uchar *s2 = reinterpret_cast<const uchar *>(str2);
260 if (!s1)
261 return s2 ? -1 : 0;
262 if (!s2)
263 return 1;
264
265 enum { Incomplete = 256 };
266 qptrdiff offset = 0;
267 auto innerCompare = [=, &offset](qptrdiff max, bool unlimited) {
268 max += offset;
269 do {
270 uchar c = s1[offset];
271 if (int res = QtMiscUtils::caseCompareAscii(c, s2[offset]))
272 return res;
273 if (!c)
274 return 0;
275 ++offset;
276 } while (unlimited || offset < max);
277 return int(Incomplete);
278 };
279
280#if defined(__SSE4_1__) && !(defined(__SANITIZE_ADDRESS__) || __has_feature(address_sanitizer))
281 enum { PageSize = 4096, PageMask = PageSize - 1 };
282 const __m128i zero = _mm_setzero_si128();
283 forever {
284 // Calculate how many bytes we can load until we cross a page boundary
285 // for either source. This isn't an exact calculation, just something
286 // very quick.
287 quintptr u1 = quintptr(s1 + offset);
288 quintptr u2 = quintptr(s2 + offset);
289 size_t n = PageSize - ((u1 | u2) & PageMask);
290
291 qptrdiff maxoffset = offset + n;
292 for ( ; offset + 16 <= maxoffset; offset += sizeof(__m128i)) {
293 // load 16 bytes from either source
294 __m128i a = _mm_loadu_si128(reinterpret_cast<const __m128i *>(s1 + offset));
295 __m128i b = _mm_loadu_si128(reinterpret_cast<const __m128i *>(s2 + offset));
296
297 // compare the two against each other
298 __m128i cmp = _mm_cmpeq_epi8(a, b);
299
300 // find NUL terminators too
301 cmp = _mm_min_epu8(cmp, a);
302 cmp = _mm_cmpeq_epi8(cmp, zero);
303
304 // was there any difference or a NUL?
305 uint mask = _mm_movemask_epi8(cmp);
306 if (mask) {
307 // yes, find out where
308 uint start = qCountTrailingZeroBits(mask);
309 uint end = sizeof(mask) * 8 - qCountLeadingZeroBits(mask);
310 Q_ASSERT(end >= start);
311 offset += start;
312 n = end - start;
313 break;
314 }
315 }
316
317 // using SIMD could cause a page fault, so iterate byte by byte
318 int res = innerCompare(n, false);
319 if (res != Incomplete)
320 return res;
321 }
322#endif
323
324 return innerCompare(-1, true);
325}
326
327/*! \relates QByteArray
328
329 A safe \c strnicmp() function.
330
331 Compares at most \a len bytes of \a str1 and \a str2, ignoring differences
332 in the case of any ASCII characters.
333
334 Returns a negative value if \a str1 is less than \a str2, 0 if \a str1
335 is equal to \a str2 or a positive value if \a str1 is greater than \a
336 str2.
337
338 If both strings are \nullptr, they are deemed equal; otherwise, if either is
339 \nullptr, it is treated as less than the other (even if the other is an
340 empty string or \a len is 0).
341
342 \sa qstrcmp(), qstrncmp(), qstricmp(), {Character Case},
343 QByteArray::compare()
344*/
345
346int qstrnicmp(const char *str1, const char *str2, size_t len)
347{
348 const uchar *s1 = reinterpret_cast<const uchar *>(str1);
349 const uchar *s2 = reinterpret_cast<const uchar *>(str2);
350 if (!s1 || !s2)
351 return s1 ? 1 : (s2 ? -1 : 0);
352 for (; len--; ++s1, ++s2) {
353 const uchar c = *s1;
354 if (int res = QtMiscUtils::caseCompareAscii(c, *s2))
355 return res;
356 if (!c) // strings are equal
357 break;
358 }
359 return 0;
360}
361
362/*!
363 \internal
364 \since 5.12
365
366 A helper for QByteArray::compare. Compares \a len1 bytes from \a str1 to \a
367 len2 bytes from \a str2. If \a len2 is -1, then \a str2 is expected to be
368 '\\0'-terminated.
369 */
370int qstrnicmp(const char *str1, qsizetype len1, const char *str2, qsizetype len2)
371{
372 Q_ASSERT(len1 >= 0);
373 Q_ASSERT(len2 >= -1);
374 const uchar *s1 = reinterpret_cast<const uchar *>(str1);
375 const uchar *s2 = reinterpret_cast<const uchar *>(str2);
376 if (!s1 || !len1) {
377 if (len2 == 0)
378 return 0;
379 if (len2 == -1)
380 return (!s2 || !*s2) ? 0 : -1;
381 Q_ASSERT(s2);
382 return -1;
383 }
384 if (!s2)
385 return len1 == 0 ? 0 : 1;
386
387 if (len2 == -1) {
388 // null-terminated str2
389 qsizetype i;
390 for (i = 0; i < len1; ++i) {
391 const uchar c = s2[i];
392 if (!c)
393 return 1;
394
395 if (int res = QtMiscUtils::caseCompareAscii(s1[i], c))
396 return res;
397 }
398 return s2[i] ? -1 : 0;
399 } else {
400 // not null-terminated
401 const qsizetype len = qMin(len1, len2);
402 for (qsizetype i = 0; i < len; ++i) {
403 if (int res = QtMiscUtils::caseCompareAscii(s1[i], s2[i]))
404 return res;
405 }
406 if (len1 == len2)
407 return 0;
408 return len1 < len2 ? -1 : 1;
409 }
410}
411
412/*!
413 \internal
414 */
415int QtPrivate::compareMemory(QByteArrayView lhs, QByteArrayView rhs)
416{
417 if (!lhs.isNull() && !rhs.isNull()) {
418 int ret = memcmp(lhs.data(), rhs.data(), qMin(lhs.size(), rhs.size()));
419 if (ret != 0)
420 return ret;
421 }
422
423 // they matched qMin(l1, l2) bytes
424 // so the longer one is lexically after the shorter one
425 return lhs.size() == rhs.size() ? 0 : lhs.size() > rhs.size() ? 1 : -1;
426}
427
428/*!
429 \internal
430*/
431bool QtPrivate::isValidUtf8(QByteArrayView s) noexcept
432{
433 return QUtf8::isValidUtf8(s).isValidUtf8;
434}
435
436// the CRC table below is created by the following piece of code
437#if 0
438static void createCRC16Table() // build CRC16 lookup table
439{
440 unsigned int i;
441 unsigned int j;
442 unsigned short crc_tbl[16];
443 unsigned int v0, v1, v2, v3;
444 for (i = 0; i < 16; i++) {
445 v0 = i & 1;
446 v1 = (i >> 1) & 1;
447 v2 = (i >> 2) & 1;
448 v3 = (i >> 3) & 1;
449 j = 0;
450#undef SET_BIT
451#define SET_BIT(x, b, v) (x) |= (v) << (b)
452 SET_BIT(j, 0, v0);
453 SET_BIT(j, 7, v0);
454 SET_BIT(j, 12, v0);
455 SET_BIT(j, 1, v1);
456 SET_BIT(j, 8, v1);
457 SET_BIT(j, 13, v1);
458 SET_BIT(j, 2, v2);
459 SET_BIT(j, 9, v2);
460 SET_BIT(j, 14, v2);
461 SET_BIT(j, 3, v3);
462 SET_BIT(j, 10, v3);
463 SET_BIT(j, 15, v3);
464 crc_tbl[i] = j;
465 }
466 printf("static const quint16 crc_tbl[16] = {\n");
467 for (int i = 0; i < 16; i +=4)
468 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]);
469 printf("};\n");
470}
471#endif
472
473static const quint16 crc_tbl[16] = {
474 0x0000, 0x1081, 0x2102, 0x3183,
475 0x4204, 0x5285, 0x6306, 0x7387,
476 0x8408, 0x9489, 0xa50a, 0xb58b,
477 0xc60c, 0xd68d, 0xe70e, 0xf78f
478};
479
480/*!
481 \relates QByteArray
482 \since 5.9
483
484 Returns the CRC-16 checksum of \a data.
485
486 The checksum is independent of the byte order (endianness) and will
487 be calculated accorded to the algorithm published in \a standard.
488 By default the algorithm published in ISO 3309 (Qt::ChecksumIso3309) is used.
489
490 \note This function is a 16-bit cache conserving (16 entry table)
491 implementation of the CRC-16-CCITT algorithm.
492*/
493quint16 qChecksum(QByteArrayView data, Qt::ChecksumType standard)
494{
495 quint16 crc = 0x0000;
496 switch (standard) {
497 case Qt::ChecksumIso3309:
498 crc = 0xffff;
499 break;
500 case Qt::ChecksumItuV41:
501 crc = 0x6363;
502 break;
503 }
504 uchar c;
505 const uchar *p = reinterpret_cast<const uchar *>(data.data());
506 qsizetype len = data.size();
507 while (len--) {
508 c = *p++;
509 crc = ((crc >> 4) & 0x0fff) ^ crc_tbl[((crc ^ c) & 15)];
510 c >>= 4;
511 crc = ((crc >> 4) & 0x0fff) ^ crc_tbl[((crc ^ c) & 15)];
512 }
513 switch (standard) {
514 case Qt::ChecksumIso3309:
515 crc = ~crc;
516 break;
517 case Qt::ChecksumItuV41:
518 break;
519 }
520 return crc & 0xffff;
521}
522
523/*!
524 \fn QByteArray qCompress(const QByteArray& data, int compressionLevel)
525
526 \relates QByteArray
527
528 Compresses the \a data byte array and returns the compressed data
529 in a new byte array.
530
531 The \a compressionLevel parameter specifies how much compression
532 should be used. Valid values are between 0 and 9, with 9
533 corresponding to the greatest compression (i.e. smaller compressed
534 data) at the cost of using a slower algorithm. Smaller values (8,
535 7, ..., 1) provide successively less compression at slightly
536 faster speeds. The value 0 corresponds to no compression at all.
537 The default value is -1, which specifies zlib's default
538 compression.
539
540 \sa qUncompress(const QByteArray &data)
541*/
542
543/*!
544 \fn QByteArray qCompress(const uchar* data, qsizetype nbytes, int compressionLevel)
545 \relates QByteArray
546
547 \overload
548
549 Compresses the first \a nbytes of \a data at compression level
550 \a compressionLevel and returns the compressed data in a new byte array.
551*/
552
553#ifndef QT_NO_COMPRESS
554using CompressSizeHint_t = quint32; // 32-bit BE, historically
555
556enum class ZLibOp : bool { Compression, Decompression };
557
559static const char *zlibOpAsString(ZLibOp op)
560{
561 switch (op) {
562 case ZLibOp::Compression: return "qCompress";
563 case ZLibOp::Decompression: return "qUncompress";
564 }
565 Q_UNREACHABLE_RETURN(nullptr);
566}
567
568Q_DECL_COLD_FUNCTION
569static QByteArray zlibError(ZLibOp op, const char *what)
570{
571 qWarning("%s: %s", zlibOpAsString(op), what);
572 return QByteArray();
573}
574
575Q_DECL_COLD_FUNCTION
576static QByteArray dataIsNull(ZLibOp op)
577{
578 return zlibError(op, "Data is null");
579}
580
581Q_DECL_COLD_FUNCTION
582static QByteArray lengthIsNegative(ZLibOp op)
583{
584 return zlibError(op, "Input length is negative");
585}
586
587Q_DECL_COLD_FUNCTION
588static QByteArray tooMuchData(ZLibOp op)
589{
590 return zlibError(op, "Not enough memory");
591}
592
593Q_DECL_COLD_FUNCTION
594static QByteArray invalidCompressedData()
595{
596 return zlibError(ZLibOp::Decompression, "Input data is corrupted");
597}
598
599Q_DECL_COLD_FUNCTION
600static QByteArray unexpectedZlibError(ZLibOp op, int err, const char *msg)
601{
602 qWarning("%s unexpected zlib error: %s (%d)",
603 zlibOpAsString(op),
604 msg ? msg : "",
605 err);
606 return QByteArray();
607}
608
609static QByteArray xxflate(ZLibOp op, QArrayDataPointer<char> out, QByteArrayView input,
610 qxp::function_ref<int(z_stream *) const> init,
611 qxp::function_ref<int(z_stream *, size_t) const> processChunk,
612 qxp::function_ref<void(z_stream *) const> deinit)
613{
614 if (out.data() == nullptr) // allocation failed
615 return tooMuchData(op);
616 qsizetype capacity = out.allocatedCapacity();
617
618 const auto initalSize = out.size;
619
620 z_stream zs = {};
621 zs.next_in = reinterpret_cast<uchar *>(const_cast<char *>(input.data())); // 1980s C API...
622 if (const int err = init(&zs); err != Z_OK)
623 return unexpectedZlibError(op, err, zs.msg);
624 const auto sg = qScopeGuard([&] { deinit(&zs); });
625
626 using ZlibChunkSize_t = decltype(zs.avail_in);
627 static_assert(!std::is_signed_v<ZlibChunkSize_t>);
628 static_assert(std::is_same_v<ZlibChunkSize_t, decltype(zs.avail_out)>);
629 constexpr auto MaxChunkSize = std::numeric_limits<ZlibChunkSize_t>::max();
630 [[maybe_unused]]
631 constexpr auto MaxStatisticsSize = std::numeric_limits<decltype(zs.total_out)>::max();
632
633 size_t inputLeft = size_t(input.size());
634
635 int res;
636 do {
637 Q_ASSERT(out.freeSpaceAtBegin() == 0); // ensure prepend optimization stays out of the way
638 Q_ASSERT(capacity == out.allocatedCapacity());
639
640 if (zs.avail_out == 0) {
641 Q_ASSERT(size_t(out.size) - initalSize > MaxStatisticsSize || // total_out overflow
642 size_t(out.size) - initalSize == zs.total_out);
643 Q_ASSERT(out.size <= capacity);
644
645 qsizetype avail_out = capacity - out.size;
646 if (avail_out == 0) {
647 out->reallocateAndGrow(QArrayData::GrowsAtEnd, 1); // grow to next natural capacity
648 if (out.data() == nullptr) // reallocation failed
649 return tooMuchData(op);
650 capacity = out.allocatedCapacity();
651 avail_out = capacity - out.size;
652 }
653 zs.next_out = reinterpret_cast<uchar *>(out.data()) + out.size;
654 zs.avail_out = size_t(avail_out) > size_t(MaxChunkSize) ? MaxChunkSize
655 : ZlibChunkSize_t(avail_out);
656 out.size += zs.avail_out;
657
658 Q_ASSERT(zs.avail_out > 0);
659 }
660
661 if (zs.avail_in == 0) {
662 // zs.next_in is kept up-to-date by processChunk(), so nothing to do
663 zs.avail_in = inputLeft > MaxChunkSize ? MaxChunkSize : ZlibChunkSize_t(inputLeft);
664 inputLeft -= zs.avail_in;
665 }
666
667 res = processChunk(&zs, inputLeft);
668 } while (res == Z_OK);
669
670 switch (res) {
671 case Z_STREAM_END:
672 out.size -= zs.avail_out;
673 Q_ASSERT(size_t(out.size) - initalSize > MaxStatisticsSize || // total_out overflow
674 size_t(out.size) - initalSize == zs.total_out);
675 Q_ASSERT(out.size <= out.allocatedCapacity());
676 out.data()[out.size] = '\0';
677 return QByteArray(std::move(out));
678
679 case Z_MEM_ERROR:
680 return tooMuchData(op);
681
682 case Z_BUF_ERROR:
683 Q_UNREACHABLE(); // cannot happen - we supply a buffer that can hold the result,
684 // or else error out early
685
686 case Z_DATA_ERROR: // can only happen on decompression
687 Q_ASSERT(op == ZLibOp::Decompression);
688 return invalidCompressedData();
689
690 default:
691 return unexpectedZlibError(op, res, zs.msg);
692 }
693}
694
695QByteArray qCompress(const uchar* data, qsizetype nbytes, int compressionLevel)
696{
697 constexpr qsizetype HeaderSize = sizeof(CompressSizeHint_t);
698 if (nbytes == 0) {
699 return QByteArray(HeaderSize, '\0');
700 }
701 if (!data)
702 return dataIsNull(ZLibOp::Compression);
703
704 if (nbytes < 0)
705 return lengthIsNegative(ZLibOp::Compression);
706
707 if (compressionLevel < -1 || compressionLevel > 9)
708 compressionLevel = -1;
709
710 QArrayDataPointer out = [&] {
711 constexpr qsizetype SingleAllocLimit = 256 * 1024; // the maximum size for which we use
712 // zlib's compressBound() to guarantee
713 // the output buffer size is sufficient
714 // to hold result
715 qsizetype capacity = HeaderSize;
716 if (nbytes < SingleAllocLimit) {
717 // use maximum size
718 capacity += compressBound(uLong(nbytes)); // cannot overflow (both times)!
719 return QArrayDataPointer<char>(capacity);
720 }
721
722 // for larger buffers, assume it compresses optimally, and
723 // grow geometrically from there:
724 constexpr qsizetype MaxCompressionFactor = 1024; // max theoretical factor is 1032
725 // cf. http://www.zlib.org/zlib_tech.html,
726 // but use a nearby power-of-two (faster)
727 capacity += std::max(qsizetype(compressBound(uLong(SingleAllocLimit))),
728 nbytes / MaxCompressionFactor);
729 return QArrayDataPointer<char>(capacity, 0, QArrayData::Grow);
730 }();
731
732 if (out.data() == nullptr) // allocation failed
733 return tooMuchData(ZLibOp::Compression);
734
735 qToBigEndian(q26::saturate_cast<CompressSizeHint_t>(nbytes), out.data());
736 out.size = HeaderSize;
737
738 return xxflate(ZLibOp::Compression, std::move(out), {data, nbytes},
739 [=] (z_stream *zs) { return deflateInit(zs, compressionLevel); },
740 [] (z_stream *zs, size_t inputLeft) {
741 return deflate(zs, inputLeft ? Z_NO_FLUSH : Z_FINISH);
742 },
743 [] (z_stream *zs) { deflateEnd(zs); });
744}
745#endif
746
747/*!
748 \fn QByteArray qUncompress(const QByteArray &data)
749
750 \relates QByteArray
751
752 Uncompresses the \a data byte array and returns a new byte array
753 with the uncompressed data.
754
755 Returns an empty QByteArray if the input data was corrupt.
756
757 This function will uncompress data compressed with qCompress()
758 from this and any earlier Qt version, back to Qt 3.1 when this
759 feature was added.
760
761 \b{Note:} If you want to use this function to uncompress external
762 data that was compressed using zlib, you first need to prepend a four
763 byte header to the byte array containing the data. The header must
764 contain the expected length (in bytes) of the uncompressed data,
765 expressed as an unsigned, big-endian, 32-bit integer. This number is
766 just a hint for the initial size of the output buffer size,
767 though. If the indicated size is too small to hold the result, the
768 output buffer size will still be increased until either the output
769 fits or the system runs out of memory. So, despite the 32-bit
770 header, this function, on 64-bit platforms, can produce more than
771 4GiB of output.
772
773 \note In Qt versions prior to Qt 6.5, more than 2GiB of data
774 worked unreliably; in Qt versions prior to Qt 6.0, not at all.
775
776 \sa qCompress()
777*/
778
779#ifndef QT_NO_COMPRESS
780/*! \relates QByteArray
781
782 \overload
783
784 Uncompresses the first \a nbytes of \a data and returns a new byte
785 array with the uncompressed data.
786*/
787QByteArray qUncompress(const uchar* data, qsizetype nbytes)
788{
789 if (!data)
790 return dataIsNull(ZLibOp::Decompression);
791
792 if (nbytes < 0)
793 return lengthIsNegative(ZLibOp::Decompression);
794
795 constexpr qsizetype HeaderSize = sizeof(CompressSizeHint_t);
796 if (nbytes < HeaderSize)
797 return invalidCompressedData();
798
799 const auto expectedSize = qFromBigEndian<CompressSizeHint_t>(data);
800 if (nbytes == HeaderSize) {
801 if (expectedSize != 0)
802 return invalidCompressedData();
803 return QByteArray();
804 }
805
806 constexpr auto MaxDecompressedSize = size_t(QByteArray::maxSize());
807 if constexpr (MaxDecompressedSize < std::numeric_limits<CompressSizeHint_t>::max()) {
808 if (expectedSize > MaxDecompressedSize)
809 return tooMuchData(ZLibOp::Decompression);
810 }
811
812 // expectedSize may be truncated, so always use at least nbytes
813 // (larger by at most 1%, according to zlib docs)
814 qsizetype capacity = std::max(qsizetype(expectedSize), // cannot overflow!
815 nbytes);
816
817 QArrayDataPointer<char> d(capacity);
818 return xxflate(ZLibOp::Decompression, std::move(d), {data + HeaderSize, nbytes - HeaderSize},
819 [] (z_stream *zs) { return inflateInit(zs); },
820 [] (z_stream *zs, size_t) { return inflate(zs, Z_NO_FLUSH); },
821 [] (z_stream *zs) { inflateEnd(zs); });
822}
823#endif
824
825/*!
826 \class QByteArray
827 \inmodule QtCore
828 \brief The QByteArray class provides an array of bytes.
829
830 \ingroup tools
831 \ingroup shared
832 \ingroup string-processing
833
834 \reentrant
835
836 \compares strong
837 \compareswith strong {const char *}
838 \endcompareswith
839 \compareswith strong QChar char16_t QString QStringView QLatin1StringView \
840 QUtf8StringView
841 When comparing with string types, the content is interpreted as UTF-8.
842 \endcompareswith
843
844 QByteArray can be used to store both raw bytes (including '\\0's)
845 and traditional 8-bit '\\0'-terminated strings. Using QByteArray
846 is much more convenient than using \c{const char *}. Behind the
847 scenes, it always ensures that the data is followed by a '\\0'
848 terminator, and uses \l{implicit sharing} (copy-on-write) to
849 reduce memory usage and avoid needless copying of data.
850
851 In addition to QByteArray, Qt also provides the QString class to store
852 string data. For most purposes, QString is the class you want to use. It
853 understands its content as Unicode text (encoded using UTF-16) where
854 QByteArray aims to avoid assumptions about the encoding or semantics of the
855 bytes it stores (aside from a few legacy cases where it uses ASCII).
856 Furthermore, QString is used throughout in the Qt API. The two main cases
857 where QByteArray is appropriate are when you need to store raw binary data,
858 and when memory conservation is critical (e.g., with Qt for Embedded Linux).
859
860 One way to initialize a QByteArray is simply to pass a \c{const
861 char *} to its constructor. For example, the following code
862 creates a byte array of size 5 containing the data "Hello":
863
864 \snippet code/src_corelib_text_qbytearray.cpp 0
865
866 Although the size() is 5, the byte array also maintains an extra '\\0' byte
867 at the end so that if a function is used that asks for a pointer to the
868 underlying data (e.g. a call to data()), the data pointed to is guaranteed
869 to be '\\0'-terminated.
870
871 QByteArray makes a deep copy of the \c{const char *} data, so you can modify
872 it later without experiencing side effects. (If, for example for performance
873 reasons, you don't want to take a deep copy of the data, use
874 QByteArray::fromRawData() instead.)
875
876 Another approach is to set the size of the array using resize() and to
877 initialize the data byte by byte. QByteArray uses 0-based indexes, just like
878 C++ arrays. To access the byte at a particular index position, you can use
879 operator[](). On non-const byte arrays, operator[]() returns a reference to
880 a byte that can be used on the left side of an assignment. For example:
881
882 \snippet code/src_corelib_text_qbytearray.cpp 1
883
884 For read-only access, an alternative syntax is to use at():
885
886 \snippet code/src_corelib_text_qbytearray.cpp 2
887
888 at() can be faster than operator[](), because it never causes a
889 \l{deep copy} to occur.
890
891 To extract many bytes at a time, use first(), last(), or sliced().
892
893 A QByteArray can embed '\\0' bytes. The size() function always
894 returns the size of the whole array, including embedded '\\0'
895 bytes, but excluding the terminating '\\0' added by QByteArray.
896 For example:
897
898 \snippet code/src_corelib_text_qbytearray.cpp 48
899
900 If you want to obtain the length of the data up to and excluding the first
901 '\\0' byte, call qstrlen() on the byte array.
902
903 After a call to resize(), newly allocated bytes have undefined
904 values. To set all the bytes to a particular value, call fill().
905
906 To obtain a pointer to the actual bytes, call data() or constData(). These
907 functions return a pointer to the beginning of the data. The pointer is
908 guaranteed to remain valid until a non-const function is called on the
909 QByteArray. It is also guaranteed that the data ends with a '\\0' byte
910 unless the QByteArray was created from \l{fromRawData()}{raw data}. This
911 '\\0' byte is automatically provided by QByteArray and is not counted in
912 size().
913
914 QByteArray provides the following basic functions for modifying
915 the byte data: append(), prepend(), insert(), replace(), and
916 remove(). For example:
917
918 \snippet code/src_corelib_text_qbytearray.cpp 3
919
920 In the above example the replace() function's first two arguments are the
921 position from which to start replacing and the number of bytes that
922 should be replaced.
923
924 When data-modifying functions increase the size of the array,
925 they may lead to reallocation of memory for the QByteArray object. When
926 this happens, QByteArray expands by more than it immediately needs so as
927 to have space for further expansion without reallocation until the size
928 of the array has greatly increased.
929
930 The insert(), remove() and, when replacing a sub-array with one of
931 different size, replace() functions can be slow (\l{linear time}) for
932 large arrays, because they require moving many bytes in the array by
933 at least one position in memory.
934
935 If you are building a QByteArray gradually and know in advance
936 approximately how many bytes the QByteArray will contain, you
937 can call reserve(), asking QByteArray to preallocate a certain amount
938 of memory. You can also call capacity() to find out how much
939 memory the QByteArray actually has allocated.
940
941 Note that using non-const operators and functions can cause
942 QByteArray to do a deep copy of the data, due to \l{implicit sharing}.
943
944 QByteArray provides \l{STL-style iterators} (QByteArray::const_iterator and
945 QByteArray::iterator). In practice, iterators are handy when working with
946 generic algorithms provided by the C++ standard library.
947
948 \note Iterators and references to individual QByteArray elements are subject
949 to stability issues. They are often invalidated when a QByteArray-modifying
950 operation (e.g. insert() or remove()) is called. When stability and
951 iterator-like functionality is required, you should use indexes instead of
952 iterators as they are not tied to QByteArray's internal state and thus do
953 not get invalidated.
954
955 \note Iterators over a QByteArray, and references to individual bytes
956 within one, cannot be relied on to remain valid when any non-const method
957 of the QByteArray is called. Accessing such an iterator or reference after
958 the call to a non-const method leads to undefined behavior. When stability
959 for iterator-like functionality is required, you should use indexes instead
960 of iterators as they are not tied to QByteArray's internal state and thus do
961 not get invalidated.
962
963 If you want to find all occurrences of a particular byte or sequence of
964 bytes in a QByteArray, use indexOf() or lastIndexOf(). The former searches
965 forward starting from a given index position, the latter searches
966 backward. Both return the index position of the byte sequence if they find
967 it; otherwise, they return -1. For example, here's a typical loop that finds
968 all occurrences of a particular string:
969
970 \snippet code/src_corelib_text_qbytearray.cpp 4
971
972 If you simply want to check whether a QByteArray contains a particular byte
973 sequence, use contains(). If you want to find out how many times a
974 particular byte sequence occurs in the byte array, use count(). If you want
975 to replace all occurrences of a particular value with another, use one of
976 the two-parameter replace() overloads.
977
978 \l{QByteArray}s can be compared using overloaded operators such as
979 operator<(), operator<=(), operator==(), operator>=(), and so on. The
980 comparison is based exclusively on the numeric values of the bytes and is
981 very fast, but is not what a human would
982 expect. QString::localeAwareCompare() is a better choice for sorting
983 user-interface strings.
984
985 For historical reasons, QByteArray distinguishes between a null
986 byte array and an empty byte array. A \e null byte array is a
987 byte array that is initialized using QByteArray's default
988 constructor or by passing (const char *)0 to the constructor. An
989 \e empty byte array is any byte array with size 0. A null byte
990 array is always empty, but an empty byte array isn't necessarily
991 null:
992
993 \snippet code/src_corelib_text_qbytearray.cpp 5
994
995 All functions except isNull() treat null byte arrays the same as empty byte
996 arrays. For example, data() returns a valid pointer (\e not nullptr) to a
997 '\\0' byte for a null byte array and QByteArray() compares equal to
998 QByteArray(""). We recommend that you always use isEmpty() and avoid
999 isNull().
1000
1001 \section1 Maximum size and out-of-memory conditions
1002
1003 The maximum size of QByteArray depends on the architecture. Most 64-bit
1004 systems can allocate more than 2 GB of memory, with a typical limit
1005 of 2^63 bytes. The actual value also depends on the overhead required for
1006 managing the data block. As a result, you can expect the maximum size
1007 of 2 GB minus overhead on 32-bit platforms, and 2^63 bytes minus overhead
1008 on 64-bit platforms. The number of elements that can be stored in a
1009 QByteArray is this maximum size.
1010
1011 When memory allocation fails, QByteArray throws a \c std::bad_alloc
1012 exception if the application is being compiled with exception support.
1013 Out of memory conditions in Qt containers are the only case where Qt
1014 will throw exceptions. If exceptions are disabled, then running out of
1015 memory is undefined behavior.
1016
1017 Note that the operating system may impose further limits on applications
1018 holding a lot of allocated memory, especially large, contiguous blocks.
1019 Such considerations, the configuration of such behavior or any mitigation
1020 are outside the scope of the QByteArray API.
1021
1022 \section1 C locale and ASCII functions
1023
1024 QByteArray generally handles data as bytes, without presuming any semantics;
1025 where it does presume semantics, it uses the C locale and ASCII encoding.
1026 Standard Unicode encodings are supported by QString, other encodings may be
1027 supported using QStringEncoder and QStringDecoder to convert to Unicode. For
1028 locale-specific interpretation of text, use QLocale or QString.
1029
1030 \section2 C Strings
1031
1032 Traditional C strings, also known as '\\0'-terminated strings, are sequences
1033 of bytes, specified by a start-point and implicitly including each byte up
1034 to, but not including, the first '\\0' byte thereafter. Methods that accept
1035 such a pointer, without a length, will interpret it as this sequence of
1036 bytes. Such a sequence, by construction, cannot contain a '\\0' byte.
1037
1038 Other overloads accept a start-pointer and a byte-count; these use the given
1039 number of bytes, following the start address, regardless of whether any of
1040 them happen to be '\\0' bytes. In some cases, where there is no overload
1041 taking only a pointer, passing a length of -1 will cause the method to use
1042 the offset of the first '\\0' byte after the pointer as the length; a length
1043 of -1 should only be passed if the method explicitly says it does this (in
1044 which case it is typically a default argument).
1045
1046 \section2 Spacing Characters
1047
1048 A frequent requirement is to remove spacing characters from a byte array
1049 (\c{'\n'}, \c{'\t'}, \c{' '}, etc.). If you want to remove spacing from both
1050 ends of a QByteArray, use trimmed(). If you want to also replace each run of
1051 spacing characters with a single space character within the byte array, use
1052 simplified(). Only ASCII spacing characters are recognized for these
1053 purposes.
1054
1055 \section2 Number-String Conversions
1056
1057 Functions that perform conversions between numeric data types and string
1058 representations are performed in the C locale, regardless of the user's
1059 locale settings. Use QLocale to perform locale-aware conversions between
1060 numbers and strings.
1061
1062 \section2 Character Case
1063
1064 In QByteArray, the notion of uppercase and lowercase and of case-independent
1065 comparison is limited to ASCII. Non-ASCII characters are treated as
1066 caseless, since their case depends on encoding. This affects functions that
1067 support a case insensitive option or that change the case of their
1068 arguments. Functions that this affects include compare(), isLower(),
1069 isUpper(), toLower() and toUpper().
1070
1071 This issue does not apply to \l{QString}s since they represent characters
1072 using Unicode.
1073
1074 \sa QByteArrayView, QString, QBitArray
1075*/
1076
1077/*!
1078 \enum QByteArray::Base64Option
1079 \since 5.2
1080
1081 This enum contains the options available for encoding and decoding Base64.
1082 Base64 is defined by \l{RFC 4648}, with the following options:
1083
1084 \value Base64Encoding (default) The regular Base64 alphabet, called simply "base64"
1085 \value Base64UrlEncoding An alternate alphabet, called "base64url", which replaces two
1086 characters in the alphabet to be more friendly to URLs.
1087 \value KeepTrailingEquals (default) Keeps the trailing padding equal signs at the end
1088 of the encoded data, so the data is always a size multiple of
1089 four.
1090 \value OmitTrailingEquals Omits adding the padding equal signs at the end of the encoded
1091 data.
1092 \value IgnoreBase64DecodingErrors When decoding Base64-encoded data, ignores errors
1093 in the input; invalid characters are simply skipped.
1094 This enum value has been added in Qt 5.15.
1095 \value AbortOnBase64DecodingErrors When decoding Base64-encoded data, stops at the first
1096 decoding error.
1097 This enum value has been added in Qt 5.15.
1098
1099 QByteArray::fromBase64Encoding() and QByteArray::fromBase64()
1100 ignore the KeepTrailingEquals and OmitTrailingEquals options. If
1101 the IgnoreBase64DecodingErrors option is specified, they will not
1102 flag errors in case trailing equal signs are missing or if there
1103 are too many of them. If instead the AbortOnBase64DecodingErrors is
1104 specified, then the input must either have no padding or have the
1105 correct amount of equal signs.
1106*/
1107
1108/*! \fn QByteArray::iterator QByteArray::begin()
1109
1110 Returns an \l{STL-style iterators}{STL-style iterator} pointing to the first
1111 byte in the byte-array.
1112
1113//! [iterator-invalidation-func-desc]
1114 \warning The returned iterator is invalidated on detachment or when the
1115 QByteArray is modified.
1116//! [iterator-invalidation-func-desc]
1117
1118 \sa constBegin(), end()
1119*/
1120
1121/*! \fn QByteArray::const_iterator QByteArray::begin() const
1122
1123 \overload begin()
1124*/
1125
1126/*! \fn QByteArray::const_iterator QByteArray::cbegin() const
1127 \since 5.0
1128
1129 Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the
1130 first byte in the byte-array.
1131
1132 \include qbytearray.cpp iterator-invalidation-func-desc
1133
1134 \sa begin(), cend()
1135*/
1136
1137/*! \fn QByteArray::const_iterator QByteArray::constBegin() const
1138
1139 Returns a const \l{STL-style iterators}{STL-style iterator} pointing to the
1140 first byte in the byte-array.
1141
1142 \include qbytearray.cpp iterator-invalidation-func-desc
1143
1144 \sa begin(), constEnd()
1145*/
1146
1147/*! \fn QByteArray::iterator QByteArray::end()
1148
1149 Returns an \l{STL-style iterators}{STL-style iterator} pointing just after
1150 the last byte in the byte-array.
1151
1152 \include qbytearray.cpp iterator-invalidation-func-desc
1153
1154 \sa begin(), constEnd()
1155*/
1156
1157/*! \fn QByteArray::const_iterator QByteArray::end() const
1158
1159 \overload end()
1160*/
1161
1162/*! \fn QByteArray::const_iterator QByteArray::cend() const
1163 \since 5.0
1164
1165 Returns a const \l{STL-style iterators}{STL-style iterator} pointing just
1166 after the last byte in the byte-array.
1167
1168 \include qbytearray.cpp iterator-invalidation-func-desc
1169
1170 \sa cbegin(), end()
1171*/
1172
1173/*! \fn QByteArray::const_iterator QByteArray::constEnd() const
1174
1175 Returns a const \l{STL-style iterators}{STL-style iterator} pointing just
1176 after the last byte in the byte-array.
1177
1178 \include qbytearray.cpp iterator-invalidation-func-desc
1179
1180 \sa constBegin(), end()
1181*/
1182
1183/*! \fn QByteArray::reverse_iterator QByteArray::rbegin()
1184 \since 5.6
1185
1186 Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing to
1187 the first byte in the byte-array, in reverse order.
1188
1189 \include qbytearray.cpp iterator-invalidation-func-desc
1190
1191 \sa begin(), crbegin(), rend()
1192*/
1193
1194/*! \fn QByteArray::const_reverse_iterator QByteArray::rbegin() const
1195 \since 5.6
1196 \overload
1197*/
1198
1199/*! \fn QByteArray::const_reverse_iterator QByteArray::crbegin() const
1200 \since 5.6
1201
1202 Returns a const \l{STL-style iterators}{STL-style} reverse iterator pointing
1203 to the first byte in the byte-array, in reverse order.
1204
1205 \include qbytearray.cpp iterator-invalidation-func-desc
1206
1207 \sa begin(), rbegin(), rend()
1208*/
1209
1210/*! \fn QByteArray::reverse_iterator QByteArray::rend()
1211 \since 5.6
1212
1213 Returns a \l{STL-style iterators}{STL-style} reverse iterator pointing just
1214 after the last byte in the byte-array, in reverse order.
1215
1216 \include qbytearray.cpp iterator-invalidation-func-desc
1217
1218 \sa end(), crend(), rbegin()
1219*/
1220
1221/*! \fn QByteArray::const_reverse_iterator QByteArray::rend() const
1222 \since 5.6
1223 \overload
1224*/
1225
1226/*! \fn QByteArray::const_reverse_iterator QByteArray::crend() const
1227 \since 5.6
1228
1229 Returns a const \l{STL-style iterators}{STL-style} reverse iterator pointing
1230 just after the last byte in the byte-array, in reverse order.
1231
1232 \include qbytearray.cpp iterator-invalidation-func-desc
1233
1234 \sa end(), rend(), rbegin()
1235*/
1236
1237/*! \fn void QByteArray::push_back(const QByteArray &other)
1238
1239 This function is provided for STL compatibility. It is equivalent
1240 to append(\a other).
1241*/
1242
1243/*! \fn void QByteArray::push_back(QByteArrayView str)
1244 \since 6.0
1245 \overload
1246
1247 Same as append(\a str).
1248*/
1249
1250/*! \fn void QByteArray::push_back(const char *str)
1251
1252 \overload
1253
1254 Same as append(\a str).
1255*/
1256
1257/*! \fn void QByteArray::push_back(char ch)
1258
1259 \overload
1260
1261 Same as append(\a ch).
1262*/
1263
1264/*! \fn void QByteArray::push_front(const QByteArray &other)
1265
1266 This function is provided for STL compatibility. It is equivalent
1267 to prepend(\a other).
1268*/
1269
1270/*! \fn void QByteArray::push_front(QByteArrayView str)
1271 \since 6.0
1272 \overload
1273
1274 Same as prepend(\a str).
1275*/
1276
1277/*! \fn void QByteArray::push_front(const char *str)
1278
1279 \overload
1280
1281 Same as prepend(\a str).
1282*/
1283
1284/*! \fn void QByteArray::push_front(char ch)
1285
1286 \overload
1287
1288 Same as prepend(\a ch).
1289*/
1290
1291/*! \fn void QByteArray::shrink_to_fit()
1292 \since 5.10
1293
1294 This function is provided for STL compatibility. It is equivalent to
1295 squeeze().
1296*/
1297
1298/*!
1299 \since 6.1
1300
1301 Removes from the byte array the characters in the half-open range
1302 [ \a first , \a last ). Returns an iterator to the character
1303 referred to by \a last before the erase.
1304*/
1305QByteArray::iterator QByteArray::erase(QByteArray::const_iterator first, QByteArray::const_iterator last)
1306{
1307 const auto start = std::distance(cbegin(), first);
1308 const auto len = std::distance(first, last);
1309 remove(start, len);
1310 return begin() + start;
1311}
1312
1313/*!
1314 \fn QByteArray::iterator QByteArray::erase(QByteArray::const_iterator it)
1315
1316 \overload
1317 \since 6.5
1318
1319 Removes the character denoted by \c it from the byte array.
1320 Returns an iterator to the character immediately after the
1321 erased character.
1322
1323 \code
1324 QByteArray ba = "abcdefg";
1325 auto it = ba.erase(ba.cbegin()); // ba is now "bcdefg" and it points to "b"
1326 \endcode
1327*/
1328
1329/*! \fn QByteArray::QByteArray(const QByteArray &other)
1330
1331 Constructs a copy of \a other.
1332
1333 This operation takes \l{constant time}, because QByteArray is
1334 \l{implicitly shared}. This makes returning a QByteArray from a
1335 function very fast. If a shared instance is modified, it will be
1336 copied (copy-on-write), taking \l{linear time}.
1337
1338 \sa operator=()
1339*/
1340
1341/*!
1342 \fn QByteArray::QByteArray(QByteArray &&other)
1343
1344 Move-constructs a QByteArray instance, making it point at the same
1345 object that \a other was pointing to.
1346
1347 \since 5.2
1348*/
1349
1350/*! \fn QByteArray::QByteArray(QByteArrayDataPtr dd)
1351
1352 \internal
1353
1354 Constructs a byte array pointing to the same data as \a dd.
1355*/
1356
1357/*! \fn QByteArray::~QByteArray()
1358 Destroys the byte array.
1359*/
1360
1361/*!
1362 Assigns \a other to this byte array and returns a reference to
1363 this byte array.
1364*/
1365QByteArray &QByteArray::operator=(const QByteArray & other) noexcept
1366{
1367 d = other.d;
1368 return *this;
1369}
1370
1371
1372/*!
1373 \overload
1374
1375 Assigns \a str to this byte array.
1376
1377 \a str is assumed to point to a null-terminated string, and its length is
1378 determined dynamically.
1379*/
1380
1381QByteArray &QByteArray::operator=(const char *str)
1382{
1383 if (!str) {
1384 d.clear();
1385 } else if (!*str) {
1386 d = DataPointer::fromRawData(&_empty, 0);
1387 } else {
1388 assign(str);
1389 }
1390 return *this;
1391}
1392
1393/*!
1394 \fn QByteArray &QByteArray::operator=(QByteArray &&other)
1395
1396 Move-assigns \a other to this QByteArray instance.
1397
1398 \since 5.2
1399*/
1400
1401/*! \fn void QByteArray::swap(QByteArray &other)
1402 \since 4.8
1403 \memberswap{byte array}
1404*/
1405
1406/*! \fn qsizetype QByteArray::size() const
1407
1408 Returns the number of bytes in this byte array.
1409
1410 The last byte in the byte array is at position size() - 1. In addition,
1411 QByteArray ensures that the byte at position size() is always '\\0', so that
1412 you can use the return value of data() and constData() as arguments to
1413 functions that expect '\\0'-terminated strings. If the QByteArray object was
1414 created from a \l{fromRawData()}{raw data} that didn't include the trailing
1415 '\\0'-termination byte, then QByteArray doesn't add it automatically unless a
1416 \l{deep copy} is created.
1417
1418 Example:
1419 \snippet code/src_corelib_text_qbytearray.cpp 6
1420
1421 \sa isEmpty(), resize()
1422*/
1423
1424/*! \fn qsizetype QByteArray::max_size() const
1425 \fn qsizetype QByteArray::maxSize()
1426 \since 6.8
1427
1428 It returns the maximum number of elements that the byte array can
1429 theoretically hold. In practice, the number can be much smaller,
1430 limited by the amount of memory available to the system.
1431*/
1432
1433/*! \fn bool QByteArray::isEmpty() const
1434
1435 Returns \c true if the byte array has size 0; otherwise returns \c false.
1436
1437 Example:
1438 \snippet code/src_corelib_text_qbytearray.cpp 7
1439
1440 \sa size()
1441*/
1442
1443/*! \fn qsizetype QByteArray::capacity() const
1444
1445 Returns the maximum number of bytes that can be stored in the
1446 byte array without forcing a reallocation.
1447
1448 The sole purpose of this function is to provide a means of fine
1449 tuning QByteArray's memory usage. In general, you will rarely
1450 ever need to call this function. If you want to know how many
1451 bytes are in the byte array, call size().
1452
1453 \note a statically allocated byte array will report a capacity of 0,
1454 even if it's not empty.
1455
1456 \note The free space position in the allocated memory block is undefined. In
1457 other words, one should not assume that the free memory is always located
1458 after the initialized elements.
1459
1460 \sa reserve(), squeeze()
1461*/
1462
1463/*! \fn void QByteArray::reserve(qsizetype size)
1464
1465 Attempts to allocate memory for at least \a size bytes.
1466
1467 If you know in advance how large the byte array will be, you can call
1468 this function, and if you call resize() often you are likely to
1469 get better performance.
1470
1471 If in doubt about how much space shall be needed, it is usually better to
1472 use an upper bound as \a size, or a high estimate of the most likely size,
1473 if a strict upper bound would be much bigger than this. If \a size is an
1474 underestimate, the array will grow as needed once the reserved size is
1475 exceeded, which may lead to a larger allocation than your best overestimate
1476 would have and will slow the operation that triggers it.
1477
1478 \warning reserve() reserves memory but does not change the size of the byte
1479 array. Accessing data beyond the end of the byte array is undefined
1480 behavior. If you need to access memory beyond the current end of the array,
1481 use resize().
1482
1483 The sole purpose of this function is to provide a means of fine
1484 tuning QByteArray's memory usage. In general, you will rarely
1485 ever need to call this function.
1486
1487 \sa squeeze(), capacity()
1488*/
1489
1490/*! \fn void QByteArray::squeeze()
1491
1492 Releases any memory not required to store the array's data.
1493
1494 The sole purpose of this function is to provide a means of fine
1495 tuning QByteArray's memory usage. In general, you will rarely
1496 ever need to call this function.
1497
1498 \sa reserve(), capacity()
1499*/
1500
1501/*! \fn QByteArray::operator const char *() const
1502 \fn QByteArray::operator const void *() const
1503
1504 \note Use constData() instead in new code.
1505
1506 Returns a pointer to the data stored in the byte array. The
1507 pointer can be used to access the bytes that compose the array.
1508 The data is '\\0'-terminated.
1509
1510//! [pointer-invalidation-desc]
1511 The pointer remains valid as long as no detach happens and the QByteArray
1512 is not modified.
1513//! [pointer-invalidation-desc]
1514
1515 This operator is mostly useful to pass a byte array to a function
1516 that accepts a \c{const char *}.
1517
1518 You can disable this operator by defining \c
1519 QT_NO_CAST_FROM_BYTEARRAY when you compile your applications.
1520
1521 Note: A QByteArray can store any byte values including '\\0's,
1522 but most functions that take \c{char *} arguments assume that the
1523 data ends at the first '\\0' they encounter.
1524
1525 \sa constData()
1526*/
1527
1528/*!
1529 \macro QT_NO_CAST_FROM_BYTEARRAY
1530 \relates QByteArray
1531
1532 Disables automatic conversions from QByteArray to
1533 const char * or const void *.
1534
1535 \sa QT_NO_CAST_TO_ASCII, QT_NO_CAST_FROM_ASCII
1536*/
1537
1538/*! \fn char *QByteArray::data()
1539
1540 Returns a pointer to the data stored in the byte array. The pointer can be
1541 used to access and modify the bytes that compose the array. The data is
1542 '\\0'-terminated, i.e. the number of bytes you can access following the
1543 returned pointer is size() + 1, including the '\\0' terminator.
1544
1545 Example:
1546 \snippet code/src_corelib_text_qbytearray.cpp 8
1547
1548 \include qbytearray.cpp pointer-invalidation-desc
1549
1550 For read-only access, constData() is faster because it never
1551 causes a \l{deep copy} to occur.
1552
1553 This function is mostly useful to pass a byte array to a function
1554 that accepts a \c{const char *}.
1555
1556 The following example makes a copy of the char* returned by
1557 data(), but it will corrupt the heap and cause a crash because it
1558 does not allocate a byte for the '\\0' at the end:
1559
1560 \snippet code/src_corelib_text_qbytearray.cpp 46
1561
1562 This one allocates the correct amount of space:
1563
1564 \snippet code/src_corelib_text_qbytearray.cpp 47
1565
1566 Note: A QByteArray can store any byte values including '\\0's,
1567 but most functions that take \c{char *} arguments assume that the
1568 data ends at the first '\\0' they encounter.
1569
1570 \sa constData(), operator[]()
1571*/
1572
1573/*! \fn const char *QByteArray::data() const
1574
1575 \overload
1576*/
1577
1578/*! \fn const char *QByteArray::constData() const
1579
1580 Returns a pointer to the const data stored in the byte array. The pointer
1581 can be used to access the bytes that compose the array. The data is
1582 '\\0'-terminated unless the QByteArray object was created from raw data.
1583
1584 \include qbytearray.cpp pointer-invalidation-desc
1585
1586 This function is mostly useful to pass a byte array to a function
1587 that accepts a \c{const char *}.
1588
1589 Note: A QByteArray can store any byte values including '\\0's,
1590 but most functions that take \c{char *} arguments assume that the
1591 data ends at the first '\\0' they encounter.
1592
1593 \sa data(), operator[](), fromRawData()
1594*/
1595
1596/*! \fn void QByteArray::detach()
1597
1598 \internal
1599*/
1600
1601/*! \fn bool QByteArray::isDetached() const
1602
1603 \internal
1604*/
1605
1606/*! \fn bool QByteArray::isSharedWith(const QByteArray &other) const
1607
1608 \internal
1609*/
1610
1611/*! \fn char QByteArray::at(qsizetype i) const
1612
1613 Returns the byte at index position \a i in the byte array.
1614
1615 \a i must be a valid index position in the byte array (i.e., 0 <=
1616 \a i < size()).
1617
1618 \sa operator[]()
1619*/
1620
1621/*! \fn char &QByteArray::operator[](qsizetype i)
1622
1623 Returns the byte at index position \a i as a modifiable reference.
1624
1625 \a i must be a valid index position in the byte array (i.e., 0 <=
1626 \a i < size()).
1627
1628 Example:
1629 \snippet code/src_corelib_text_qbytearray.cpp 9
1630
1631 \sa at()
1632*/
1633
1634/*! \fn char QByteArray::operator[](qsizetype i) const
1635
1636 \overload
1637
1638 Same as at(\a i).
1639*/
1640
1641/*!
1642 \fn char QByteArray::front() const
1643 \since 5.10
1644
1645 Returns the first byte in the byte array.
1646 Same as \c{at(0)}.
1647
1648 This function is provided for STL compatibility.
1649
1650 \warning Calling this function on an empty byte array constitutes
1651 undefined behavior.
1652
1653 \sa back(), at(), operator[]()
1654*/
1655
1656/*!
1657 \fn char QByteArray::back() const
1658 \since 5.10
1659
1660 Returns the last byte in the byte array.
1661 Same as \c{at(size() - 1)}.
1662
1663 This function is provided for STL compatibility.
1664
1665 \warning Calling this function on an empty byte array constitutes
1666 undefined behavior.
1667
1668 \sa front(), at(), operator[]()
1669*/
1670
1671/*!
1672 \fn char &QByteArray::front()
1673 \since 5.10
1674
1675 Returns a reference to the first byte in the byte array.
1676 Same as \c{operator[](0)}.
1677
1678 This function is provided for STL compatibility.
1679
1680 \warning Calling this function on an empty byte array constitutes
1681 undefined behavior.
1682
1683 \sa back(), at(), operator[]()
1684*/
1685
1686/*!
1687 \fn char &QByteArray::back()
1688 \since 5.10
1689
1690 Returns a reference to the last byte in the byte array.
1691 Same as \c{operator[](size() - 1)}.
1692
1693 This function is provided for STL compatibility.
1694
1695 \warning Calling this function on an empty byte array constitutes
1696 undefined behavior.
1697
1698 \sa front(), at(), operator[]()
1699*/
1700
1701/*! \fn bool QByteArray::contains(QByteArrayView bv) const
1702 \since 6.0
1703
1704 Returns \c true if this byte array contains an occurrence of the
1705 sequence of bytes viewed by \a bv; otherwise returns \c false.
1706
1707 \sa indexOf(), count()
1708*/
1709
1710/*! \fn bool QByteArray::contains(char ch) const
1711
1712 \overload
1713
1714 Returns \c true if the byte array contains the byte \a ch;
1715 otherwise returns \c false.
1716*/
1717
1718/*!
1719
1720 Truncates the byte array at index position \a pos.
1721
1722 If \a pos is beyond the end of the array, nothing happens.
1723
1724 Example:
1725 \snippet code/src_corelib_text_qbytearray.cpp 10
1726
1727 \sa chop(), resize(), first()
1728*/
1729void QByteArray::truncate(qsizetype pos)
1730{
1731 if (pos < size())
1732 resize(pos);
1733}
1734
1735/*!
1736
1737 Removes \a n bytes from the end of the byte array.
1738
1739 If \a n is greater than size(), the result is an empty byte
1740 array.
1741
1742 Example:
1743 \snippet code/src_corelib_text_qbytearray.cpp 11
1744
1745 \sa truncate(), resize(), first()
1746*/
1747
1748void QByteArray::chop(qsizetype n)
1749{
1750 if (n > 0)
1751 resize(size() - n);
1752}
1753
1754
1755/*! \fn QByteArray &QByteArray::operator+=(const QByteArray &ba)
1756
1757 Appends the byte array \a ba onto the end of this byte array and
1758 returns a reference to this byte array.
1759
1760 Example:
1761 \snippet code/src_corelib_text_qbytearray.cpp 12
1762
1763 Note: QByteArray is an \l{implicitly shared} class. Consequently,
1764 if you append to an empty byte array, then the byte array will just
1765 share the data held in \a ba. In this case, no copying of data is done,
1766 taking \l{constant time}. If a shared instance is modified, it will
1767 be copied (copy-on-write), taking \l{linear time}.
1768
1769 If the byte array being appended to is not empty, a deep copy of the
1770 data is performed, taking \l{linear time}.
1771
1772 This operation typically does not suffer from allocation overhead,
1773 because QByteArray preallocates extra space at the end of the data
1774 so that it may grow without reallocating for each append operation.
1775
1776 \sa append(), prepend()
1777*/
1778
1779/*! \fn QByteArray &QByteArray::operator+=(const char *str)
1780
1781 \overload
1782
1783 Appends the '\\0'-terminated string \a str onto the end of this byte array
1784 and returns a reference to this byte array.
1785*/
1786
1787/*! \fn QByteArray &QByteArray::operator+=(char ch)
1788
1789 \overload
1790
1791 Appends the byte \a ch onto the end of this byte array and returns a
1792 reference to this byte array.
1793*/
1794
1795/*! \fn qsizetype QByteArray::length() const
1796
1797 Same as size().
1798*/
1799
1800/*! \fn bool QByteArray::isNull() const
1801
1802 Returns \c true if this byte array is null; otherwise returns \c false.
1803
1804 Example:
1805 \snippet code/src_corelib_text_qbytearray.cpp 13
1806
1807 Qt makes a distinction between null byte arrays and empty byte
1808 arrays for historical reasons. For most applications, what
1809 matters is whether or not a byte array contains any data,
1810 and this can be determined using isEmpty().
1811
1812 \sa isEmpty()
1813*/
1814
1815/*! \fn QByteArray::QByteArray()
1816
1817 Constructs an empty byte array.
1818
1819 \sa isEmpty()
1820*/
1821
1822/*!
1823 Constructs a byte array containing the first \a size bytes of
1824 array \a data.
1825
1826 If \a data is 0, a null byte array is constructed.
1827
1828 If \a size is negative, \a data is assumed to point to a '\\0'-terminated
1829 string and its length is determined dynamically.
1830
1831 QByteArray makes a deep copy of the string data.
1832
1833 \sa fromRawData()
1834*/
1835
1836QByteArray::QByteArray(const char *data, qsizetype size)
1837{
1838 if (!data) {
1839 d = DataPointer();
1840 } else {
1841 if (size < 0)
1842 size = qstrlen(data);
1843 if (!size) {
1844 d = DataPointer::fromRawData(&_empty, 0);
1845 } else {
1846 d = DataPointer(size, size);
1847 Q_CHECK_PTR(d.data());
1848 memcpy(d.data(), data, size);
1849 d.data()[size] = '\0';
1850 }
1851 }
1852}
1853
1854/*!
1855 Constructs a byte array of size \a size with every byte set to \a ch.
1856
1857 \sa fill()
1858*/
1859
1860QByteArray::QByteArray(qsizetype size, char ch)
1861{
1862 if (size <= 0) {
1863 d = DataPointer::fromRawData(&_empty, 0);
1864 } else {
1865 d = DataPointer(size, size);
1866 Q_CHECK_PTR(d.data());
1867 memset(d.data(), ch, size);
1868 d.data()[size] = '\0';
1869 }
1870}
1871
1872/*!
1873 Constructs a byte array of size \a size with uninitialized contents.
1874
1875 For example:
1876 \code
1877 QByteArray buffer(123, Qt::Uninitialized);
1878 \endcode
1879*/
1880
1881QByteArray::QByteArray(qsizetype size, Qt::Initialization)
1882{
1883 if (size <= 0) {
1884 d = DataPointer::fromRawData(&_empty, 0);
1885 } else {
1886 d = DataPointer(size, size);
1887 Q_CHECK_PTR(d.data());
1888 d.data()[size] = '\0';
1889 }
1890}
1891
1892/*!
1893 \fn QByteArray::QByteArray(QByteArrayView v)
1894 \since 6.8
1895
1896 Constructs a byte array initialized with the byte array view's data.
1897
1898 The QByteArray will be null if and only if \a v is null.
1899*/
1900
1901/*!
1902 Sets the size of the byte array to \a size bytes.
1903
1904 If \a size is greater than the current size, the byte array is
1905 extended to make it \a size bytes with the extra bytes added to
1906 the end. The new bytes are uninitialized.
1907
1908 If \a size is less than the current size, bytes beyond position
1909 \a size are excluded from the byte array.
1910
1911 \note While resize() will grow the capacity if needed, it never shrinks
1912 capacity. To shed excess capacity, use squeeze().
1913
1914 \sa size(), truncate(), squeeze()
1915*/
1916void QByteArray::resize(qsizetype size)
1917{
1918 if (size < 0)
1919 size = 0;
1920
1921 const auto capacityAtEnd = capacity() - d.freeSpaceAtBegin();
1922 if (d->needsDetach() || size > capacityAtEnd)
1923 reallocData(size, QArrayData::Grow);
1924 d.size = size;
1925 if (d->allocatedCapacity())
1926 d.data()[size] = 0;
1927}
1928
1929/*!
1930 \since 6.4
1931
1932 Sets the size of the byte array to \a newSize bytes.
1933
1934 If \a newSize is greater than the current size, the byte array is
1935 extended to make it \a newSize bytes with the extra bytes added to
1936 the end. The new bytes are initialized to \a c.
1937
1938 If \a newSize is less than the current size, bytes beyond position
1939 \a newSize are excluded from the byte array.
1940
1941 \note While resize() will grow the capacity if needed, it never shrinks
1942 capacity. To shed excess capacity, use squeeze().
1943
1944 \sa size(), truncate(), squeeze()
1945*/
1946void QByteArray::resize(qsizetype newSize, char c)
1947{
1948 const auto old = d.size;
1949 resize(newSize);
1950 if (old < d.size)
1951 memset(d.data() + old, c, d.size - old);
1952}
1953
1954/*!
1955 \since 6.8
1956
1957 Resizes the byte array to \a size bytes. If the size of the
1958 byte array grows, the new bytes are uninitialized.
1959
1960 The behavior is identical to \c{resize(size)}.
1961
1962 \sa resize()
1963*/
1964void QByteArray::resizeForOverwrite(qsizetype size)
1965{
1966 resize(size);
1967}
1968
1969/*!
1970 Sets every byte in the byte array to \a ch. If \a size is different from -1
1971 (the default), the byte array is resized to size \a size beforehand.
1972
1973 Example:
1974 \snippet code/src_corelib_text_qbytearray.cpp 14
1975
1976 \sa resize()
1977*/
1978
1979QByteArray &QByteArray::fill(char ch, qsizetype size)
1980{
1981 resize(size < 0 ? this->size() : size);
1982 if (this->size())
1983 memset(d.data(), ch, this->size());
1984 return *this;
1985}
1986
1987void QByteArray::reallocData(qsizetype alloc, QArrayData::AllocationOption option)
1988{
1989 if (!alloc) {
1990 d = DataPointer::fromRawData(&_empty, 0);
1991 return;
1992 }
1993
1994 // don't use reallocate path when reducing capacity and there's free space
1995 // at the beginning: might shift data pointer outside of allocated space
1996 const bool cannotUseReallocate = d.freeSpaceAtBegin() > 0;
1997
1998 if (d->needsDetach() || cannotUseReallocate) {
1999 DataPointer dd(alloc, qMin(alloc, d.size), option);
2000 Q_CHECK_PTR(dd.data());
2001 if (dd.size > 0)
2002 ::memcpy(dd.data(), d.data(), dd.size);
2003 dd.data()[dd.size] = 0;
2004 d.swap(dd);
2005 } else {
2006 d->reallocate(alloc, option);
2007 }
2008}
2009
2010void QByteArray::reallocGrowData(qsizetype n)
2011{
2012 if (!n) // expected to always allocate
2013 n = 1;
2014
2015 if (d->needsDetach()) {
2016 DataPointer dd(DataPointer::allocateGrow(d, n, QArrayData::GrowsAtEnd));
2017 Q_CHECK_PTR(dd.data());
2018 dd->copyAppend(d.data(), d.data() + d.size);
2019 dd.data()[dd.size] = 0;
2020 d.swap(dd);
2021 } else {
2022 d->reallocate(d.constAllocatedCapacity() + n, QArrayData::Grow);
2023 }
2024}
2025
2026void QByteArray::expand(qsizetype i)
2027{
2028 resize(qMax(i + 1, size()));
2029}
2030
2031/*!
2032 \since 6.10
2033
2034 If this byte array's data isn't null-terminated, this method will make
2035 a deep-copy of the data and make it null-terminated.
2036
2037 A QByteArray is null-terminated by default, however in some cases
2038 (e.g. when using fromRawData()), the data doesn't necessarily end with
2039 a \c {\0} character, which could be a problem when calling methods that
2040 expect a null-terminated string (for example, C API).
2041
2042 \sa nullTerminated(), fromRawData(), setRawData()
2043*/
2044QByteArray &QByteArray::nullTerminate()
2045{
2046 // Ensure \0-termination for fromRawData() byte arrays
2047 if (!d.isMutable())
2048 *this = QByteArray{constData(), size()};
2049 return *this;
2050}
2051
2052/*!
2053 \fn QByteArray QByteArray::nullTerminated() const &
2054 \fn QByteArray QByteArray::nullTerminated() &&
2055 \since 6.10
2056
2057 Returns a copy of this byte array that is always null-terminated.
2058 See nullTerminate().
2059
2060 \sa nullTerminate(), fromRawData(), setRawData()
2061*/
2062QByteArray QByteArray::nullTerminated() const &
2063{
2064 // Ensure \0-termination for fromRawData() byte arrays
2065 if (!d.isMutable())
2066 return QByteArray{constData(), size()};
2067 return *this;
2068}
2069
2070QByteArray QByteArray::nullTerminated() &&
2071{
2072 nullTerminate();
2073 return std::move(*this);
2074}
2075
2076/*!
2077 \fn QByteArray &QByteArray::prepend(QByteArrayView ba)
2078
2079 Prepends the byte array view \a ba to this byte array and returns a
2080 reference to this byte array.
2081
2082 This operation is typically very fast (\l{constant time}), because
2083 QByteArray preallocates extra space at the beginning of the data,
2084 so it can grow without reallocating the entire array each time.
2085
2086 Example:
2087 \snippet code/src_corelib_text_qbytearray.cpp 15
2088
2089 This is the same as insert(0, \a ba).
2090
2091 \sa append(), insert()
2092*/
2093
2094/*!
2095 \fn QByteArray &QByteArray::prepend(const QByteArray &ba)
2096 \overload
2097
2098 Prepends \a ba to this byte array.
2099*/
2101{
2102 if (size() == 0 && ba.size() > d.constAllocatedCapacity() && ba.d.isMutable())
2103 return (*this = ba);
2104 return prepend(QByteArrayView(ba));
2105}
2106
2107/*!
2108 \fn QByteArray &QByteArray::prepend(const char *str)
2109 \overload
2110
2111 Prepends the '\\0'-terminated string \a str to this byte array.
2112*/
2113
2114/*!
2115 \fn QByteArray &QByteArray::prepend(const char *str, qsizetype len)
2116 \overload
2117 \since 4.6
2118
2119 Prepends \a len bytes starting at \a str to this byte array.
2120 The bytes prepended may include '\\0' bytes.
2121*/
2122
2123/*! \fn QByteArray &QByteArray::prepend(qsizetype count, char ch)
2124
2125 \overload
2126 \since 5.7
2127
2128 Prepends \a count copies of byte \a ch to this byte array.
2129*/
2130
2131/*!
2132 \fn QByteArray &QByteArray::prepend(char ch)
2133 \overload
2134
2135 Prepends the byte \a ch to this byte array.
2136*/
2137
2138/*!
2139 Appends the byte array \a ba onto the end of this byte array.
2140
2141 Example:
2142 \snippet code/src_corelib_text_qbytearray.cpp 16
2143
2144 This is the same as insert(size(), \a ba).
2145
2146 Note: QByteArray is an \l{implicitly shared} class. Consequently,
2147 if you append to an empty byte array, then the byte array will just
2148 share the data held in \a ba. In this case, no copying of data is done,
2149 taking \l{constant time}. If a shared instance is modified, it will
2150 be copied (copy-on-write), taking \l{linear time}.
2151
2152 If the byte array being appended to is not empty, a deep copy of the
2153 data is performed, taking \l{linear time}.
2154
2155 The append() function is typically very fast (\l{constant time}),
2156 because QByteArray preallocates extra space at the end of the data,
2157 so it can grow without reallocating the entire array each time.
2158
2159 \sa operator+=(), prepend(), insert()
2160*/
2161
2163{
2164 if (!ba.isNull()) {
2165 if (isNull()) {
2166 if (Q_UNLIKELY(!ba.d.isMutable()))
2167 assign(ba); // fromRawData, so we do a deep copy
2168 else
2169 operator=(ba);
2170 } else if (ba.size()) {
2171 append(QByteArrayView(ba));
2172 }
2173 }
2174 return *this;
2175}
2176
2177/*!
2178 \fn QByteArray &QByteArray::append(QByteArrayView data)
2179 \overload
2180
2181 Appends \a data to this byte array.
2182*/
2183
2184/*!
2185 \fn QByteArray& QByteArray::append(const char *str)
2186 \overload
2187
2188 Appends the '\\0'-terminated string \a str to this byte array.
2189*/
2190
2191/*!
2192 \fn QByteArray &QByteArray::append(const char *str, qsizetype len)
2193 \overload
2194
2195 Appends the first \a len bytes starting at \a str to this byte array and
2196 returns a reference to this byte array. The bytes appended may include '\\0'
2197 bytes.
2198
2199 If \a len is negative, \a str will be assumed to be a '\\0'-terminated
2200 string and the length to be copied will be determined automatically using
2201 qstrlen().
2202
2203 If \a len is zero or \a str is null, nothing is appended to the byte
2204 array. Ensure that \a len is \e not longer than \a str.
2205*/
2206
2207/*! \fn QByteArray &QByteArray::append(qsizetype count, char ch)
2208
2209 \overload
2210 \since 5.7
2211
2212 Appends \a count copies of byte \a ch to this byte array and returns a
2213 reference to this byte array.
2214
2215 If \a count is negative or zero nothing is appended to the byte array.
2216*/
2217
2218/*!
2219 \overload
2220
2221 Appends the byte \a ch to this byte array.
2222*/
2223
2224QByteArray& QByteArray::append(char ch)
2225{
2226 d.detachAndGrow(QArrayData::GrowsAtEnd, 1, nullptr, nullptr);
2227 d->copyAppend(1, ch);
2228 d.data()[d.size] = '\0';
2229 return *this;
2230}
2231
2232/*!
2233 \fn QByteArray &QByteArray::assign(QByteArrayView v)
2234 \since 6.6
2235
2236 Replaces the contents of this byte array with a copy of \a v and returns a
2237 reference to this byte array.
2238
2239 The size of this byte array will be equal to the size of \a v.
2240
2241 This function only allocates memory if the size of \a v exceeds the capacity
2242 of this byte array or this byte array is shared.
2243*/
2244
2245/*!
2246 \fn QByteArray &QByteArray::assign(qsizetype n, char c)
2247 \since 6.6
2248
2249 Replaces the contents of this byte array with \a n copies of \a c and
2250 returns a reference to this byte array.
2251
2252 The size of this byte array will be equal to \a n, which has to be non-negative.
2253
2254 This function will only allocate memory if \a n exceeds the capacity of this
2255 byte array or this byte array is shared.
2256
2257 \sa fill()
2258*/
2259
2260/*!
2261 \fn template <typename InputIterator, QByteArray::if_input_iterator<InputIterator>> QByteArray &QByteArray::assign(InputIterator first, InputIterator last)
2262 \since 6.6
2263
2264 Replaces the contents of this byte array with a copy of the elements in the
2265 iterator range [\a first, \a last) and returns a reference to this
2266 byte array.
2267
2268 The size of this byte array will be equal to the number of elements in the
2269 range [\a first, \a last).
2270
2271 This function will only allocate memory if the number of elements in the
2272 range exceeds the capacity of this byte array or this byte array is shared.
2273
2274 \note The behavior is undefined if either argument is an iterator into *this or
2275 [\a first, \a last) is not a valid range.
2276
2277 \constraints \c InputIterator meets the requirements of a
2278 \l {https://en.cppreference.com/w/cpp/named_req/InputIterator} {LegacyInputIterator}.
2279*/
2280
2281QByteArray &QByteArray::assign(QByteArrayView v)
2282{
2283 const auto len = v.size();
2284
2285 if (len <= capacity() && isDetached()) {
2286 const auto offset = d.freeSpaceAtBegin();
2287 if (offset)
2288 d.setBegin(d.begin() - offset);
2289 std::memcpy(d.begin(), v.data(), len);
2290 d.size = len;
2291 d.data()[d.size] = '\0';
2292 } else {
2293 *this = v.toByteArray();
2294 }
2295 return *this;
2296}
2297
2298/*!
2299 Inserts \a data at index position \a i and returns a
2300 reference to this byte array.
2301
2302 Example:
2303 \snippet code/src_corelib_text_qbytearray.cpp 17
2304 \since 6.0
2305
2306 For large byte arrays, this operation can be slow (\l{linear time}),
2307 because it requires moving all the bytes at indexes \a i and
2308 above by at least one position further in memory.
2309
2310//! [array-grow-at-insertion]
2311 This array grows to accommodate the insertion. If \a i is beyond
2312 the end of the array, the array is first extended with space characters
2313 to reach this \a i.
2314//! [array-grow-at-insertion]
2315
2316 \sa append(), prepend(), replace(), remove()
2317*/
2318QByteArray &QByteArray::insert(qsizetype i, QByteArrayView data)
2319{
2320 const char *str = data.data();
2321 qsizetype size = data.size();
2322 if (i < 0 || size <= 0)
2323 return *this;
2324
2325 // handle this specially, as QArrayDataOps::insert() doesn't handle out of
2326 // bounds positions
2327 if (i >= d->size) {
2328 // In case when data points into the range or is == *this, we need to
2329 // defer a call to free() so that it comes after we copied the data from
2330 // the old memory:
2331 DataPointer detached{}; // construction is free
2332 d.detachAndGrow(Data::GrowsAtEnd, (i - d.size) + size, &str, &detached);
2333 Q_CHECK_PTR(d.data());
2334 d->copyAppend(i - d->size, ' ');
2335 d->copyAppend(str, str + size);
2336 d.data()[d.size] = '\0';
2337 return *this;
2338 }
2339
2340 if (!d->needsDetach() && QtPrivate::q_points_into_range(str, d)) {
2341 QVarLengthArray a(str, str + size);
2342 return insert(i, a);
2343 }
2344
2345 d->insert(i, str, size);
2346 d.data()[d.size] = '\0';
2347 return *this;
2348}
2349
2350/*!
2351 \fn QByteArray &QByteArray::insert(qsizetype i, const QByteArray &data)
2352 Inserts \a data at index position \a i and returns a
2353 reference to this byte array.
2354
2355 \include qbytearray.cpp array-grow-at-insertion
2356
2357 \sa append(), prepend(), replace(), remove()
2358*/
2359
2360/*!
2361 \fn QByteArray &QByteArray::insert(qsizetype i, const char *s)
2362 Inserts \a s at index position \a i and returns a
2363 reference to this byte array.
2364
2365 \include qbytearray.cpp array-grow-at-insertion
2366
2367 The function is equivalent to \c{insert(i, QByteArrayView(s))}
2368
2369 \sa append(), prepend(), replace(), remove()
2370*/
2371
2372/*!
2373 \fn QByteArray &QByteArray::insert(qsizetype i, const char *data, qsizetype len)
2374 \overload
2375 \since 4.6
2376
2377 Inserts \a len bytes, starting at \a data, at position \a i in the byte
2378 array.
2379
2380 \include qbytearray.cpp array-grow-at-insertion
2381*/
2382
2383/*!
2384 \fn QByteArray &QByteArray::insert(qsizetype i, char ch)
2385 \overload
2386
2387 Inserts byte \a ch at index position \a i in the byte array.
2388
2389 \include qbytearray.cpp array-grow-at-insertion
2390*/
2391
2392/*! \fn QByteArray &QByteArray::insert(qsizetype i, qsizetype count, char ch)
2393
2394 \overload
2395 \since 5.7
2396
2397 Inserts \a count copies of byte \a ch at index position \a i in the byte
2398 array.
2399
2400 \include qbytearray.cpp array-grow-at-insertion
2401*/
2402
2403QByteArray &QByteArray::insert(qsizetype i, qsizetype count, char ch)
2404{
2405 if (i < 0 || count <= 0)
2406 return *this;
2407
2408 if (i >= d->size) {
2409 // handle this specially, as QArrayDataOps::insert() doesn't handle out of bounds positions
2410 d.detachAndGrow(Data::GrowsAtEnd, (i - d.size) + count, nullptr, nullptr);
2411 Q_CHECK_PTR(d.data());
2412 d->copyAppend(i - d->size, ' ');
2413 d->copyAppend(count, ch);
2414 d.data()[d.size] = '\0';
2415 return *this;
2416 }
2417
2418 d->insert(i, count, ch);
2419 d.data()[d.size] = '\0';
2420 return *this;
2421}
2422
2423/*!
2424 Removes \a len bytes from the array, starting at index position \a
2425 pos, and returns a reference to the array.
2426
2427 If \a pos is out of range, nothing happens. If \a pos is valid,
2428 but \a pos + \a len is larger than the size of the array, the
2429 array is truncated at position \a pos.
2430
2431 Example:
2432 \snippet code/src_corelib_text_qbytearray.cpp 18
2433
2434 Element removal will preserve the array's capacity and not reduce the
2435 amount of allocated memory. To shed extra capacity and free as much memory
2436 as possible, call squeeze() after the last change to the array's size.
2437
2438 \sa insert(), replace(), squeeze()
2439*/
2440
2441QByteArray &QByteArray::remove(qsizetype pos, qsizetype len)
2442{
2443 if (len <= 0 || pos < 0 || size_t(pos) >= size_t(size()))
2444 return *this;
2445 if (pos + len > d->size)
2446 len = d->size - pos;
2447
2448 const auto toRemove_start = d.begin() + pos;
2449 if (!d->isShared()) {
2450 d->erase(toRemove_start, len);
2451 d.data()[d.size] = '\0';
2452 } else {
2453 QByteArray copy{size() - len, Qt::Uninitialized};
2454 copy.d->copyRanges({{d.begin(), toRemove_start},
2455 {toRemove_start + len, d.end()}});
2456 swap(copy);
2457 }
2458 return *this;
2459}
2460
2461/*!
2462 \fn QByteArray &QByteArray::removeAt(qsizetype pos)
2463
2464 \since 6.5
2465
2466 Removes the character at index \a pos. If \a pos is out of bounds
2467 (i.e. \a pos >= size()) this function does nothing.
2468
2469 \sa remove()
2470*/
2471
2472/*!
2473 \fn QByteArray &QByteArray::removeFirst()
2474
2475 \since 6.5
2476
2477 Removes the first character in this byte array. If the byte array is empty,
2478 this function does nothing.
2479
2480 \sa remove()
2481*/
2482/*!
2483 \fn QByteArray &QByteArray::removeLast()
2484
2485 \since 6.5
2486
2487 Removes the last character in this byte array. If the byte array is empty,
2488 this function does nothing.
2489
2490 \sa remove()
2491*/
2492
2493/*!
2494 \fn template <typename Predicate> QByteArray &QByteArray::removeIf(Predicate pred)
2495 \since 6.1
2496
2497 Removes all bytes for which the predicate \a pred returns true
2498 from the byte array. Returns a reference to the byte array.
2499
2500 \sa remove()
2501*/
2502
2503/*!
2504 Replaces \a len bytes from index position \a pos with the byte
2505 array \a after, and returns a reference to this byte array.
2506
2507 Example:
2508 \snippet code/src_corelib_text_qbytearray.cpp 19
2509
2510 \sa insert(), remove()
2511*/
2512
2513QByteArray &QByteArray::replace(qsizetype pos, qsizetype len, QByteArrayView after)
2514{
2515 if (size_t(pos) > size_t(this->size()))
2516 return *this;
2517 if (len > this->size() - pos)
2518 len = this->size() - pos;
2519 // Historic behavior, negative len was the equivalent of:
2520 // remove(pos, len); // does nothing
2521 // insert(pos, after);
2522 if (len <= 0)
2523 return insert(pos, after);
2524
2525 if (after.isEmpty())
2526 return remove(pos, len);
2527
2528 using A = QStringAlgorithms<QByteArray>;
2529 const qsizetype newlen = A::newSize(*this, len, after, {pos});
2530 if (data_ptr().needsDetach() || A::needsReallocate(*this, newlen)) {
2531 A::replace_into_copy(*this, len, after, {pos}, newlen);
2532 return *this;
2533 }
2534
2535 // No detaching or reallocation -> change in-place
2536 char *const begin = data_ptr().data(); // data(), without the detach() check
2537 char *const before = begin + pos;
2538 const char *beforeEnd = before + len;
2539 if (len >= after.size()) {
2540 memmove(before , after.cbegin(), after.size()); // sizeof(char) == 1
2541
2542 if (len > after.size()) {
2543 memmove(before + after.size(), beforeEnd, d.size - (beforeEnd - begin));
2544 A::setSize(*this, newlen);
2545 }
2546 } else { // len < after.size()
2547 char *oldEnd = begin + d.size;
2548 const qsizetype adjust = newlen - d.size;
2549 A::setSize(*this, newlen);
2550
2551 QByteArrayView tail{beforeEnd, oldEnd};
2552 QByteArrayView prefix = after;
2553 QByteArrayView suffix;
2554 if (QtPrivate::q_points_into_range(after.cend() - 1, tail)) {
2555 if (QtPrivate::q_points_into_range(after.cbegin(), tail)) {
2556 // `after` fully contained inside `tail`
2557 prefix = {};
2558 suffix = QByteArrayView{after.cbegin(), after.cend()};
2559 } else { // after.cbegin() is in [begin, beforeEnd)
2560 prefix = QByteArrayView{after.cbegin(), beforeEnd};
2561 suffix = QByteArrayView{beforeEnd, after.cend()};
2562 }
2563 }
2564 memmove(before + after.size(), tail.cbegin(), tail.size());
2565 if (!prefix.isEmpty())
2566 memmove(before, prefix.cbegin(), prefix.size()); // `prefix` may overlap `before`
2567 if (!suffix.isEmpty()) // adjust suffix after calling memcpy() above
2568 memcpy(before + prefix.size(), suffix.cbegin() + adjust, suffix.size()); // no overlap
2569 }
2570 return *this;
2571}
2572
2573/*! \fn QByteArray &QByteArray::replace(qsizetype pos, qsizetype len, const char *after, qsizetype alen)
2574
2575 \overload
2576
2577 Replaces \a len bytes from index position \a pos with \a alen bytes starting
2578 at position \a after. The bytes inserted may include '\\0' bytes.
2579
2580 \since 4.7
2581*/
2582
2583/*!
2584 \fn QByteArray &QByteArray::replace(const char *before, qsizetype bsize, const char *after, qsizetype asize)
2585 \overload
2586
2587 Replaces every occurrence of the \a bsize bytes starting at \a before with
2588 the \a asize bytes starting at \a after. Since the sizes of the strings are
2589 given by \a bsize and \a asize, they may contain '\\0' bytes and do not need
2590 to be '\\0'-terminated.
2591*/
2592
2593/*!
2594 \overload
2595 \since 6.0
2596
2597 Replaces every occurrence of the byte array \a before with the
2598 byte array \a after.
2599
2600 Example:
2601 \snippet code/src_corelib_text_qbytearray.cpp 20
2602*/
2603
2604QByteArray &QByteArray::replace(QByteArrayView before, QByteArrayView after)
2605{
2606 const char *b = before.data();
2607 qsizetype bsize = before.size();
2608 const char *a = after.data();
2609 qsizetype asize = after.size();
2610
2611 if (isEmpty()) {
2612 if (bsize)
2613 return *this;
2614 } else {
2615 if (b == a && bsize == asize)
2616 return *this;
2617 }
2618 if (asize == 0 && bsize == 0)
2619 return *this;
2620
2621 if (bsize == 1 && asize == 1)
2622 return replace(*b, *a); // use the fast char-char algorithm
2623
2624 // protect against `after` being part of this
2625 std::string pinnedReplacement;
2626 if (QtPrivate::q_points_into_range(a, d)) {
2627 pinnedReplacement.assign(a, a + asize);
2628 after = pinnedReplacement;
2629 }
2630
2631 QByteArrayMatcher matcher(b, bsize);
2632 // - create a table of replacement positions
2633 // - figure out the needed size; modify in place; or allocate a new byte array
2634 // and copy characters to it as needed
2635 // - do the replacements
2636 QVarLengthArray<qsizetype> indices;
2637 qsizetype index = 0;
2638 while ((index = matcher.indexIn(*this, index)) != -1) {
2639 indices.push_back(index);
2640 if (bsize > 0)
2641 index += bsize; // Step over before
2642 else
2643 ++index; // avoid infinite loop
2644 }
2645
2646 QStringAlgorithms<QByteArray>::replace_helper(*this, bsize, after, indices);
2647 return *this;
2648}
2649
2650/*!
2651 \fn QByteArray &QByteArray::replace(char before, QByteArrayView after)
2652 \overload
2653
2654 Replaces every occurrence of the byte \a before with the byte array \a
2655 after.
2656*/
2657
2658/*!
2659 \overload
2660
2661 Replaces every occurrence of the byte \a before with the byte \a after.
2662*/
2663
2664QByteArray &QByteArray::replace(char before, char after)
2665{
2666 if (before != after) {
2667 if (const auto pos = indexOf(before); pos >= 0) {
2668 if (d.needsDetach()) {
2669 QByteArray tmp(size(), Qt::Uninitialized);
2670 auto dst = tmp.d.data();
2671 dst = std::copy(d.data(), d.data() + pos, dst);
2672 *dst++ = after;
2673 std::replace_copy(d.data() + pos + 1, d.end(), dst, before, after);
2674 swap(tmp);
2675 } else {
2676 // in-place
2677 d.data()[pos] = after;
2678 std::replace(d.data() + pos + 1, d.end(), before, after);
2679 }
2680 }
2681 }
2682 return *this;
2683}
2684
2685/*!
2686 Splits the byte array into subarrays wherever \a sep occurs, and
2687 returns the list of those arrays. If \a sep does not match
2688 anywhere in the byte array, split() returns a single-element list
2689 containing this byte array.
2690*/
2691
2692QList<QByteArray> QByteArray::split(char sep) const
2693{
2694 QList<QByteArray> list;
2695 qsizetype start = 0;
2696 qsizetype end;
2697 while ((end = indexOf(sep, start)) != -1) {
2698 list.append(mid(start, end - start));
2699 start = end + 1;
2700 }
2701 list.append(mid(start));
2702 return list;
2703}
2704
2705/*!
2706 \since 4.5
2707
2708 Returns a copy of this byte array repeated the specified number of \a times.
2709
2710 If \a times is less than 1, an empty byte array is returned.
2711
2712 Example:
2713
2714 \snippet code/src_corelib_text_qbytearray.cpp 49
2715*/
2716QByteArray QByteArray::repeated(qsizetype times) const
2717{
2718 if (isEmpty())
2719 return *this;
2720
2721 if (times <= 1) {
2722 if (times == 1)
2723 return *this;
2724 return QByteArray();
2725 }
2726
2727 const qsizetype resultSize = times * size();
2728
2729 QByteArray result;
2730 result.reserve(resultSize);
2731 if (result.capacity() != resultSize)
2732 return QByteArray(); // not enough memory
2733
2734 memcpy(result.d.data(), data(), size());
2735
2736 qsizetype sizeSoFar = size();
2737 char *end = result.d.data() + sizeSoFar;
2738
2739 const qsizetype halfResultSize = resultSize >> 1;
2740 while (sizeSoFar <= halfResultSize) {
2741 memcpy(end, result.d.data(), sizeSoFar);
2742 end += sizeSoFar;
2743 sizeSoFar <<= 1;
2744 }
2745 memcpy(end, result.d.data(), resultSize - sizeSoFar);
2746 result.d.data()[resultSize] = '\0';
2747 result.d.size = resultSize;
2748 return result;
2749}
2750
2751/*! \fn qsizetype QByteArray::indexOf(QByteArrayView bv, qsizetype from) const
2752 \since 6.0
2753
2754 Returns the index position of the start of the first occurrence of the
2755 sequence of bytes viewed by \a bv in this byte array, searching forward
2756 from index position \a from. Returns -1 if no match is found.
2757
2758 Example:
2759 \snippet code/src_corelib_text_qbytearray.cpp 21
2760
2761 \sa lastIndexOf(), contains(), count()
2762*/
2763
2764/*!
2765 \fn qsizetype QByteArray::indexOf(char ch, qsizetype from) const
2766 \overload
2767
2768 Returns the index position of the start of the first occurrence of the
2769 byte \a ch in this byte array, searching forward from index position \a from.
2770 Returns -1 if no match is found.
2771
2772 Example:
2773 \snippet code/src_corelib_text_qbytearray.cpp 22
2774
2775 \sa lastIndexOf(), contains()
2776*/
2777
2778static qsizetype lastIndexOfHelper(const char *haystack, qsizetype l, const char *needle,
2779 qsizetype ol, qsizetype from)
2780{
2781 auto delta = l - ol;
2782 if (from > l)
2783 return -1;
2784 if (from < 0 || from > delta)
2785 from = delta;
2786 if (from < 0)
2787 return -1;
2788
2789 const char *end = haystack;
2790 haystack += from;
2791 const qregisteruint ol_minus_1 = ol - 1;
2792 const char *n = needle + ol_minus_1;
2793 const char *h = haystack + ol_minus_1;
2794 qregisteruint hashNeedle = 0, hashHaystack = 0;
2795 qsizetype idx;
2796 for (idx = 0; idx < ol; ++idx) {
2797 hashNeedle = ((hashNeedle<<1) + *(n-idx));
2798 hashHaystack = ((hashHaystack<<1) + *(h-idx));
2799 }
2800 hashHaystack -= *haystack;
2801 while (haystack >= end) {
2802 hashHaystack += *haystack;
2803 if (hashHaystack == hashNeedle && memcmp(needle, haystack, ol) == 0)
2804 return haystack - end;
2805 --haystack;
2806 if (ol_minus_1 < sizeof(ol_minus_1) * CHAR_BIT)
2807 hashHaystack -= qregisteruint(*(haystack + ol)) << ol_minus_1;
2808 hashHaystack <<= 1;
2809 }
2810 return -1;
2811}
2812
2813qsizetype QtPrivate::lastIndexOf(QByteArrayView haystack, qsizetype from, QByteArrayView needle) noexcept
2814{
2815 if (haystack.isEmpty()) {
2816 if (needle.isEmpty() && from == 0)
2817 return 0;
2818 return -1;
2819 }
2820 const auto ol = needle.size();
2821 if (ol == 1)
2822 return QtPrivate::lastIndexOf(haystack, from, needle.front());
2823
2824 return lastIndexOfHelper(haystack.data(), haystack.size(), needle.data(), ol, from);
2825}
2826
2827/*! \fn qsizetype QByteArray::lastIndexOf(QByteArrayView bv, qsizetype from) const
2828 \since 6.0
2829
2830 Returns the index position of the start of the last occurrence of the
2831 sequence of bytes viewed by \a bv in this byte array, searching backward
2832 from index position \a from.
2833
2834 \include qstring.qdocinc negative-index-start-search-from-end
2835
2836 Returns -1 if no match is found.
2837
2838 Example:
2839 \snippet code/src_corelib_text_qbytearray.cpp 23
2840
2841 \note When searching for a 0-length \a bv, the match at the end of
2842 the data is excluded from the search by a negative \a from, even
2843 though \c{-1} is normally thought of as searching from the end of
2844 the byte array: the match at the end is \e after the last character, so
2845 it is excluded. To include such a final empty match, either give a
2846 positive value for \a from or omit the \a from parameter entirely.
2847
2848 \sa indexOf(), contains(), count()
2849*/
2850
2851/*! \fn qsizetype QByteArray::lastIndexOf(QByteArrayView bv) const
2852 \since 6.2
2853 \overload
2854
2855 Returns the index position of the start of the last occurrence of the
2856 sequence of bytes viewed by \a bv in this byte array, searching backward
2857 from the end of the byte array. Returns -1 if no match is found.
2858
2859 Example:
2860 \snippet code/src_corelib_text_qbytearray.cpp 23
2861
2862 \sa indexOf(), contains(), count()
2863*/
2864
2865/*!
2866 \fn qsizetype QByteArray::lastIndexOf(char ch, qsizetype from) const
2867 \overload
2868
2869 Returns the index position of the start of the last occurrence of byte \a ch
2870 in this byte array, searching backward from index position \a from.
2871 If \a from is -1 (the default), the search starts at the last byte
2872 (at index size() - 1). Returns -1 if no match is found.
2873
2874 Example:
2875 \snippet code/src_corelib_text_qbytearray.cpp 24
2876
2877 \sa indexOf(), contains()
2878*/
2879
2880static inline qsizetype countCharHelper(QByteArrayView haystack, char needle) noexcept
2881{
2882 qsizetype num = 0;
2883 for (char ch : haystack) {
2884 if (ch == needle)
2885 ++num;
2886 }
2887 return num;
2888}
2889
2890qsizetype QtPrivate::count(QByteArrayView haystack, QByteArrayView needle) noexcept
2891{
2892 if (needle.size() == 0)
2893 return haystack.size() + 1;
2894
2895 if (needle.size() == 1)
2896 return countCharHelper(haystack, needle[0]);
2897
2898 qsizetype num = 0;
2899 qsizetype i = -1;
2900 if (haystack.size() > 500 && needle.size() > 5) {
2901 QByteArrayMatcher matcher(needle);
2902 while ((i = matcher.indexIn(haystack, i + 1)) != -1)
2903 ++num;
2904 } else {
2905 while ((i = haystack.indexOf(needle, i + 1)) != -1)
2906 ++num;
2907 }
2908 return num;
2909}
2910
2911/*! \fn qsizetype QByteArray::count(QByteArrayView bv) const
2912 \since 6.0
2913
2914 Returns the number of (potentially overlapping) occurrences of the
2915 sequence of bytes viewed by \a bv in this byte array.
2916
2917 \sa contains(), indexOf()
2918*/
2919
2920/*!
2921 \overload
2922
2923 Returns the number of occurrences of byte \a ch in the byte array.
2924
2925 \sa contains(), indexOf()
2926*/
2927
2928qsizetype QByteArray::count(char ch) const
2929{
2930 return countCharHelper(*this, ch);
2931}
2932
2933#if QT_DEPRECATED_SINCE(6, 4)
2934/*! \fn qsizetype QByteArray::count() const
2935 \deprecated [6.4] Use size() or length() instead.
2936 \overload
2937
2938 Same as size().
2939*/
2940#endif
2941
2942/*!
2943 \fn int QByteArray::compare(QByteArrayView bv, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
2944 \since 6.0
2945
2946 Returns an integer less than, equal to, or greater than zero depending on
2947 whether this QByteArray sorts before, at the same position as, or after the
2948 QByteArrayView \a bv. The comparison is performed according to case
2949 sensitivity \a cs.
2950
2951 \sa operator==, {Character Case}
2952*/
2953
2954bool QtPrivate::startsWith(QByteArrayView haystack, QByteArrayView needle) noexcept
2955{
2956 if (haystack.size() < needle.size())
2957 return false;
2958 if (haystack.data() == needle.data() || needle.size() == 0)
2959 return true;
2960 return memcmp(haystack.data(), needle.data(), needle.size()) == 0;
2961}
2962
2963/*! \fn bool QByteArray::startsWith(QByteArrayView bv) const
2964 \since 6.0
2965
2966 Returns \c true if this byte array starts with the sequence of bytes
2967 viewed by \a bv; otherwise returns \c false.
2968
2969 Example:
2970 \snippet code/src_corelib_text_qbytearray.cpp 25
2971
2972 \sa endsWith(), first()
2973*/
2974
2975/*!
2976 \fn bool QByteArray::startsWith(char ch) const
2977 \overload
2978
2979 Returns \c true if this byte array starts with byte \a ch; otherwise returns
2980 \c false.
2981*/
2982
2983bool QtPrivate::endsWith(QByteArrayView haystack, QByteArrayView needle) noexcept
2984{
2985 if (haystack.size() < needle.size())
2986 return false;
2987 if (haystack.end() == needle.end() || needle.size() == 0)
2988 return true;
2989 return memcmp(haystack.end() - needle.size(), needle.data(), needle.size()) == 0;
2990}
2991
2992/*!
2993 \fn bool QByteArray::endsWith(QByteArrayView bv) const
2994 \since 6.0
2995
2996 Returns \c true if this byte array ends with the sequence of bytes
2997 viewed by \a bv; otherwise returns \c false.
2998
2999 Example:
3000 \snippet code/src_corelib_text_qbytearray.cpp 26
3001
3002 \sa startsWith(), last()
3003*/
3004
3005/*!
3006 \fn bool QByteArray::endsWith(char ch) const
3007 \overload
3008
3009 Returns \c true if this byte array ends with byte \a ch;
3010 otherwise returns \c false.
3011*/
3012
3013/*
3014 Returns true if \a c is an uppercase ASCII letter.
3015 */
3016static constexpr inline bool isUpperCaseAscii(char c)
3017{
3018 return c >= 'A' && c <= 'Z';
3019}
3020
3021/*
3022 Returns true if \a c is an lowercase ASCII letter.
3023 */
3024static constexpr inline bool isLowerCaseAscii(char c)
3025{
3026 return c >= 'a' && c <= 'z';
3027}
3028
3029/*!
3030 Returns \c true if this byte array is uppercase, that is, if
3031 it's identical to its toUpper() folding.
3032
3033 Note that this does \e not mean that the byte array only contains
3034 uppercase letters; only that it contains no ASCII lowercase letters.
3035
3036 \since 5.12
3037
3038 \sa isLower(), toUpper()
3039*/
3040bool QByteArray::isUpper() const
3041{
3042 return std::none_of(begin(), end(), isLowerCaseAscii);
3043}
3044
3045/*!
3046 Returns \c true if this byte array is lowercase, that is, if
3047 it's identical to its toLower() folding.
3048
3049 Note that this does \e not mean that the byte array only contains
3050 lowercase letters; only that it contains no ASCII uppercase letters.
3051
3052 \since 5.12
3053
3054 \sa isUpper(), toLower()
3055 */
3056bool QByteArray::isLower() const
3057{
3058 return std::none_of(begin(), end(), isUpperCaseAscii);
3059}
3060
3061/*!
3062 \fn QByteArray::isValidUtf8() const
3063
3064 Returns \c true if this byte array contains valid UTF-8 encoded data,
3065 or \c false otherwise.
3066
3067 \since 6.3
3068*/
3069
3070/*!
3071 \fn QByteArray QByteArray::left(qsizetype len) const &
3072 \fn QByteArray QByteArray::left(qsizetype len) &&
3073
3074 Returns a byte array that contains the first \a len bytes of this byte
3075 array.
3076
3077 If you know that \a len cannot be out of bounds, use first() instead in new
3078 code, because it is faster.
3079
3080 The entire byte array is returned if \a len is greater than
3081 size().
3082
3083 Returns an empty QByteArray if \a len is smaller than 0.
3084
3085 \sa first(), last(), startsWith(), chopped(), chop(), truncate()
3086*/
3087
3088/*!
3089 \fn QByteArray QByteArray::right(qsizetype len) const &
3090 \fn QByteArray QByteArray::right(qsizetype len) &&
3091
3092 Returns a byte array that contains the last \a len bytes of this byte array.
3093
3094 If you know that \a len cannot be out of bounds, use last() instead in new
3095 code, because it is faster.
3096
3097 The entire byte array is returned if \a len is greater than
3098 size().
3099
3100 Returns an empty QByteArray if \a len is smaller than 0.
3101
3102 \sa endsWith(), last(), first(), sliced(), chopped(), chop(), truncate(), slice()
3103*/
3104
3105/*!
3106 \fn QByteArray QByteArray::mid(qsizetype pos, qsizetype len) const &
3107 \fn QByteArray QByteArray::mid(qsizetype pos, qsizetype len) &&
3108
3109 Returns a byte array containing \a len bytes from this byte array,
3110 starting at position \a pos.
3111
3112 If you know that \a pos and \a len cannot be out of bounds, use sliced()
3113 instead in new code, because it is faster.
3114
3115 If \a len is -1 (the default), or \a pos + \a len >= size(),
3116 returns a byte array containing all bytes starting at position \a
3117 pos until the end of the byte array.
3118
3119 \sa first(), last(), sliced(), chopped(), chop(), truncate(), slice()
3120*/
3121
3122QByteArray QByteArray::mid(qsizetype pos, qsizetype len) const &
3123{
3124 qsizetype p = pos;
3125 qsizetype l = len;
3126 using namespace QtPrivate;
3127 switch (QContainerImplHelper::mid(size(), &p, &l)) {
3128 case QContainerImplHelper::Null:
3129 return QByteArray();
3130 case QContainerImplHelper::Empty:
3131 {
3132 return QByteArray(DataPointer::fromRawData(&_empty, 0));
3133 }
3134 case QContainerImplHelper::Full:
3135 return *this;
3136 case QContainerImplHelper::Subset:
3137 return sliced(p, l);
3138 }
3139 Q_UNREACHABLE_RETURN(QByteArray());
3140}
3141
3142QByteArray QByteArray::mid(qsizetype pos, qsizetype len) &&
3143{
3144 qsizetype p = pos;
3145 qsizetype l = len;
3146 using namespace QtPrivate;
3147 switch (QContainerImplHelper::mid(size(), &p, &l)) {
3148 case QContainerImplHelper::Null:
3149 return QByteArray();
3150 case QContainerImplHelper::Empty:
3151 resize(0); // keep capacity if we've reserve()d
3152 [[fallthrough]];
3153 case QContainerImplHelper::Full:
3154 return std::move(*this);
3155 case QContainerImplHelper::Subset:
3156 return std::move(*this).sliced(p, l);
3157 }
3158 Q_UNREACHABLE_RETURN(QByteArray());
3159}
3160
3161/*!
3162 \fn QByteArray QByteArray::first(qsizetype n) const &
3163 \fn QByteArray QByteArray::first(qsizetype n) &&
3164 \since 6.0
3165
3166 Returns the first \a n bytes of the byte array.
3167
3168 \note The behavior is undefined when \a n < 0 or \a n > size().
3169
3170 Example:
3171 \snippet code/src_corelib_text_qbytearray.cpp 27
3172
3173 \sa last(), sliced(), startsWith(), chopped(), chop(), truncate(), slice()
3174*/
3175
3176/*!
3177 \fn QByteArray QByteArray::last(qsizetype n) const &
3178 \fn QByteArray QByteArray::last(qsizetype n) &&
3179 \since 6.0
3180
3181 Returns the last \a n bytes of the byte array.
3182
3183 \note The behavior is undefined when \a n < 0 or \a n > size().
3184
3185 Example:
3186 \snippet code/src_corelib_text_qbytearray.cpp 28
3187
3188 \sa first(), sliced(), endsWith(), chopped(), chop(), truncate(), slice()
3189*/
3190
3191/*!
3192 \fn QByteArray QByteArray::sliced(qsizetype pos, qsizetype n) const &
3193 \fn QByteArray QByteArray::sliced(qsizetype pos, qsizetype n) &&
3194 \since 6.0
3195
3196 Returns a byte array containing the \a n bytes of this object starting
3197 at position \a pos.
3198
3199 \note The behavior is undefined when \a pos < 0, \a n < 0,
3200 or \a pos + \a n > size().
3201
3202 Example:
3203 \snippet code/src_corelib_text_qbytearray.cpp 29
3204
3205 \sa first(), last(), chopped(), chop(), truncate(), slice()
3206*/
3207QByteArray QByteArray::sliced_helper(QByteArray &a, qsizetype pos, qsizetype n)
3208{
3209 if (n == 0)
3210 return fromRawData(&_empty, 0);
3211 DataPointer d = std::move(a.d).sliced(pos, n);
3212 d.data()[n] = 0;
3213 return QByteArray(std::move(d));
3214}
3215
3216/*!
3217 \fn QByteArray QByteArray::sliced(qsizetype pos) const &
3218 \fn QByteArray QByteArray::sliced(qsizetype pos) &&
3219 \since 6.0
3220 \overload
3221
3222 Returns a byte array containing the bytes starting at position \a pos
3223 in this object, and extending to the end of this object.
3224
3225 \note The behavior is undefined when \a pos < 0 or \a pos > size().
3226
3227 \sa first(), last(), chopped(), chop(), truncate(), slice()
3228*/
3229
3230/*!
3231 \fn QByteArray &QByteArray::slice(qsizetype pos, qsizetype n)
3232 \since 6.8
3233
3234 Modifies this byte array to start at position \a pos, extending for \a n
3235 bytes, and returns a reference to this byte array.
3236
3237 \note The behavior is undefined if \a pos < 0, \a n < 0,
3238 or \a pos + \a n > size().
3239
3240 Example:
3241 \snippet code/src_corelib_text_qbytearray.cpp 57
3242
3243 \sa sliced(), first(), last(), chopped(), chop(), truncate()
3244*/
3245
3246/*!
3247 \fn QByteArray &QByteArray::slice(qsizetype pos)
3248 \since 6.8
3249 \overload
3250
3251 Modifies this byte array to start at position \a pos, extending to its
3252 end, and returns a reference to this byte array.
3253
3254 \note The behavior is undefined if \a pos < 0 or \a pos > size().
3255
3256 \sa sliced(), first(), last(), chopped(), chop(), truncate()
3257*/
3258
3259/*!
3260 \fn QByteArray QByteArray::chopped(qsizetype len) const &
3261 \fn QByteArray QByteArray::chopped(qsizetype len) &&
3262 \since 5.10
3263
3264 Returns a byte array that contains the leftmost size() - \a len bytes of
3265 this byte array.
3266
3267 \note The behavior is undefined if \a len is negative or greater than size().
3268
3269 \sa endsWith(), first(), last(), sliced(), chop(), truncate(), slice()
3270*/
3271
3272/*!
3273 \fn QByteArray QByteArray::toLower() const
3274
3275 Returns a copy of the byte array in which each ASCII uppercase letter
3276 converted to lowercase.
3277
3278 Example:
3279 \snippet code/src_corelib_text_qbytearray.cpp 30
3280
3281 \sa isLower(), toUpper(), {Character Case}
3282*/
3283
3284static QByteArray toCase(const QByteArray &input, QByteArray *rvalue, 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 q_choose_copy_move(input, rvalue);
3299
3300 // transform the rest
3301 QByteArray s = q_choose_copy_move(input, rvalue);
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(a, nullptr, asciiLower);
3313}
3314
3315QByteArray QByteArray::toLower_helper(QByteArray &a)
3316{
3317 return toCase(a, &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(a, nullptr, asciiUpper);
3335}
3336
3337QByteArray QByteArray::toUpper_helper(QByteArray &a)
3338{
3339 return toCase(a, &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 {QLocale::toString(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 qsizetype q_fromPercentEncoding(QByteArrayView src, char percent, QSpan<char> buffer)
4729{
4730 char *data = buffer.begin();
4731 const char *inputPtr = src.begin();
4732
4733 qsizetype i = 0;
4734 const qsizetype len = src.size();
4735 while (i < len) {
4736 char c = inputPtr[i];
4737 if (c == percent && i + 2 < len) {
4738 if (int a = QtMiscUtils::fromHex(uchar(inputPtr[++i])); a != -1)
4739 *data = a << 4;
4740 if (int b = QtMiscUtils::fromHex(uchar(inputPtr[++i])); b != -1)
4741 *data |= b;
4742 } else {
4743 *data = c;
4744 }
4745 ++data;
4746 ++i;
4747 }
4748
4749 return data - buffer.begin();
4750}
4751
4752/*!
4753 \fn QByteArray QByteArray::percentDecoded(char percent) const &
4754 \since 6.4
4755
4756 Decodes URI/URL-style percent-encoding.
4757
4758 Returns a byte array containing the decoded text. The \a percent parameter
4759 allows use of a different character than '%' (for instance, '_' or '=') as
4760 the escape character.
4761
4762 For example:
4763 \snippet code/src_corelib_text_qbytearray.cpp 54
4764
4765 \note Given invalid input (such as a string containing the sequence "%G5",
4766 which is not a valid hexadecimal number) the output will be invalid as
4767 well. As an example: the sequence "%G5" could be decoded to 'W'.
4768
4769 \sa toPercentEncoding(), QUrl::fromPercentEncoding()
4770*/
4771
4772/*!
4773 \fn QByteArray QByteArray::percentDecoded(char percent) &&
4774 \since 6.11
4775 \overload
4776*/
4777
4778/*!
4779 \since 4.4
4780
4781 Decodes \a input from URI/URL-style percent-encoding.
4782
4783 Returns a byte array containing the decoded text. The \a percent parameter
4784 allows use of a different character than '%' (for instance, '_' or '=') as
4785 the escape character. Equivalent to input.percentDecoded(percent).
4786
4787 For example:
4788 \snippet code/src_corelib_text_qbytearray.cpp 51
4789
4790 \sa percentDecoded()
4791*/
4792QByteArray QByteArray::fromPercentEncoding(const QByteArray &input, char percent)
4793{
4794 if (input.isEmpty())
4795 return input; // Preserves isNull().
4796
4797 QByteArray out{input.size(), Qt::Uninitialized};
4798 qsizetype len = q_fromPercentEncoding(input, percent, out);
4799 out.truncate(len);
4800 return out;
4801}
4802
4803/*!
4804 \overload
4805 \since 6.11
4806*/
4807QByteArray QByteArray::fromPercentEncoding(QByteArray &&input, char percent)
4808{
4809 if (input.d->needsDetach())
4810 return fromPercentEncoding(input, percent); // lvalue overload
4811
4812 if (input.isEmpty())
4813 return std::move(input); // Preserves isNull().
4814
4815 qsizetype len = q_fromPercentEncoding(input, percent, input);
4816 input.truncate(len);
4817 return std::move(input);
4818}
4819
4820/*! \fn QByteArray QByteArray::fromStdString(const std::string &str)
4821 \since 5.4
4822
4823 Returns a copy of the \a str string as a QByteArray.
4824
4825 \sa toStdString(), QString::fromStdString()
4826*/
4827QByteArray QByteArray::fromStdString(const std::string &s)
4828{
4829 return QByteArray(s.data(), qsizetype(s.size()));
4830}
4831
4832/*!
4833 \fn std::string QByteArray::toStdString() const
4834 \since 5.4
4835
4836 Returns a std::string object with the data contained in this
4837 QByteArray.
4838
4839 This operator is mostly useful to pass a QByteArray to a function
4840 that accepts a std::string object.
4841
4842 \sa fromStdString(), QString::toStdString()
4843*/
4844std::string QByteArray::toStdString() const
4845{
4846 return std::string(data(), size_t(size()));
4847}
4848
4849/*!
4850 \fn QByteArray::operator std::string_view() const noexcept
4851 \target qbytearray-operator-std-string_view
4852 \since 6.10
4853
4854 Converts this QByteArray object to a \c{std::string_view} object.
4855 The returned string view will span over the entirety of the byte
4856 array.
4857*/
4858
4859/*!
4860 \since 4.4
4861
4862 Returns a URI/URL-style percent-encoded copy of this byte array. The
4863 \a percent parameter allows you to override the default '%'
4864 character for another.
4865
4866 By default, this function will encode all bytes that are not one of the
4867 following:
4868
4869 ALPHA ("a" to "z" and "A" to "Z") / DIGIT (0 to 9) / "-" / "." / "_" / "~"
4870
4871 To prevent bytes from being encoded pass them to \a exclude. To force bytes
4872 to be encoded pass them to \a include. The \a percent character is always
4873 encoded.
4874
4875 Example:
4876
4877 \snippet code/src_corelib_text_qbytearray.cpp 52
4878
4879 The hex encoding uses the numbers 0-9 and the uppercase letters A-F.
4880
4881 \sa fromPercentEncoding(), QUrl::toPercentEncoding()
4882*/
4883QByteArray QByteArray::toPercentEncoding(const QByteArray &exclude, const QByteArray &include,
4884 char percent) const
4885{
4886 if (isNull())
4887 return QByteArray(); // preserve null
4888 if (isEmpty())
4889 return QByteArray(data(), 0);
4890
4891 const auto contains = [](const QByteArray &view, char c) {
4892 // As view.contains(c), but optimised to bypass a lot of overhead:
4893 return view.size() > 0 && memchr(view.data(), c, view.size()) != nullptr;
4894 };
4895
4896 QByteArray result = *this;
4897 char *output = nullptr;
4898 qsizetype length = 0;
4899
4900 for (unsigned char c : *this) {
4901 if (char(c) != percent
4902 && ((c >= 0x61 && c <= 0x7A) // ALPHA
4903 || (c >= 0x41 && c <= 0x5A) // ALPHA
4904 || (c >= 0x30 && c <= 0x39) // DIGIT
4905 || c == 0x2D // -
4906 || c == 0x2E // .
4907 || c == 0x5F // _
4908 || c == 0x7E // ~
4909 || contains(exclude, c))
4910 && !contains(include, c)) {
4911 if (output)
4912 output[length] = c;
4913 ++length;
4914 } else {
4915 if (!output) {
4916 // detach now
4917 result.resize(size() * 3); // worst case
4918 output = result.data();
4919 }
4920 output[length++] = percent;
4921 output[length++] = QtMiscUtils::toHexUpper((c & 0xf0) >> 4);
4922 output[length++] = QtMiscUtils::toHexUpper(c & 0xf);
4923 }
4924 }
4925 if (output)
4926 result.truncate(length);
4927
4928 return result;
4929}
4930
4931#if defined(Q_OS_WASM) || defined(Q_QDOC)
4932
4933/*!
4934 Constructs a new QByteArray containing a copy of the Uint8Array \a uint8array.
4935
4936 This function transfers data from a JavaScript data buffer - which
4937 is not addressable from C++ code - to heap memory owned by a QByteArray.
4938 The Uint8Array can be released once this function returns and a copy
4939 has been made.
4940
4941 The \a uint8array argument must an emscripten::val referencing an Uint8Array
4942 object, e.g. obtained from a global JavaScript variable:
4943
4944 \snippet code/src_corelib_text_qbytearray.cpp 55
4945
4946 This function returns a null QByteArray if the size of the Uint8Array
4947 exceeds the maximum capacity of QByteArray, or if the \a uint8array
4948 argument is not of the Uint8Array type.
4949
4950 \since 6.5
4951 \ingroup platform-type-conversions
4952
4953 \sa toEcmaUint8Array()
4954*/
4955
4956QByteArray QByteArray::fromEcmaUint8Array(emscripten::val uint8array)
4957{
4958 return qstdweb::Uint8Array(uint8array).copyToQByteArray();
4959}
4960
4961/*!
4962 Creates a Uint8Array from a QByteArray.
4963
4964 This function transfers data from heap memory owned by a QByteArray
4965 to a JavaScript data buffer. The function allocates and copies into an
4966 ArrayBuffer, and returns a Uint8Array view to that buffer.
4967
4968 The JavaScript objects own a copy of the data, and this
4969 QByteArray can be safely deleted after the copy has been made.
4970
4971 \snippet code/src_corelib_text_qbytearray.cpp 56
4972
4973 \since 6.5
4974 \ingroup platform-type-conversions
4975
4976 \sa fromEcmaUint8Array()
4977*/
4978emscripten::val QByteArray::toEcmaUint8Array()
4979{
4980 return qstdweb::Uint8Array::copyFrom(*this).val();
4981}
4982
4983#endif
4984
4985/*! \typedef QByteArray::ConstIterator
4986 \internal
4987*/
4988
4989/*! \typedef QByteArray::Iterator
4990 \internal
4991*/
4992
4993/*! \typedef QByteArray::const_iterator
4994
4995 This typedef provides an STL-style const iterator for QByteArray.
4996
4997 \sa QByteArray::const_reverse_iterator, QByteArray::iterator
4998*/
4999
5000/*! \typedef QByteArray::iterator
5001
5002 This typedef provides an STL-style non-const iterator for QByteArray.
5003
5004 \sa QByteArray::reverse_iterator, QByteArray::const_iterator
5005*/
5006
5007/*! \typedef QByteArray::const_reverse_iterator
5008 \since 5.6
5009
5010 This typedef provides an STL-style const reverse iterator for QByteArray.
5011
5012 \sa QByteArray::reverse_iterator, QByteArray::const_iterator
5013*/
5014
5015/*! \typedef QByteArray::reverse_iterator
5016 \since 5.6
5017
5018 This typedef provides an STL-style non-const reverse iterator for QByteArray.
5019
5020 \sa QByteArray::const_reverse_iterator, QByteArray::iterator
5021*/
5022
5023/*! \typedef QByteArray::size_type
5024 \internal
5025*/
5026
5027/*! \typedef QByteArray::difference_type
5028 \internal
5029*/
5030
5031/*! \typedef QByteArray::const_reference
5032 \internal
5033*/
5034
5035/*! \typedef QByteArray::reference
5036 \internal
5037*/
5038
5039/*! \typedef QByteArray::const_pointer
5040 \internal
5041*/
5042
5043/*! \typedef QByteArray::pointer
5044 \internal
5045*/
5046
5047/*! \typedef QByteArray::value_type
5048 \internal
5049 */
5050
5051/*!
5052 \fn DataPtr &QByteArray::data_ptr()
5053 \internal
5054*/
5055
5056/*!
5057 \typedef QByteArray::DataPtr
5058 \internal
5059*/
5060
5061/*!
5062 \macro QByteArrayLiteral(ba)
5063 \relates QByteArray
5064
5065 The macro generates the data for a QByteArray out of the string literal \a
5066 ba at compile time. Creating a QByteArray from it is free in this case, and
5067 the generated byte array data is stored in the read-only segment of the
5068 compiled object file.
5069
5070 For instance:
5071
5072 \snippet code/src_corelib_text_qbytearray.cpp 53
5073
5074 Using QByteArrayLiteral instead of a double quoted plain C++ string literal
5075 can significantly speed up creation of QByteArray instances from data known
5076 at compile time.
5077
5078 \sa QStringLiteral
5079*/
5080
5081#if QT_DEPRECATED_SINCE(6, 8)
5082/*!
5083 \fn QtLiterals::operator""_qba(const char *str, size_t size)
5084
5085 \relates QByteArray
5086 \since 6.2
5087 \deprecated [6.8] Use \c _ba from Qt::StringLiterals namespace instead.
5088
5089 Literal operator that creates a QByteArray out of the first \a size characters
5090 in the char string literal \a str.
5091
5092 The QByteArray is created at compile time, and the generated string data is stored
5093 in the read-only segment of the compiled object file. Duplicate literals may share
5094 the same read-only memory. This functionality is interchangeable with
5095 QByteArrayLiteral, but saves typing when many string literals are present in the
5096 code.
5097
5098 The following code creates a QByteArray:
5099 \code
5100 auto str = "hello"_qba;
5101 \endcode
5102
5103 \sa QByteArrayLiteral, QtLiterals::operator""_qs(const char16_t *str, size_t size)
5104*/
5105#endif // QT_DEPRECATED_SINCE(6, 8)
5106
5107/*!
5108 \fn Qt::Literals::StringLiterals::operator""_ba(const char *str, size_t size)
5109
5110 \relates QByteArray
5111 \since 6.4
5112
5113 Literal operator that creates a QByteArray out of the first \a size characters
5114 in the char string literal \a str.
5115
5116 The QByteArray is created at compile time, and the generated string data is stored
5117 in the read-only segment of the compiled object file. Duplicate literals may share
5118 the same read-only memory. This functionality is interchangeable with
5119 QByteArrayLiteral, but saves typing when many string literals are present in the
5120 code.
5121
5122 The following code creates a QByteArray:
5123 \code
5124 using namespace Qt::StringLiterals;
5125
5126 auto str = "hello"_ba;
5127 \endcode
5128
5129 \sa Qt::Literals::StringLiterals
5130*/
5131
5132/*!
5133 \class QByteArray::FromBase64Result
5134 \inmodule QtCore
5135 \ingroup tools
5136 \since 5.15
5137
5138 \brief The QByteArray::FromBase64Result class holds the result of
5139 a call to QByteArray::fromBase64Encoding.
5140
5141 Objects of this class can be used to check whether the conversion
5142 was successful, and if so, retrieve the decoded QByteArray. The
5143 conversion operators defined for QByteArray::FromBase64Result make
5144 its usage straightforward:
5145
5146 \snippet code/src_corelib_text_qbytearray.cpp 44ter
5147
5148 Alternatively, it is possible to access the conversion status
5149 and the decoded data directly:
5150
5151 \snippet code/src_corelib_text_qbytearray.cpp 44quater
5152
5153 \sa QByteArray::fromBase64
5154*/
5155
5156/*!
5157 \variable QByteArray::FromBase64Result::decoded
5158
5159 Contains the decoded byte array.
5160*/
5161
5162/*!
5163 \variable QByteArray::FromBase64Result::decodingStatus
5164
5165 Contains whether the decoding was successful, expressed as a value
5166 of type QByteArray::Base64DecodingStatus.
5167*/
5168
5169/*!
5170 \fn QByteArray::FromBase64Result::operator bool() const
5171
5172 Returns whether the decoding was successful. This is equivalent
5173 to checking whether the \c{decodingStatus} member is equal to
5174 QByteArray::Base64DecodingStatus::Ok.
5175*/
5176
5177/*!
5178 \fn const QByteArray &QByteArray::FromBase64Result::operator*() const &
5179 \fn QByteArray &QByteArray::FromBase64Result::operator*() &
5180 \fn QByteArray &&QByteArray::FromBase64Result::operator*() &&
5181
5182 Returns the decoded byte array.
5183*/
5184
5185/*!
5186 \fn bool QByteArray::FromBase64Result::operator==(const QByteArray::FromBase64Result &lhs, const QByteArray::FromBase64Result &rhs) noexcept
5187
5188 Returns \c true if \a lhs and \a rhs are equal, otherwise returns \c false.
5189
5190 \a lhs and \a rhs are equal if and only if they contain the same decoding
5191 status and, if the status is QByteArray::Base64DecodingStatus::Ok, if and
5192 only if they contain the same decoded data.
5193*/
5194
5195/*!
5196 \fn bool QByteArray::FromBase64Result::operator!=(const QByteArray::FromBase64Result &lhs, const QByteArray::FromBase64Result &rhs) noexcept
5197
5198 Returns \c true if \a lhs and \a rhs are different, otherwise
5199 returns \c false.
5200*/
5201
5202/*!
5203 \qhashold{QByteArray::FromBase64Result}
5204*/
5205size_t qHash(const QByteArray::FromBase64Result &key, size_t seed) noexcept
5206{
5207 return qHashMulti(seed, key.decoded, static_cast<int>(key.decodingStatus));
5208}
5209
5210/*! \fn template <typename T> qsizetype erase(QByteArray &ba, const T &t)
5211 \relates QByteArray
5212 \since 6.1
5213
5214 Removes all elements that compare equal to \a t from the
5215 byte array \a ba. Returns the number of elements removed, if any.
5216
5217 \sa erase_if
5218*/
5219
5220/*! \fn template <typename Predicate> qsizetype erase_if(QByteArray &ba, Predicate pred)
5221 \relates QByteArray
5222 \since 6.1
5223
5224 Removes all elements for which the predicate \a pred returns true
5225 from the byte array \a ba. Returns the number of elements removed, if
5226 any.
5227
5228 \sa erase
5229*/
5230
5231QT_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:81
static constexpr bool isLowerCaseAscii(char c)
static const quint16 crc_tbl[16]
QByteArray qCompress(const uchar *data, qsizetype nbytes, int compressionLevel)
ZLibOp
@ Decompression
static Q_DECL_COLD_FUNCTION const char * zlibOpAsString(ZLibOp op)
static QByteArray toCase(const QByteArray &input, QByteArray *rvalue, uchar(*lookup)(uchar))
static qsizetype q_fromPercentEncoding(QByteArrayView src, char percent, QSpan< char > buffer)
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:192
static float convertDoubleToFloat(double d, bool *ok)
Definition qlocale_p.h:339
@ DFSignificantDigits
Definition qlocale_p.h:261