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

source code of qtbase/src/corelib/text/qbytearray.cpp