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