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