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