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 std::memcpy(d.begin(), v.data(), len);
2235 d.size = len;
2236 d.data()[d.size] = '\0';
2237 } else {
2238 *this = v.toByteArray();
2239 }
2240 return *this;
2241}
2242
2243/*!
2244 Inserts \a data at index position \a i and returns a
2245 reference to this byte array.
2246
2247 Example:
2248 \snippet code/src_corelib_text_qbytearray.cpp 17
2249 \since 6.0
2250
2251 For large byte arrays, this operation can be slow (\l{linear time}),
2252 because it requires moving all the bytes at indexes \a i and
2253 above by at least one position further in memory.
2254
2255//! [array-grow-at-insertion]
2256 This array grows to accommodate the insertion. If \a i is beyond
2257 the end of the array, the array is first extended with space characters
2258 to reach this \a i.
2259//! [array-grow-at-insertion]
2260
2261 \sa append(), prepend(), replace(), remove()
2262*/
2263QByteArray &QByteArray::insert(qsizetype i, QByteArrayView data)
2264{
2265 const char *str = data.data();
2266 qsizetype size = data.size();
2267 if (i < 0 || size <= 0)
2268 return *this;
2269
2270 // handle this specially, as QArrayDataOps::insert() doesn't handle out of
2271 // bounds positions
2272 if (i >= d.size) {
2273 // In case when data points into the range or is == *this, we need to
2274 // defer a call to free() so that it comes after we copied the data from
2275 // the old memory:
2276 DataPointer detached{}; // construction is free
2277 d.detachAndGrow(Data::GrowsAtEnd, (i - d.size) + size, &str, &detached);
2278 Q_CHECK_PTR(d.data());
2279 d->copyAppend(i - d.size, ' ');
2280 d->copyAppend(str, str + size);
2281 d.data()[d.size] = '\0';
2282 return *this;
2283 }
2284
2285 if (!d.needsDetach() && QtPrivate::q_points_into_range(str, d)) {
2286 QVarLengthArray a(str, str + size);
2287 return insert(i, a);
2288 }
2289
2290 d->insert(i, str, size);
2291 d.data()[d.size] = '\0';
2292 return *this;
2293}
2294
2295/*!
2296 \fn QByteArray &QByteArray::insert(qsizetype i, const QByteArray &data)
2297 Inserts \a data at index position \a i and returns a
2298 reference to this byte array.
2299
2300 \include qbytearray.cpp array-grow-at-insertion
2301
2302 \sa append(), prepend(), replace(), remove()
2303*/
2304
2305/*!
2306 \fn QByteArray &QByteArray::insert(qsizetype i, const char *s)
2307 Inserts \a s at index position \a i and returns a
2308 reference to this byte array.
2309
2310 \include qbytearray.cpp array-grow-at-insertion
2311
2312 The function is equivalent to \c{insert(i, QByteArrayView(s))}
2313
2314 \sa append(), prepend(), replace(), remove()
2315*/
2316
2317/*!
2318 \fn QByteArray &QByteArray::insert(qsizetype i, const char *data, qsizetype len)
2319 \overload
2320 \since 4.6
2321
2322 Inserts \a len bytes, starting at \a data, at position \a i in the byte
2323 array.
2324
2325 \include qbytearray.cpp array-grow-at-insertion
2326*/
2327
2328/*!
2329 \fn QByteArray &QByteArray::insert(qsizetype i, char ch)
2330 \overload
2331
2332 Inserts byte \a ch at index position \a i in the byte array.
2333
2334 \include qbytearray.cpp array-grow-at-insertion
2335*/
2336
2337/*! \fn QByteArray &QByteArray::insert(qsizetype i, qsizetype count, char ch)
2338
2339 \overload
2340 \since 5.7
2341
2342 Inserts \a count copies of byte \a ch at index position \a i in the byte
2343 array.
2344
2345 \include qbytearray.cpp array-grow-at-insertion
2346*/
2347
2348QByteArray &QByteArray::insert(qsizetype i, qsizetype count, char ch)
2349{
2350 if (i < 0 || count <= 0)
2351 return *this;
2352
2353 if (i >= d.size) {
2354 // handle this specially, as QArrayDataOps::insert() doesn't handle out of bounds positions
2355 d.detachAndGrow(Data::GrowsAtEnd, (i - d.size) + count, nullptr, nullptr);
2356 Q_CHECK_PTR(d.data());
2357 d->copyAppend(i - d.size, ' ');
2358 d->copyAppend(count, ch);
2359 d.data()[d.size] = '\0';
2360 return *this;
2361 }
2362
2363 d->insert(i, count, ch);
2364 d.data()[d.size] = '\0';
2365 return *this;
2366}
2367
2368/*!
2369 Removes \a len bytes from the array, starting at index position \a
2370 pos, and returns a reference to the array.
2371
2372 If \a pos is out of range, nothing happens. If \a pos is valid,
2373 but \a pos + \a len is larger than the size of the array, the
2374 array is truncated at position \a pos.
2375
2376 Example:
2377 \snippet code/src_corelib_text_qbytearray.cpp 18
2378
2379 Element removal will preserve the array's capacity and not reduce the
2380 amount of allocated memory. To shed extra capacity and free as much memory
2381 as possible, call squeeze() after the last change to the array's size.
2382
2383 \sa insert(), replace(), squeeze()
2384*/
2385
2386QByteArray &QByteArray::remove(qsizetype pos, qsizetype len)
2387{
2388 if (len <= 0 || pos < 0 || size_t(pos) >= size_t(size()))
2389 return *this;
2390 if (pos + len > d.size)
2391 len = d.size - pos;
2392
2393 const auto toRemove_start = d.begin() + pos;
2394 if (!d.isShared()) {
2395 d->erase(toRemove_start, len);
2396 d.data()[d.size] = '\0';
2397 } else {
2398 QByteArray copy{size() - len, Qt::Uninitialized};
2399 copy.d->copyRanges({{d.begin(), toRemove_start},
2400 {toRemove_start + len, d.end()}});
2401 swap(copy);
2402 }
2403 return *this;
2404}
2405
2406/*!
2407 \fn QByteArray &QByteArray::removeAt(qsizetype pos)
2408
2409 \since 6.5
2410
2411 Removes the character at index \a pos. If \a pos is out of bounds
2412 (i.e. \a pos >= size()) this function does nothing.
2413
2414 \sa remove()
2415*/
2416
2417/*!
2418 \fn QByteArray &QByteArray::removeFirst()
2419
2420 \since 6.5
2421
2422 Removes the first character in this byte array. If the byte array is empty,
2423 this function does nothing.
2424
2425 \sa remove()
2426*/
2427/*!
2428 \fn QByteArray &QByteArray::removeLast()
2429
2430 \since 6.5
2431
2432 Removes the last character in this byte array. If the byte array is empty,
2433 this function does nothing.
2434
2435 \sa remove()
2436*/
2437
2438/*!
2439 \fn template <typename Predicate> QByteArray &QByteArray::removeIf(Predicate pred)
2440 \since 6.1
2441
2442 Removes all bytes for which the predicate \a pred returns true
2443 from the byte array. Returns a reference to the byte array.
2444
2445 \sa remove()
2446*/
2447
2448/*!
2449 Replaces \a len bytes from index position \a pos with the byte
2450 array \a after, and returns a reference to this byte array.
2451
2452 Example:
2453 \snippet code/src_corelib_text_qbytearray.cpp 19
2454
2455 \sa insert(), remove()
2456*/
2457
2458QByteArray &QByteArray::replace(qsizetype pos, qsizetype len, QByteArrayView after)
2459{
2460 if (size_t(pos) > size_t(this->size()))
2461 return *this;
2462 if (len > this->size() - pos)
2463 len = this->size() - pos;
2464 // Historic behavior, negative len was the equivalent of:
2465 // remove(pos, len); // does nothing
2466 // insert(pos, after);
2467 if (len <= 0)
2468 return insert(pos, after);
2469
2470 if (after.isEmpty())
2471 return remove(pos, len);
2472
2473 using A = QStringAlgorithms<QByteArray>;
2474 const qsizetype newlen = A::newSize(*this, len, after, {pos});
2475 if (data_ptr().needsDetach() || A::needsReallocate(*this, newlen)) {
2476 A::replace_into_copy(*this, len, after, {pos}, newlen);
2477 return *this;
2478 }
2479
2480 // No detaching or reallocation -> change in-place
2481 char *const begin = data_ptr().data(); // data(), without the detach() check
2482 char *const before = begin + pos;
2483 const char *beforeEnd = before + len;
2484 if (len >= after.size()) {
2485 memmove(before , after.cbegin(), after.size()); // sizeof(char) == 1
2486
2487 if (len > after.size()) {
2488 memmove(before + after.size(), beforeEnd, d.size - (beforeEnd - begin));
2489 A::setSize(*this, newlen);
2490 }
2491 } else { // len < after.size()
2492 char *oldEnd = begin + d.size;
2493 const qsizetype adjust = newlen - d.size;
2494 A::setSize(*this, newlen);
2495
2496 QByteArrayView tail{beforeEnd, oldEnd};
2497 QByteArrayView prefix = after;
2498 QByteArrayView suffix;
2499 if (QtPrivate::q_points_into_range(after.cend() - 1, tail)) {
2500 if (QtPrivate::q_points_into_range(after.cbegin(), tail)) {
2501 // `after` fully contained inside `tail`
2502 prefix = {};
2503 suffix = QByteArrayView{after.cbegin(), after.cend()};
2504 } else { // after.cbegin() is in [begin, beforeEnd)
2505 prefix = QByteArrayView{after.cbegin(), beforeEnd};
2506 suffix = QByteArrayView{beforeEnd, after.cend()};
2507 }
2508 }
2509 memmove(before + after.size(), tail.cbegin(), tail.size());
2510 if (!prefix.isEmpty())
2511 memmove(before, prefix.cbegin(), prefix.size()); // `prefix` may overlap `before`
2512 if (!suffix.isEmpty()) // adjust suffix after calling memcpy() above
2513 memcpy(before + prefix.size(), suffix.cbegin() + adjust, suffix.size()); // no overlap
2514 }
2515 return *this;
2516}
2517
2518/*! \fn QByteArray &QByteArray::replace(qsizetype pos, qsizetype len, const char *after, qsizetype alen)
2519
2520 \overload
2521
2522 Replaces \a len bytes from index position \a pos with \a alen bytes starting
2523 at position \a after. The bytes inserted may include '\\0' bytes.
2524
2525 \since 4.7
2526*/
2527
2528/*!
2529 \fn QByteArray &QByteArray::replace(const char *before, qsizetype bsize, const char *after, qsizetype asize)
2530 \overload
2531
2532 Replaces every occurrence of the \a bsize bytes starting at \a before with
2533 the \a asize bytes starting at \a after. Since the sizes of the strings are
2534 given by \a bsize and \a asize, they may contain '\\0' bytes and do not need
2535 to be '\\0'-terminated.
2536*/
2537
2538/*!
2539 \overload
2540 \since 6.0
2541
2542 Replaces every occurrence of the byte array \a before with the
2543 byte array \a after.
2544
2545 Example:
2546 \snippet code/src_corelib_text_qbytearray.cpp 20
2547*/
2548
2549QByteArray &QByteArray::replace(QByteArrayView before, QByteArrayView after)
2550{
2551 const char *b = before.data();
2552 qsizetype bsize = before.size();
2553 const char *a = after.data();
2554 qsizetype asize = after.size();
2555
2556 if (isEmpty()) {
2557 if (bsize)
2558 return *this;
2559 } else {
2560 if (b == a && bsize == asize)
2561 return *this;
2562 }
2563 if (asize == 0 && bsize == 0)
2564 return *this;
2565
2566 if (bsize == 1 && asize == 1)
2567 return replace(*b, *a); // use the fast char-char algorithm
2568
2569 // protect against `after` being part of this
2570 std::string pinnedReplacement;
2571 if (QtPrivate::q_points_into_range(a, d)) {
2572 pinnedReplacement.assign(a, a + asize);
2573 after = pinnedReplacement;
2574 }
2575
2576 QByteArrayMatcher matcher(b, bsize);
2577 // - create a table of replacement positions
2578 // - figure out the needed size; modify in place; or allocate a new byte array
2579 // and copy characters to it as needed
2580 // - do the replacements
2581 QVarLengthArray<qsizetype> indices;
2582 qsizetype index = 0;
2583 while ((index = matcher.indexIn(*this, index)) != -1) {
2584 indices.push_back(index);
2585 if (bsize > 0)
2586 index += bsize; // Step over before
2587 else
2588 ++index; // avoid infinite loop
2589 }
2590
2591 QStringAlgorithms<QByteArray>::replace_helper(*this, bsize, after, indices);
2592 return *this;
2593}
2594
2595/*!
2596 \fn QByteArray &QByteArray::replace(char before, QByteArrayView after)
2597 \overload
2598
2599 Replaces every occurrence of the byte \a before with the byte array \a
2600 after.
2601*/
2602
2603/*!
2604 \overload
2605
2606 Replaces every occurrence of the byte \a before with the byte \a after.
2607*/
2608
2609QByteArray &QByteArray::replace(char before, char after)
2610{
2611 if (before != after) {
2612 if (const auto pos = indexOf(before); pos >= 0) {
2613 if (d.needsDetach()) {
2614 QByteArray tmp(size(), Qt::Uninitialized);
2615 auto dst = tmp.d.data();
2616 dst = std::copy(d.data(), d.data() + pos, dst);
2617 *dst++ = after;
2618 std::replace_copy(d.data() + pos + 1, d.end(), dst, before, after);
2619 swap(tmp);
2620 } else {
2621 // in-place
2622 d.data()[pos] = after;
2623 std::replace(d.data() + pos + 1, d.end(), before, after);
2624 }
2625 }
2626 }
2627 return *this;
2628}
2629
2630/*!
2631 Splits the byte array into subarrays wherever \a sep occurs, and
2632 returns the list of those arrays. If \a sep does not match
2633 anywhere in the byte array, split() returns a single-element list
2634 containing this byte array.
2635*/
2636
2637QList<QByteArray> QByteArray::split(char sep) const
2638{
2639 QList<QByteArray> list;
2640 qsizetype start = 0;
2641 qsizetype end;
2642 while ((end = indexOf(sep, start)) != -1) {
2643 list.append(mid(start, end - start));
2644 start = end + 1;
2645 }
2646 list.append(mid(start));
2647 return list;
2648}
2649
2650/*!
2651 \since 4.5
2652
2653 Returns a copy of this byte array repeated the specified number of \a times.
2654
2655 If \a times is less than 1, an empty byte array is returned.
2656
2657 Example:
2658
2659 \snippet code/src_corelib_text_qbytearray.cpp 49
2660*/
2661QByteArray QByteArray::repeated(qsizetype times) const
2662{
2663 if (isEmpty())
2664 return *this;
2665
2666 if (times <= 1) {
2667 if (times == 1)
2668 return *this;
2669 return QByteArray();
2670 }
2671
2672 const qsizetype resultSize = times * size();
2673
2674 QByteArray result;
2675 result.reserve(resultSize);
2676 if (result.capacity() != resultSize)
2677 return QByteArray(); // not enough memory
2678
2679 memcpy(result.d.data(), data(), size());
2680
2681 qsizetype sizeSoFar = size();
2682 char *end = result.d.data() + sizeSoFar;
2683
2684 const qsizetype halfResultSize = resultSize >> 1;
2685 while (sizeSoFar <= halfResultSize) {
2686 memcpy(end, result.d.data(), sizeSoFar);
2687 end += sizeSoFar;
2688 sizeSoFar <<= 1;
2689 }
2690 memcpy(end, result.d.data(), resultSize - sizeSoFar);
2691 result.d.data()[resultSize] = '\0';
2692 result.d.size = resultSize;
2693 return result;
2694}
2695
2696/*! \fn qsizetype QByteArray::indexOf(QByteArrayView bv, qsizetype from) const
2697 \since 6.0
2698
2699 Returns the index position of the start of the first occurrence of the
2700 sequence of bytes viewed by \a bv in this byte array, searching forward
2701 from index position \a from. Returns -1 if no match is found.
2702
2703 Example:
2704 \snippet code/src_corelib_text_qbytearray.cpp 21
2705
2706 \sa lastIndexOf(), contains(), count()
2707*/
2708
2709/*!
2710 \fn qsizetype QByteArray::indexOf(char ch, qsizetype from) const
2711 \overload
2712
2713 Returns the index position of the start of the first occurrence of the
2714 byte \a ch in this byte array, searching forward from index position \a from.
2715 Returns -1 if no match is found.
2716
2717 Example:
2718 \snippet code/src_corelib_text_qbytearray.cpp 22
2719
2720 \sa lastIndexOf(), contains()
2721*/
2722
2723static qsizetype lastIndexOfHelper(const char *haystack, qsizetype l, const char *needle,
2724 qsizetype ol, qsizetype from)
2725{
2726 auto delta = l - ol;
2727 if (from > l)
2728 return -1;
2729 if (from < 0 || from > delta)
2730 from = delta;
2731 if (from < 0)
2732 return -1;
2733
2734 const char *end = haystack;
2735 haystack += from;
2736 const qregisteruint ol_minus_1 = ol - 1;
2737 const char *n = needle + ol_minus_1;
2738 const char *h = haystack + ol_minus_1;
2739 qregisteruint hashNeedle = 0, hashHaystack = 0;
2740 qsizetype idx;
2741 for (idx = 0; idx < ol; ++idx) {
2742 hashNeedle = ((hashNeedle<<1) + *(n-idx));
2743 hashHaystack = ((hashHaystack<<1) + *(h-idx));
2744 }
2745 hashHaystack -= *haystack;
2746 while (haystack >= end) {
2747 hashHaystack += *haystack;
2748 if (hashHaystack == hashNeedle && memcmp(needle, haystack, ol) == 0)
2749 return haystack - end;
2750 --haystack;
2751 if (ol_minus_1 < sizeof(ol_minus_1) * CHAR_BIT)
2752 hashHaystack -= qregisteruint(*(haystack + ol)) << ol_minus_1;
2753 hashHaystack <<= 1;
2754 }
2755 return -1;
2756}
2757
2758qsizetype QtPrivate::lastIndexOf(QByteArrayView haystack, qsizetype from, QByteArrayView needle) noexcept
2759{
2760 if (haystack.isEmpty()) {
2761 if (needle.isEmpty() && from == 0)
2762 return 0;
2763 return -1;
2764 }
2765 const auto ol = needle.size();
2766 if (ol == 1)
2767 return QtPrivate::lastIndexOf(haystack, from, needle.front());
2768
2769 return lastIndexOfHelper(haystack.data(), haystack.size(), needle.data(), ol, from);
2770}
2771
2772/*! \fn qsizetype QByteArray::lastIndexOf(QByteArrayView bv, qsizetype from) const
2773 \since 6.0
2774
2775 Returns the index position of the start of the last occurrence of the
2776 sequence of bytes viewed by \a bv in this byte array, searching backward
2777 from index position \a from.
2778
2779 \include qstring.qdocinc negative-index-start-search-from-end
2780
2781 Returns -1 if no match is found.
2782
2783 Example:
2784 \snippet code/src_corelib_text_qbytearray.cpp 23
2785
2786 \note When searching for a 0-length \a bv, the match at the end of
2787 the data is excluded from the search by a negative \a from, even
2788 though \c{-1} is normally thought of as searching from the end of
2789 the byte array: the match at the end is \e after the last character, so
2790 it is excluded. To include such a final empty match, either give a
2791 positive value for \a from or omit the \a from parameter entirely.
2792
2793 \sa indexOf(), contains(), count()
2794*/
2795
2796/*! \fn qsizetype QByteArray::lastIndexOf(QByteArrayView bv) const
2797 \since 6.2
2798 \overload
2799
2800 Returns the index position of the start of the last occurrence of the
2801 sequence of bytes viewed by \a bv in this byte array, searching backward
2802 from the end of the byte array. Returns -1 if no match is found.
2803
2804 Example:
2805 \snippet code/src_corelib_text_qbytearray.cpp 23
2806
2807 \sa indexOf(), contains(), count()
2808*/
2809
2810/*!
2811 \fn qsizetype QByteArray::lastIndexOf(char ch, qsizetype from) const
2812 \overload
2813
2814 Returns the index position of the start of the last occurrence of byte \a ch
2815 in this byte array, searching backward from index position \a from.
2816 If \a from is -1 (the default), the search starts at the last byte
2817 (at index size() - 1). Returns -1 if no match is found.
2818
2819 Example:
2820 \snippet code/src_corelib_text_qbytearray.cpp 24
2821
2822 \sa indexOf(), contains()
2823*/
2824
2825static inline qsizetype countCharHelper(QByteArrayView haystack, char needle) noexcept
2826{
2827 qsizetype num = 0;
2828 for (char ch : haystack) {
2829 if (ch == needle)
2830 ++num;
2831 }
2832 return num;
2833}
2834
2835qsizetype QtPrivate::count(QByteArrayView haystack, QByteArrayView needle) noexcept
2836{
2837 if (needle.size() == 0)
2838 return haystack.size() + 1;
2839
2840 if (needle.size() == 1)
2841 return countCharHelper(haystack, needle[0]);
2842
2843 qsizetype num = 0;
2844 qsizetype i = -1;
2845 if (haystack.size() > 500 && needle.size() > 5) {
2846 QByteArrayMatcher matcher(needle);
2847 while ((i = matcher.indexIn(haystack, i + 1)) != -1)
2848 ++num;
2849 } else {
2850 while ((i = haystack.indexOf(needle, i + 1)) != -1)
2851 ++num;
2852 }
2853 return num;
2854}
2855
2856/*! \fn qsizetype QByteArray::count(QByteArrayView bv) const
2857 \since 6.0
2858
2859 Returns the number of (potentially overlapping) occurrences of the
2860 sequence of bytes viewed by \a bv in this byte array.
2861
2862 \sa contains(), indexOf()
2863*/
2864
2865/*!
2866 \overload
2867
2868 Returns the number of occurrences of byte \a ch in the byte array.
2869
2870 \sa contains(), indexOf()
2871*/
2872
2873qsizetype QByteArray::count(char ch) const
2874{
2875 return countCharHelper(*this, ch);
2876}
2877
2878#if QT_DEPRECATED_SINCE(6, 4)
2879/*! \fn qsizetype QByteArray::count() const
2880 \deprecated [6.4] Use size() or length() instead.
2881 \overload
2882
2883 Same as size().
2884*/
2885#endif
2886
2887/*!
2888 \fn int QByteArray::compare(QByteArrayView bv, Qt::CaseSensitivity cs = Qt::CaseSensitive) const
2889 \since 6.0
2890
2891 Returns an integer less than, equal to, or greater than zero depending on
2892 whether this QByteArray sorts before, at the same position as, or after the
2893 QByteArrayView \a bv. The comparison is performed according to case
2894 sensitivity \a cs.
2895
2896 \sa operator==, {Character Case}
2897*/
2898
2899bool QtPrivate::startsWith(QByteArrayView haystack, QByteArrayView needle) noexcept
2900{
2901 if (haystack.size() < needle.size())
2902 return false;
2903 if (haystack.data() == needle.data() || needle.size() == 0)
2904 return true;
2905 return memcmp(haystack.data(), needle.data(), needle.size()) == 0;
2906}
2907
2908/*! \fn bool QByteArray::startsWith(QByteArrayView bv) const
2909 \since 6.0
2910
2911 Returns \c true if this byte array starts with the sequence of bytes
2912 viewed by \a bv; otherwise returns \c false.
2913
2914 Example:
2915 \snippet code/src_corelib_text_qbytearray.cpp 25
2916
2917 \sa endsWith(), first()
2918*/
2919
2920/*!
2921 \fn bool QByteArray::startsWith(char ch) const
2922 \overload
2923
2924 Returns \c true if this byte array starts with byte \a ch; otherwise returns
2925 \c false.
2926*/
2927
2928bool QtPrivate::endsWith(QByteArrayView haystack, QByteArrayView needle) noexcept
2929{
2930 if (haystack.size() < needle.size())
2931 return false;
2932 if (haystack.end() == needle.end() || needle.size() == 0)
2933 return true;
2934 return memcmp(haystack.end() - needle.size(), needle.data(), needle.size()) == 0;
2935}
2936
2937/*!
2938 \fn bool QByteArray::endsWith(QByteArrayView bv) const
2939 \since 6.0
2940
2941 Returns \c true if this byte array ends with the sequence of bytes
2942 viewed by \a bv; otherwise returns \c false.
2943
2944 Example:
2945 \snippet code/src_corelib_text_qbytearray.cpp 26
2946
2947 \sa startsWith(), last()
2948*/
2949
2950/*!
2951 \fn bool QByteArray::endsWith(char ch) const
2952 \overload
2953
2954 Returns \c true if this byte array ends with byte \a ch;
2955 otherwise returns \c false.
2956*/
2957
2958/*
2959 Returns true if \a c is an uppercase ASCII letter.
2960 */
2961static constexpr inline bool isUpperCaseAscii(char c)
2962{
2963 return c >= 'A' && c <= 'Z';
2964}
2965
2966/*
2967 Returns true if \a c is an lowercase ASCII letter.
2968 */
2969static constexpr inline bool isLowerCaseAscii(char c)
2970{
2971 return c >= 'a' && c <= 'z';
2972}
2973
2974/*!
2975 Returns \c true if this byte array is uppercase, that is, if
2976 it's identical to its toUpper() folding.
2977
2978 Note that this does \e not mean that the byte array only contains
2979 uppercase letters; only that it contains no ASCII lowercase letters.
2980
2981 \since 5.12
2982
2983 \sa isLower(), toUpper()
2984*/
2985bool QByteArray::isUpper() const
2986{
2987 return std::none_of(begin(), end(), isLowerCaseAscii);
2988}
2989
2990/*!
2991 Returns \c true if this byte array is lowercase, that is, if
2992 it's identical to its toLower() folding.
2993
2994 Note that this does \e not mean that the byte array only contains
2995 lowercase letters; only that it contains no ASCII uppercase letters.
2996
2997 \since 5.12
2998
2999 \sa isUpper(), toLower()
3000 */
3001bool QByteArray::isLower() const
3002{
3003 return std::none_of(begin(), end(), isUpperCaseAscii);
3004}
3005
3006/*!
3007 \fn QByteArray::isValidUtf8() const
3008
3009 Returns \c true if this byte array contains valid UTF-8 encoded data,
3010 or \c false otherwise.
3011
3012 \since 6.3
3013*/
3014
3015/*!
3016 \fn QByteArray QByteArray::left(qsizetype len) const &
3017 \fn QByteArray QByteArray::left(qsizetype len) &&
3018
3019 Returns a byte array that contains the first \a len bytes of this byte
3020 array.
3021
3022 If you know that \a len cannot be out of bounds, use first() instead in new
3023 code, because it is faster.
3024
3025 The entire byte array is returned if \a len is greater than
3026 size().
3027
3028 Returns an empty QByteArray if \a len is smaller than 0.
3029
3030 \sa first(), last(), startsWith(), chopped(), chop(), truncate()
3031*/
3032
3033/*!
3034 \fn QByteArray QByteArray::right(qsizetype len) const &
3035 \fn QByteArray QByteArray::right(qsizetype len) &&
3036
3037 Returns a byte array that contains the last \a len bytes of this byte array.
3038
3039 If you know that \a len cannot be out of bounds, use last() instead in new
3040 code, because it is faster.
3041
3042 The entire byte array is returned if \a len is greater than
3043 size().
3044
3045 Returns an empty QByteArray if \a len is smaller than 0.
3046
3047 \sa endsWith(), last(), first(), sliced(), chopped(), chop(), truncate(), slice()
3048*/
3049
3050/*!
3051 \fn QByteArray QByteArray::mid(qsizetype pos, qsizetype len) const &
3052 \fn QByteArray QByteArray::mid(qsizetype pos, qsizetype len) &&
3053
3054 Returns a byte array containing \a len bytes from this byte array,
3055 starting at position \a pos.
3056
3057 If you know that \a pos and \a len cannot be out of bounds, use sliced()
3058 instead in new code, because it is faster.
3059
3060 If \a len is -1 (the default), or \a pos + \a len >= size(),
3061 returns a byte array containing all bytes starting at position \a
3062 pos until the end of the byte array.
3063
3064 \sa first(), last(), sliced(), chopped(), chop(), truncate(), slice()
3065*/
3066
3067QByteArray QByteArray::mid(qsizetype pos, qsizetype len) const &
3068{
3069 qsizetype p = pos;
3070 qsizetype l = len;
3071 using namespace QtPrivate;
3072 switch (QContainerImplHelper::mid(size(), &p, &l)) {
3073 case QContainerImplHelper::Null:
3074 return QByteArray();
3075 case QContainerImplHelper::Empty:
3076 {
3077 return QByteArray(DataPointer::fromRawData(&_empty, 0));
3078 }
3079 case QContainerImplHelper::Full:
3080 return *this;
3081 case QContainerImplHelper::Subset:
3082 return sliced(p, l);
3083 }
3084 Q_UNREACHABLE_RETURN(QByteArray());
3085}
3086
3087QByteArray QByteArray::mid(qsizetype pos, qsizetype len) &&
3088{
3089 qsizetype p = pos;
3090 qsizetype l = len;
3091 using namespace QtPrivate;
3092 switch (QContainerImplHelper::mid(size(), &p, &l)) {
3093 case QContainerImplHelper::Null:
3094 return QByteArray();
3095 case QContainerImplHelper::Empty:
3096 resize(0); // keep capacity if we've reserve()d
3097 [[fallthrough]];
3098 case QContainerImplHelper::Full:
3099 return std::move(*this);
3100 case QContainerImplHelper::Subset:
3101 return std::move(*this).sliced(p, l);
3102 }
3103 Q_UNREACHABLE_RETURN(QByteArray());
3104}
3105
3106/*!
3107 \fn QByteArray QByteArray::first(qsizetype n) const &
3108 \fn QByteArray QByteArray::first(qsizetype n) &&
3109 \since 6.0
3110
3111 Returns the first \a n bytes of the byte array.
3112
3113 \note The behavior is undefined when \a n < 0 or \a n > size().
3114
3115 Example:
3116 \snippet code/src_corelib_text_qbytearray.cpp 27
3117
3118 \sa last(), sliced(), startsWith(), chopped(), chop(), truncate(), slice()
3119*/
3120
3121/*!
3122 \fn QByteArray QByteArray::last(qsizetype n) const &
3123 \fn QByteArray QByteArray::last(qsizetype n) &&
3124 \since 6.0
3125
3126 Returns the last \a n bytes of the byte array.
3127
3128 \note The behavior is undefined when \a n < 0 or \a n > size().
3129
3130 Example:
3131 \snippet code/src_corelib_text_qbytearray.cpp 28
3132
3133 \sa first(), sliced(), endsWith(), chopped(), chop(), truncate(), slice()
3134*/
3135
3136/*!
3137 \fn QByteArray QByteArray::sliced(qsizetype pos, qsizetype n) const &
3138 \fn QByteArray QByteArray::sliced(qsizetype pos, qsizetype n) &&
3139 \since 6.0
3140
3141 Returns a byte array containing the \a n bytes of this object starting
3142 at position \a pos.
3143
3144 \note The behavior is undefined when \a pos < 0, \a n < 0,
3145 or \a pos + \a n > size().
3146
3147 Example:
3148 \snippet code/src_corelib_text_qbytearray.cpp 29
3149
3150 \sa first(), last(), chopped(), chop(), truncate(), slice()
3151*/
3152QByteArray QByteArray::sliced_helper(QByteArray &a, qsizetype pos, qsizetype n)
3153{
3154 if (n == 0)
3155 return fromRawData(&_empty, 0);
3156 DataPointer d = std::move(a.d).sliced(pos, n);
3157 d.data()[n] = 0;
3158 return QByteArray(std::move(d));
3159}
3160
3161/*!
3162 \fn QByteArray QByteArray::sliced(qsizetype pos) const &
3163 \fn QByteArray QByteArray::sliced(qsizetype pos) &&
3164 \since 6.0
3165 \overload
3166
3167 Returns a byte array containing the bytes starting at position \a pos
3168 in this object, and extending to the end of this object.
3169
3170 \note The behavior is undefined when \a pos < 0 or \a pos > size().
3171
3172 \sa first(), last(), chopped(), chop(), truncate(), slice()
3173*/
3174
3175/*!
3176 \fn QByteArray &QByteArray::slice(qsizetype pos, qsizetype n)
3177 \since 6.8
3178
3179 Modifies this byte array to start at position \a pos, extending for \a n
3180 bytes, and returns a reference to this byte array.
3181
3182 \note The behavior is undefined if \a pos < 0, \a n < 0,
3183 or \a pos + \a n > size().
3184
3185 Example:
3186 \snippet code/src_corelib_text_qbytearray.cpp 57
3187
3188 \sa sliced(), first(), last(), chopped(), chop(), truncate()
3189*/
3190
3191/*!
3192 \fn QByteArray &QByteArray::slice(qsizetype pos)
3193 \since 6.8
3194 \overload
3195
3196 Modifies this byte array to start at position \a pos, extending to its
3197 end, and returns a reference to this byte array.
3198
3199 \note The behavior is undefined if \a pos < 0 or \a pos > size().
3200
3201 \sa sliced(), first(), last(), chopped(), chop(), truncate()
3202*/
3203
3204/*!
3205 \fn QByteArray QByteArray::chopped(qsizetype len) const &
3206 \fn QByteArray QByteArray::chopped(qsizetype len) &&
3207 \since 5.10
3208
3209 Returns a byte array that contains the leftmost size() - \a len bytes of
3210 this byte array.
3211
3212 \note The behavior is undefined if \a len is negative or greater than size().
3213
3214 \sa endsWith(), first(), last(), sliced(), chop(), truncate(), slice()
3215*/
3216
3217/*!
3218 \fn QByteArray QByteArray::toLower() const
3219
3220 Returns a copy of the byte array in which each ASCII uppercase letter
3221 converted to lowercase.
3222
3223 Example:
3224 \snippet code/src_corelib_text_qbytearray.cpp 30
3225
3226 \sa isLower(), toUpper(), {Character Case}
3227*/
3228
3229static QByteArray toCase(const QByteArray &input, QByteArray *rvalue, uchar (*lookup)(uchar))
3230{
3231 // find the first bad character in input
3232 const char *orig_begin = input.constBegin();
3233 const char *firstBad = orig_begin;
3234 const char *e = input.constEnd();
3235 for ( ; firstBad != e ; ++firstBad) {
3236 uchar ch = uchar(*firstBad);
3237 uchar converted = lookup(ch);
3238 if (ch != converted)
3239 break;
3240 }
3241
3242 if (firstBad == e)
3243 return q_choose_copy_move(input, rvalue);
3244
3245 // transform the rest
3246 QByteArray s = q_choose_copy_move(input, rvalue);
3247 char *b = s.begin(); // will detach if necessary
3248 char *p = b + (firstBad - orig_begin);
3249 e = b + s.size();
3250 for ( ; p != e; ++p)
3251 *p = char(lookup(uchar(*p)));
3252 return s;
3253}
3254
3255QByteArray QByteArray::toLower_helper(const QByteArray &a)
3256{
3257 return toCase(a, nullptr, asciiLower);
3258}
3259
3260QByteArray QByteArray::toLower_helper(QByteArray &a)
3261{
3262 return toCase(a, &a, asciiLower);
3263}
3264
3265/*!
3266 \fn QByteArray QByteArray::toUpper() const
3267
3268 Returns a copy of the byte array in which each ASCII lowercase letter
3269 converted to uppercase.
3270
3271 Example:
3272 \snippet code/src_corelib_text_qbytearray.cpp 31
3273
3274 \sa isUpper(), toLower(), {Character Case}
3275*/
3276
3277QByteArray QByteArray::toUpper_helper(const QByteArray &a)
3278{
3279 return toCase(a, nullptr, asciiUpper);
3280}
3281
3282QByteArray QByteArray::toUpper_helper(QByteArray &a)
3283{
3284 return toCase(a, &a, asciiUpper);
3285}
3286
3287/*! \fn void QByteArray::clear()
3288
3289 Clears the contents of the byte array and makes it null.
3290
3291 \sa resize(), isNull()
3292*/
3293
3294void QByteArray::clear()
3295{
3296 d.clear();
3297}
3298
3299#if !defined(QT_NO_DATASTREAM)
3300
3301/*! \relates QByteArray
3302
3303 Writes byte array \a ba to the stream \a out and returns a reference
3304 to the stream.
3305
3306 \sa {Serializing Qt Data Types}
3307*/
3308
3309QDataStream &operator<<(QDataStream &out, const QByteArray &ba)
3310{
3311 if (ba.isNull() && out.version() >= 6) {
3312 QDataStream::writeQSizeType(out, -1);
3313 return out;
3314 }
3315 return out.writeBytes(ba.constData(), ba.size());
3316}
3317
3318/*! \relates QByteArray
3319
3320 Reads a byte array into \a ba from the stream \a in and returns a
3321 reference to the stream.
3322
3323 \sa {Serializing Qt Data Types}
3324*/
3325
3326QDataStream &operator>>(QDataStream &in, QByteArray &ba)
3327{
3328 ba.clear();
3329
3330 qint64 size = QDataStream::readQSizeType(in);
3331 qsizetype len = size;
3332 if (size != len || size < -1) {
3333 ba.clear();
3334 in.setStatus(QDataStream::SizeLimitExceeded);
3335 return in;
3336 }
3337 if (len == -1) { // null byte-array
3338 ba = QByteArray();
3339 return in;
3340 }
3341
3342 constexpr qsizetype Step = 1024 * 1024;
3343 qsizetype allocated = 0;
3344
3345 do {
3346 qsizetype blockSize = qMin(Step, len - allocated);
3347 ba.resize(allocated + blockSize);
3348 if (in.readRawData(ba.data() + allocated, blockSize) != blockSize) {
3349 ba.clear();
3350 in.setStatus(QDataStream::ReadPastEnd);
3351 return in;
3352 }
3353 allocated += blockSize;
3354 } while (allocated < len);
3355
3356 return in;
3357}
3358#endif // QT_NO_DATASTREAM
3359
3360/*! \fn bool QByteArray::operator==(const QByteArray &lhs, const QByteArray &rhs)
3361 \overload
3362
3363 Returns \c true if byte array \a lhs is equal to byte array \a rhs;
3364 otherwise returns \c false.
3365
3366 \sa QByteArray::compare()
3367*/
3368
3369/*! \fn bool QByteArray::operator==(const QByteArray &lhs, const char * const &rhs)
3370 \overload
3371
3372 Returns \c true if byte array \a lhs is equal to the '\\0'-terminated string
3373 \a rhs; otherwise returns \c false.
3374
3375 \sa QByteArray::compare()
3376*/
3377
3378/*! \fn bool QByteArray::operator==(const char * const &lhs, const QByteArray &rhs)
3379 \overload
3380
3381 Returns \c true if '\\0'-terminated string \a lhs is equal to byte array \a
3382 rhs; otherwise returns \c false.
3383
3384 \sa QByteArray::compare()
3385*/
3386
3387/*! \fn bool QByteArray::operator!=(const QByteArray &lhs, const QByteArray &rhs)
3388 \overload
3389
3390 Returns \c true if byte array \a lhs is not equal to byte array \a rhs;
3391 otherwise returns \c false.
3392
3393 \sa QByteArray::compare()
3394*/
3395
3396/*! \fn bool QByteArray::operator!=(const QByteArray &lhs, const char * const &rhs)
3397 \overload
3398
3399 Returns \c true if byte array \a lhs is not equal to the '\\0'-terminated
3400 string \a rhs; otherwise returns \c false.
3401
3402 \sa QByteArray::compare()
3403*/
3404
3405/*! \fn bool QByteArray::operator!=(const char * const &lhs, const QByteArray &rhs)
3406 \overload
3407
3408 Returns \c true if '\\0'-terminated string \a lhs is not equal to byte array
3409 \a rhs; otherwise returns \c false.
3410
3411 \sa QByteArray::compare()
3412*/
3413
3414/*! \fn bool QByteArray::operator<(const QByteArray &lhs, const QByteArray &rhs)
3415 \overload
3416
3417 Returns \c true if byte array \a lhs is lexically less than byte array
3418 \a rhs; otherwise returns \c false.
3419
3420 \sa QByteArray::compare()
3421*/
3422
3423/*! \fn bool QByteArray::operator<(const QByteArray &lhs, const char * const &rhs)
3424 \overload
3425
3426 Returns \c true if byte array \a lhs is lexically less than the
3427 '\\0'-terminated string \a rhs; otherwise returns \c false.
3428
3429 \sa QByteArray::compare()
3430*/
3431
3432/*! \fn bool QByteArray::operator<(const char * const &lhs, const QByteArray &rhs)
3433 \overload
3434
3435 Returns \c true if '\\0'-terminated string \a lhs is lexically less than byte
3436 array \a rhs; otherwise returns \c false.
3437
3438 \sa QByteArray::compare()
3439*/
3440
3441/*! \fn bool QByteArray::operator<=(const QByteArray &lhs, const QByteArray &rhs)
3442 \overload
3443
3444 Returns \c true if byte array \a lhs is lexically less than or equal
3445 to byte array \a rhs; otherwise returns \c false.
3446
3447 \sa QByteArray::compare()
3448*/
3449
3450/*! \fn bool QByteArray::operator<=(const QByteArray &lhs, const char * const &rhs)
3451 \overload
3452
3453 Returns \c true if byte array \a lhs is lexically less than or equal to the
3454 '\\0'-terminated string \a rhs; otherwise returns \c false.
3455
3456 \sa QByteArray::compare()
3457*/
3458
3459/*! \fn bool QByteArray::operator<=(const char * const &lhs, const QByteArray &rhs)
3460 \overload
3461
3462 Returns \c true if '\\0'-terminated string \a lhs is lexically less than or
3463 equal to byte array \a rhs; otherwise returns \c false.
3464
3465 \sa QByteArray::compare()
3466*/
3467
3468/*! \fn bool QByteArray::operator>(const QByteArray &lhs, const QByteArray &rhs)
3469 \overload
3470
3471 Returns \c true if byte array \a lhs is lexically greater than byte
3472 array \a rhs; otherwise returns \c false.
3473
3474 \sa QByteArray::compare()
3475*/
3476
3477/*! \fn bool QByteArray::operator>(const QByteArray &lhs, const char * const &rhs)
3478 \overload
3479
3480 Returns \c true if byte array \a lhs is lexically greater than the
3481 '\\0'-terminated string \a rhs; otherwise returns \c false.
3482
3483 \sa QByteArray::compare()
3484*/
3485
3486/*! \fn bool QByteArray::operator>(const char * const &lhs, const QByteArray &rhs)
3487 \overload
3488
3489 Returns \c true if '\\0'-terminated string \a lhs is lexically greater than
3490 byte array \a rhs; otherwise returns \c false.
3491
3492 \sa QByteArray::compare()
3493*/
3494
3495/*! \fn bool QByteArray::operator>=(const QByteArray &lhs, const QByteArray &rhs)
3496 \overload
3497
3498 Returns \c true if byte array \a lhs is lexically greater than or
3499 equal to byte array \a rhs; otherwise returns \c false.
3500
3501 \sa QByteArray::compare()
3502*/
3503
3504/*! \fn bool QByteArray::operator>=(const QByteArray &lhs, const char * const &rhs)
3505 \overload
3506
3507 Returns \c true if byte array \a lhs is lexically greater than or equal to
3508 the '\\0'-terminated string \a rhs; otherwise returns \c false.
3509
3510 \sa QByteArray::compare()
3511*/
3512
3513/*! \fn bool QByteArray::operator>=(const char * const &lhs, const QByteArray &rhs)
3514 \overload
3515
3516 Returns \c true if '\\0'-terminated string \a lhs is lexically greater than
3517 or equal to byte array \a rhs; otherwise returns \c false.
3518
3519 \sa QByteArray::compare()
3520*/
3521
3522/*! \fn QByteArray operator+(const QByteArray &a1, const QByteArray &a2)
3523 \relates QByteArray
3524
3525 Returns a byte array that is the result of concatenating byte
3526 array \a a1 and byte array \a a2.
3527
3528 \sa QByteArray::operator+=()
3529*/
3530
3531/*! \fn QByteArray operator+(const QByteArray &a1, const char *a2)
3532 \relates QByteArray
3533
3534 \overload
3535
3536 Returns a byte array that is the result of concatenating byte array \a a1
3537 and '\\0'-terminated string \a a2.
3538*/
3539
3540/*! \fn QByteArray operator+(const QByteArray &a1, char a2)
3541 \relates QByteArray
3542
3543 \overload
3544
3545 Returns a byte array that is the result of concatenating byte
3546 array \a a1 and byte \a a2.
3547*/
3548
3549/*! \fn QByteArray operator+(const char *a1, const QByteArray &a2)
3550 \relates QByteArray
3551
3552 \overload
3553
3554 Returns a byte array that is the result of concatenating '\\0'-terminated
3555 string \a a1 and byte array \a a2.
3556*/
3557
3558/*! \fn QByteArray operator+(char a1, const QByteArray &a2)
3559 \relates QByteArray
3560
3561 \overload
3562
3563 Returns a byte array that is the result of concatenating byte \a a1 and byte
3564 array \a a2.
3565*/
3566
3567/*! \fn QByteArray operator+(const QByteArray &lhs, QByteArrayView rhs)
3568 \fn QByteArray operator+(QByteArrayView lhs, const QByteArray &rhs)
3569 \overload
3570 \since 6.9
3571 \relates QByteArray
3572
3573 Returns a byte array that is the result of concatenating \a lhs and \a rhs.
3574
3575 \sa QByteArray::operator+=()
3576*/
3577
3578/*!
3579 \fn QByteArray QByteArray::simplified() const
3580
3581 Returns a copy of this byte array that has spacing characters removed from
3582 the start and end, and in which each sequence of internal spacing characters
3583 is replaced with a single space.
3584
3585 The spacing characters are those for which the standard C++ \c isspace()
3586 function returns \c true in the C locale; these are the ASCII characters
3587 tabulation '\\t', line feed '\\n', carriage return '\\r', vertical
3588 tabulation '\\v', form feed '\\f', and space ' '.
3589
3590 Example:
3591 \snippet code/src_corelib_text_qbytearray.cpp 32
3592
3593 \sa trimmed(), QChar::SpecialCharacter, {Spacing Characters}
3594*/
3595QByteArray QByteArray::simplified_helper(const QByteArray &a)
3596{
3597 return QStringAlgorithms<const QByteArray>::simplified_helper(a);
3598}
3599
3600QByteArray QByteArray::simplified_helper(QByteArray &a)
3601{
3602 return QStringAlgorithms<QByteArray>::simplified_helper(a);
3603}
3604
3605/*!
3606 \fn QByteArray QByteArray::trimmed() const
3607
3608 Returns a copy of this byte array with spacing characters removed from the
3609 start and end.
3610
3611 The spacing characters are those for which the standard C++ \c isspace()
3612 function returns \c true in the C locale; these are the ASCII characters
3613 tabulation '\\t', line feed '\\n', carriage return '\\r', vertical
3614 tabulation '\\v', form feed '\\f', and space ' '.
3615
3616 Example:
3617 \snippet code/src_corelib_text_qbytearray.cpp 33
3618
3619 Unlike simplified(), \l {QByteArray::trimmed()}{trimmed()} leaves internal
3620 spacing unchanged.
3621
3622 \sa simplified(), QChar::SpecialCharacter, {Spacing Characters}
3623*/
3624QByteArray QByteArray::trimmed_helper(const QByteArray &a)
3625{
3626 return QStringAlgorithms<const QByteArray>::trimmed_helper(a);
3627}
3628
3629QByteArray QByteArray::trimmed_helper(QByteArray &a)
3630{
3631 return QStringAlgorithms<QByteArray>::trimmed_helper(a);
3632}
3633
3634QByteArrayView QtPrivate::trimmed(QByteArrayView view) noexcept
3635{
3636 const auto [start, stop] = QStringAlgorithms<QByteArrayView>::trimmed_helper_positions(view);
3637 return QByteArrayView(start, stop);
3638}
3639
3640/*!
3641 Returns a byte array of size \a width that contains this byte array padded
3642 with the \a fill byte.
3643
3644 If \a truncate is false and the size() of the byte array is more
3645 than \a width, then the returned byte array is a copy of this byte
3646 array.
3647
3648 If \a truncate is true and the size() of the byte array is more
3649 than \a width, then any bytes in a copy of the byte array
3650 after position \a width are removed, and the copy is returned.
3651
3652 Example:
3653 \snippet code/src_corelib_text_qbytearray.cpp 34
3654
3655 \sa rightJustified()
3656*/
3657
3658QByteArray QByteArray::leftJustified(qsizetype width, char fill, bool truncate) const
3659{
3660 QByteArray result;
3661 qsizetype len = size();
3662 qsizetype padlen = width - len;
3663 if (padlen > 0) {
3664 result.resize(len+padlen);
3665 if (len)
3666 memcpy(result.d.data(), data(), len);
3667 memset(result.d.data()+len, fill, padlen);
3668 } else {
3669 if (truncate)
3670 result = left(width);
3671 else
3672 result = *this;
3673 }
3674 return result;
3675}
3676
3677/*!
3678 Returns a byte array of size \a width that contains the \a fill byte
3679 followed by this byte array.
3680
3681 If \a truncate is false and the size of the byte array is more
3682 than \a width, then the returned byte array is a copy of this byte
3683 array.
3684
3685 If \a truncate is true and the size of the byte array is more
3686 than \a width, then the resulting byte array is truncated at
3687 position \a width.
3688
3689 Example:
3690 \snippet code/src_corelib_text_qbytearray.cpp 35
3691
3692 \sa leftJustified()
3693*/
3694
3695QByteArray QByteArray::rightJustified(qsizetype width, char fill, bool truncate) const
3696{
3697 QByteArray result;
3698 qsizetype len = size();
3699 qsizetype padlen = width - len;
3700 if (padlen > 0) {
3701 result.resize(len+padlen);
3702 if (len)
3703 memcpy(result.d.data()+padlen, data(), len);
3704 memset(result.d.data(), fill, padlen);
3705 } else {
3706 if (truncate)
3707 result = left(width);
3708 else
3709 result = *this;
3710 }
3711 return result;
3712}
3713
3714auto QtPrivate::toSignedInteger(QByteArrayView data, int base) -> ParsedNumber<qlonglong>
3715{
3716#if defined(QT_CHECK_RANGE)
3717 if (base != 0 && (base < 2 || base > 36)) {
3718 qWarning("QByteArray::toIntegral: Invalid base %d", base);
3719 base = 10;
3720 }
3721#endif
3722 if (data.isEmpty())
3723 return {};
3724
3725 const QSimpleParsedNumber r = QLocaleData::bytearrayToLongLong(data, base);
3726 if (r.ok())
3727 return ParsedNumber(r.result);
3728 return {};
3729}
3730
3731auto QtPrivate::toUnsignedInteger(QByteArrayView data, int base) -> ParsedNumber<qulonglong>
3732{
3733#if defined(QT_CHECK_RANGE)
3734 if (base != 0 && (base < 2 || base > 36)) {
3735 qWarning("QByteArray::toIntegral: Invalid base %d", base);
3736 base = 10;
3737 }
3738#endif
3739 if (data.isEmpty())
3740 return {};
3741
3742 const QSimpleParsedNumber r = QLocaleData::bytearrayToUnsLongLong(data, base);
3743 if (r.ok())
3744 return ParsedNumber(r.result);
3745 return {};
3746}
3747
3748/*!
3749 Returns the byte array converted to a \c {long long} using base \a base,
3750 which is ten by default. Bases 0 and 2 through 36 are supported, using
3751 letters for digits beyond 9; A is ten, B is eleven and so on.
3752
3753 If \a base is 0, the base is determined automatically using the following
3754 rules: If the byte array begins with "0x", it is assumed to be hexadecimal
3755 (base 16); otherwise, if it begins with "0b", it is assumed to be binary
3756 (base 2); otherwise, if it begins with "0", it is assumed to be octal
3757 (base 8); otherwise it is assumed to be decimal.
3758
3759 Returns 0 if the conversion fails.
3760
3761 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3762 to \c false, and success by setting *\a{ok} to \c true.
3763
3764 \note The conversion of the number is performed in the default C locale,
3765 regardless of the user's locale. Use QLocale to perform locale-aware
3766 conversions between numbers and strings.
3767
3768 \note Support for the "0b" prefix was added in Qt 6.4.
3769
3770 \sa number()
3771*/
3772
3773qlonglong QByteArray::toLongLong(bool *ok, int base) const
3774{
3775 return QtPrivate::toIntegral<qlonglong>(qToByteArrayViewIgnoringNull(*this), ok, base);
3776}
3777
3778/*!
3779 Returns the byte array converted to an \c {unsigned long long} using base \a
3780 base, which is ten by default. Bases 0 and 2 through 36 are supported, using
3781 letters for digits beyond 9; A is ten, B is eleven and so on.
3782
3783 If \a base is 0, the base is determined automatically using the following
3784 rules: If the byte array begins with "0x", it is assumed to be hexadecimal
3785 (base 16); otherwise, if it begins with "0b", it is assumed to be binary
3786 (base 2); otherwise, if it begins with "0", it is assumed to be octal
3787 (base 8); otherwise it is assumed to be decimal.
3788
3789 Returns 0 if the conversion fails.
3790
3791 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3792 to \c false, and success by setting *\a{ok} to \c true.
3793
3794 \note The conversion of the number is performed in the default C locale,
3795 regardless of the user's locale. Use QLocale to perform locale-aware
3796 conversions between numbers and strings.
3797
3798 \note Support for the "0b" prefix was added in Qt 6.4.
3799
3800 \sa number()
3801*/
3802
3803qulonglong QByteArray::toULongLong(bool *ok, int base) const
3804{
3805 return QtPrivate::toIntegral<qulonglong>(qToByteArrayViewIgnoringNull(*this), ok, base);
3806}
3807
3808/*!
3809 Returns the byte array converted to an \c int using base \a base, which is
3810 ten by default. Bases 0 and 2 through 36 are supported, using letters for
3811 digits beyond 9; A is ten, B is eleven and so on.
3812
3813 If \a base is 0, the base is determined automatically using the following
3814 rules: If the byte array begins with "0x", it is assumed to be hexadecimal
3815 (base 16); otherwise, if it begins with "0b", it is assumed to be binary
3816 (base 2); otherwise, if it begins with "0", it is assumed to be octal
3817 (base 8); otherwise it is assumed to be decimal.
3818
3819 Returns 0 if the conversion fails.
3820
3821 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3822 to \c false, and success by setting *\a{ok} to \c true.
3823
3824 \snippet code/src_corelib_text_qbytearray.cpp 36
3825
3826 \note The conversion of the number is performed in the default C locale,
3827 regardless of the user's locale. Use QLocale to perform locale-aware
3828 conversions between numbers and strings.
3829
3830 \note Support for the "0b" prefix was added in Qt 6.4.
3831
3832 \sa number()
3833*/
3834
3835int QByteArray::toInt(bool *ok, int base) const
3836{
3837 return QtPrivate::toIntegral<int>(qToByteArrayViewIgnoringNull(*this), ok, base);
3838}
3839
3840/*!
3841 Returns the byte array converted to an \c {unsigned int} using base \a base,
3842 which is ten by default. Bases 0 and 2 through 36 are supported, using
3843 letters for digits beyond 9; A is ten, B is eleven and so on.
3844
3845 If \a base is 0, the base is determined automatically using the following
3846 rules: If the byte array begins with "0x", it is assumed to be hexadecimal
3847 (base 16); otherwise, if it begins with "0b", it is assumed to be binary
3848 (base 2); otherwise, if it begins with "0", it is assumed to be octal
3849 (base 8); otherwise it is assumed to be decimal.
3850
3851 Returns 0 if the conversion fails.
3852
3853 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3854 to \c false, and success by setting *\a{ok} to \c true.
3855
3856 \note The conversion of the number is performed in the default C locale,
3857 regardless of the user's locale. Use QLocale to perform locale-aware
3858 conversions between numbers and strings.
3859
3860 \note Support for the "0b" prefix was added in Qt 6.4.
3861
3862 \sa number()
3863*/
3864
3865uint QByteArray::toUInt(bool *ok, int base) const
3866{
3867 return QtPrivate::toIntegral<uint>(qToByteArrayViewIgnoringNull(*this), ok, base);
3868}
3869
3870/*!
3871 \since 4.1
3872
3873 Returns the byte array converted to a \c long int using base \a base, which
3874 is ten by default. Bases 0 and 2 through 36 are supported, using letters for
3875 digits beyond 9; A is ten, B is eleven and so on.
3876
3877 If \a base is 0, the base is determined automatically using the following
3878 rules: If the byte array begins with "0x", it is assumed to be hexadecimal
3879 (base 16); otherwise, if it begins with "0b", it is assumed to be binary
3880 (base 2); otherwise, if it begins with "0", it is assumed to be octal
3881 (base 8); otherwise it is assumed to be decimal.
3882
3883 Returns 0 if the conversion fails.
3884
3885 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3886 to \c false, and success by setting *\a{ok} to \c true.
3887
3888 \snippet code/src_corelib_text_qbytearray.cpp 37
3889
3890 \note The conversion of the number is performed in the default C locale,
3891 regardless of the user's locale. Use QLocale to perform locale-aware
3892 conversions between numbers and strings.
3893
3894 \note Support for the "0b" prefix was added in Qt 6.4.
3895
3896 \sa number()
3897*/
3898long QByteArray::toLong(bool *ok, int base) const
3899{
3900 return QtPrivate::toIntegral<long>(qToByteArrayViewIgnoringNull(*this), ok, base);
3901}
3902
3903/*!
3904 \since 4.1
3905
3906 Returns the byte array converted to an \c {unsigned long int} using base \a
3907 base, which is ten by default. Bases 0 and 2 through 36 are supported, using
3908 letters for digits beyond 9; A is ten, B is eleven and so on.
3909
3910 If \a base is 0, the base is determined automatically using the following
3911 rules: If the byte array begins with "0x", it is assumed to be hexadecimal
3912 (base 16); otherwise, if it begins with "0b", it is assumed to be binary
3913 (base 2); otherwise, if it begins with "0", it is assumed to be octal
3914 (base 8); otherwise it is assumed to be decimal.
3915
3916 Returns 0 if the conversion fails.
3917
3918 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3919 to \c false, and success by setting *\a{ok} to \c true.
3920
3921 \note The conversion of the number is performed in the default C locale,
3922 regardless of the user's locale. Use QLocale to perform locale-aware
3923 conversions between numbers and strings.
3924
3925 \note Support for the "0b" prefix was added in Qt 6.4.
3926
3927 \sa number()
3928*/
3929ulong QByteArray::toULong(bool *ok, int base) const
3930{
3931 return QtPrivate::toIntegral<ulong>(qToByteArrayViewIgnoringNull(*this), ok, base);
3932}
3933
3934/*!
3935 Returns the byte array converted to a \c short using base \a base, which is
3936 ten by default. Bases 0 and 2 through 36 are supported, using letters for
3937 digits beyond 9; A is ten, B is eleven and so on.
3938
3939 If \a base is 0, the base is determined automatically using the following
3940 rules: If the byte array begins with "0x", it is assumed to be hexadecimal
3941 (base 16); otherwise, if it begins with "0b", it is assumed to be binary
3942 (base 2); otherwise, if it begins with "0", it is assumed to be octal
3943 (base 8); otherwise it is assumed to be decimal.
3944
3945 Returns 0 if the conversion fails.
3946
3947 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3948 to \c false, and success by setting *\a{ok} to \c true.
3949
3950 \note The conversion of the number is performed in the default C locale,
3951 regardless of the user's locale. Use QLocale to perform locale-aware
3952 conversions between numbers and strings.
3953
3954 \note Support for the "0b" prefix was added in Qt 6.4.
3955
3956 \sa number()
3957*/
3958
3959short QByteArray::toShort(bool *ok, int base) const
3960{
3961 return QtPrivate::toIntegral<short>(qToByteArrayViewIgnoringNull(*this), ok, base);
3962}
3963
3964/*!
3965 Returns the byte array converted to an \c {unsigned short} using base \a
3966 base, which is ten by default. Bases 0 and 2 through 36 are supported, using
3967 letters for digits beyond 9; A is ten, B is eleven and so on.
3968
3969 If \a base is 0, the base is determined automatically using the following
3970 rules: If the byte array begins with "0x", it is assumed to be hexadecimal
3971 (base 16); otherwise, if it begins with "0b", it is assumed to be binary
3972 (base 2); otherwise, if it begins with "0", it is assumed to be octal
3973 (base 8); otherwise it is assumed to be decimal.
3974
3975 Returns 0 if the conversion fails.
3976
3977 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
3978 to \c false, and success by setting *\a{ok} to \c true.
3979
3980 \note The conversion of the number is performed in the default C locale,
3981 regardless of the user's locale. Use QLocale to perform locale-aware
3982 conversions between numbers and strings.
3983
3984 \note Support for the "0b" prefix was added in Qt 6.4.
3985
3986 \sa number()
3987*/
3988
3989ushort QByteArray::toUShort(bool *ok, int base) const
3990{
3991 return QtPrivate::toIntegral<ushort>(qToByteArrayViewIgnoringNull(*this), ok, base);
3992}
3993
3994/*!
3995 Returns the byte array converted to a \c double value.
3996
3997 Returns an infinity if the conversion overflows or 0.0 if the
3998 conversion fails for other reasons (e.g. underflow).
3999
4000 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
4001 to \c false, and success by setting *\a{ok} to \c true.
4002
4003 \snippet code/src_corelib_text_qbytearray.cpp 38
4004
4005 \warning The QByteArray content may only contain valid numerical characters
4006 which includes the plus/minus sign, the character e used in scientific
4007 notation, and the decimal point. Including the unit or additional characters
4008 leads to a conversion error.
4009
4010 \note The conversion of the number is performed in the default C locale,
4011 regardless of the user's locale. Use QLocale to perform locale-aware
4012 conversions between numbers and strings.
4013
4014 This function ignores leading and trailing whitespace.
4015
4016 \sa number()
4017*/
4018
4019double QByteArray::toDouble(bool *ok) const
4020{
4021 return QByteArrayView(*this).toDouble(ok);
4022}
4023
4024auto QtPrivate::toDouble(QByteArrayView a) noexcept -> ParsedNumber<double>
4025{
4026 a = a.trimmed();
4027 auto r = qt_asciiToDouble(a.data(), a.size());
4028 if (r.ok())
4029 return ParsedNumber{r.result};
4030 else
4031 return {};
4032}
4033
4034/*!
4035 Returns the byte array converted to a \c float value.
4036
4037 Returns an infinity if the conversion overflows or 0.0 if the
4038 conversion fails for other reasons (e.g. underflow).
4039
4040 If \a ok is not \nullptr, failure is reported by setting *\a{ok}
4041 to \c false, and success by setting *\a{ok} to \c true.
4042
4043 \snippet code/src_corelib_text_qbytearray.cpp 38float
4044
4045 \warning The QByteArray content may only contain valid numerical characters
4046 which includes the plus/minus sign, the character e used in scientific
4047 notation, and the decimal point. Including the unit or additional characters
4048 leads to a conversion error.
4049
4050 \note The conversion of the number is performed in the default C locale,
4051 regardless of the user's locale. Use QLocale to perform locale-aware
4052 conversions between numbers and strings.
4053
4054 This function ignores leading and trailing whitespace.
4055
4056 \sa number()
4057*/
4058
4059float QByteArray::toFloat(bool *ok) const
4060{
4061 return QLocaleData::convertDoubleToFloat(toDouble(ok), ok);
4062}
4063
4064auto QtPrivate::toFloat(QByteArrayView a) noexcept -> ParsedNumber<float>
4065{
4066 if (const auto r = toDouble(a)) {
4067 bool ok = true;
4068 const auto f = QLocaleData::convertDoubleToFloat(*r, &ok);
4069 if (ok)
4070 return ParsedNumber(f);
4071 }
4072 return {};
4073}
4074
4075/*!
4076 \since 5.2
4077
4078 Returns a copy of the byte array, encoded using the options \a options.
4079
4080 \snippet code/src_corelib_text_qbytearray.cpp 39
4081
4082 The algorithm used to encode Base64-encoded data is defined in \l{RFC 4648}.
4083
4084 \sa fromBase64()
4085*/
4086QByteArray QByteArray::toBase64(Base64Options options) const
4087{
4088 constexpr char alphabet_base64[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
4089 "ghijklmn" "opqrstuv" "wxyz0123" "456789+/";
4090 constexpr char alphabet_base64url[] = "ABCDEFGH" "IJKLMNOP" "QRSTUVWX" "YZabcdef"
4091 "ghijklmn" "opqrstuv" "wxyz0123" "456789-_";
4092 const char *const alphabet = options & Base64UrlEncoding ? alphabet_base64url : alphabet_base64;
4093 constexpr char padchar = '=';
4094 qsizetype padlen = 0;
4095
4096 const qsizetype sz = size();
4097
4098 QByteArray tmp((sz + 2) / 3 * 4, Qt::Uninitialized);
4099
4100 qsizetype i = 0;
4101 char *out = tmp.data();
4102 while (i < sz) {
4103 // encode 3 bytes at a time
4104 int chunk = 0;
4105 chunk |= int(uchar(data()[i++])) << 16;
4106 if (i == sz) {
4107 padlen = 2;
4108 } else {
4109 chunk |= int(uchar(data()[i++])) << 8;
4110 if (i == sz)
4111 padlen = 1;
4112 else
4113 chunk |= int(uchar(data()[i++]));
4114 }
4115
4116 int j = (chunk & 0x00fc0000) >> 18;
4117 int k = (chunk & 0x0003f000) >> 12;
4118 int l = (chunk & 0x00000fc0) >> 6;
4119 int m = (chunk & 0x0000003f);
4120 *out++ = alphabet[j];
4121 *out++ = alphabet[k];
4122
4123 if (padlen > 1) {
4124 if ((options & OmitTrailingEquals) == 0)
4125 *out++ = padchar;
4126 } else {
4127 *out++ = alphabet[l];
4128 }
4129 if (padlen > 0) {
4130 if ((options & OmitTrailingEquals) == 0)
4131 *out++ = padchar;
4132 } else {
4133 *out++ = alphabet[m];
4134 }
4135 }
4136 Q_ASSERT((options & OmitTrailingEquals) || (out == tmp.size() + tmp.data()));
4137 if (options & OmitTrailingEquals)
4138 tmp.truncate(out - tmp.data());
4139 return tmp;
4140}
4141
4142/*!
4143 \fn QByteArray &QByteArray::setNum(int n, int base)
4144
4145 Represent the whole number \a n as text.
4146
4147 Sets this byte array to a string representing \a n in base \a base (ten by
4148 default) and returns a reference to this byte array. Bases 2 through 36 are
4149 supported, using letters for digits beyond 9; A is ten, B is eleven and so
4150 on.
4151
4152 Example:
4153 \snippet code/src_corelib_text_qbytearray.cpp 40
4154
4155 \note The format of the number is not localized; the default C locale is
4156 used regardless of the user's locale. Use QLocale to perform locale-aware
4157 conversions between numbers and strings.
4158
4159 \sa number(), toInt()
4160*/
4161
4162/*!
4163 \fn QByteArray &QByteArray::setNum(uint n, int base)
4164 \overload
4165
4166 \sa toUInt()
4167*/
4168
4169/*!
4170 \fn QByteArray &QByteArray::setNum(long n, int base)
4171 \overload
4172
4173 \sa toLong()
4174*/
4175
4176/*!
4177 \fn QByteArray &QByteArray::setNum(ulong n, int base)
4178 \overload
4179
4180 \sa toULong()
4181*/
4182
4183/*!
4184 \fn QByteArray &QByteArray::setNum(short n, int base)
4185 \overload
4186
4187 \sa toShort()
4188*/
4189
4190/*!
4191 \fn QByteArray &QByteArray::setNum(ushort n, int base)
4192 \overload
4193
4194 \sa toUShort()
4195*/
4196
4197/*!
4198 \overload
4199
4200 \sa toLongLong()
4201*/
4202QByteArray &QByteArray::setNum(qlonglong n, int base)
4203{
4204 constexpr int buffsize = 66; // big enough for MAX_ULLONG in base 2
4205 char buff[buffsize];
4206 char *p;
4207
4208 if (n < 0) {
4209 // Take care to avoid overflow on negating min value:
4210 p = qulltoa2(buff + buffsize, qulonglong(-(1 + n)) + 1, base);
4211 *--p = '-';
4212 } else {
4213 p = qulltoa2(buff + buffsize, qulonglong(n), base);
4214 }
4215
4216 return assign(QByteArrayView{p, buff + buffsize});
4217}
4218
4219/*!
4220 \overload
4221
4222 \sa toULongLong()
4223*/
4224
4225QByteArray &QByteArray::setNum(qulonglong n, int base)
4226{
4227 constexpr int buffsize = 66; // big enough for MAX_ULLONG in base 2
4228 char buff[buffsize];
4229 char *p = qulltoa2(buff + buffsize, n, base);
4230
4231 return assign(QByteArrayView{p, buff + buffsize});
4232}
4233
4234/*!
4235 \overload
4236//! [set-num]
4237 Represent the floating-point number \a n as text.
4238
4239 Sets this byte array to a string representing \a n, with a given \a format
4240 and \a precision (with the same meanings as for \l {QLocale::toString(double,
4241 char, int)}), and returns a reference to this byte array.
4242//! [set-num]
4243 \sa toDouble(), QLocale::FloatingPointPrecisionOption
4244*/
4245
4246QByteArray &QByteArray::setNum(double n, char format, int precision)
4247{
4248 return *this = QByteArray::number(n, format, precision);
4249}
4250
4251/*!
4252 \overload
4253 \fn QByteArray &QByteArray::setNum(float n, char format, int precision)
4254
4255 \include qbytearray.cpp set-num
4256
4257 \sa toFloat(), QLocale::FloatingPointPrecisionOption
4258*/
4259
4260/*!
4261 Returns a byte-array representing the whole number \a n as text.
4262
4263 Returns a byte array containing a string representing \a n, using the
4264 specified \a base (ten by default). Bases 2 through 36 are supported, using
4265 letters for digits beyond 9: A is ten, B is eleven and so on.
4266
4267 Example:
4268 \snippet code/src_corelib_text_qbytearray.cpp 41
4269
4270 \note The format of the number is not localized; the default C locale is
4271 used regardless of the user's locale. Use QLocale to perform locale-aware
4272 conversions between numbers and strings.
4273
4274 \sa setNum(), toInt()
4275*/
4276QByteArray QByteArray::number(int n, int base)
4277{
4278 QByteArray s;
4279 s.setNum(n, base);
4280 return s;
4281}
4282
4283/*!
4284 \overload
4285
4286 \sa toUInt()
4287*/
4288QByteArray QByteArray::number(uint n, int base)
4289{
4290 QByteArray s;
4291 s.setNum(n, base);
4292 return s;
4293}
4294
4295/*!
4296 \overload
4297
4298 \sa toLong()
4299*/
4300QByteArray QByteArray::number(long n, int base)
4301{
4302 QByteArray s;
4303 s.setNum(n, base);
4304 return s;
4305}
4306
4307/*!
4308 \overload
4309
4310 \sa toULong()
4311*/
4312QByteArray QByteArray::number(ulong n, int base)
4313{
4314 QByteArray s;
4315 s.setNum(n, base);
4316 return s;
4317}
4318
4319/*!
4320 \overload
4321
4322 \sa toLongLong()
4323*/
4324QByteArray QByteArray::number(qlonglong n, int base)
4325{
4326 QByteArray s;
4327 s.setNum(n, base);
4328 return s;
4329}
4330
4331/*!
4332 \overload
4333
4334 \sa toULongLong()
4335*/
4336QByteArray QByteArray::number(qulonglong n, int base)
4337{
4338 QByteArray s;
4339 s.setNum(n, base);
4340 return s;
4341}
4342
4343/*!
4344 \overload
4345 Returns a byte-array representing the floating-point number \a n as text.
4346
4347 Returns a byte array containing a string representing \a n, with a given \a
4348 format and \a precision, with the same meanings as for \l
4349 {QLocale::toString(double, char, int)}. For example:
4350
4351 \snippet code/src_corelib_text_qbytearray.cpp 42
4352
4353 \sa toDouble(), QLocale::FloatingPointPrecisionOption
4354*/
4355QByteArray QByteArray::number(double n, char format, int precision)
4356{
4358
4359 switch (QtMiscUtils::toAsciiLower(format)) {
4360 case 'f':
4362 break;
4363 case 'e':
4365 break;
4366 case 'g':
4368 break;
4369 default:
4370#if defined(QT_CHECK_RANGE)
4371 qWarning("QByteArray::setNum: Invalid format char '%c'", format);
4372#endif
4373 break;
4374 }
4375
4376 return qdtoAscii(n, form, precision, isUpperCaseAscii(format));
4377}
4378
4379/*!
4380 \fn QByteArray QByteArray::fromRawData(const char *data, qsizetype size) constexpr
4381
4382 Constructs a QByteArray that uses the first \a size bytes of the
4383 \a data array. The bytes are \e not copied. The QByteArray will
4384 contain the \a data pointer. The caller guarantees that \a data
4385 will not be deleted or modified as long as this QByteArray and any
4386 copies of it exist that have not been modified. In other words,
4387 because QByteArray is an \l{implicitly shared} class and the
4388 instance returned by this function contains the \a data pointer,
4389 the caller must not delete \a data or modify it directly as long
4390 as the returned QByteArray and any copies exist. However,
4391 QByteArray does not take ownership of \a data, so the QByteArray
4392 destructor will never delete the raw \a data, even when the
4393 last QByteArray referring to \a data is destroyed.
4394
4395 A subsequent attempt to modify the contents of the returned
4396 QByteArray or any copy made from it will cause it to create a deep
4397 copy of the \a data array before doing the modification. This
4398 ensures that the raw \a data array itself will never be modified
4399 by QByteArray.
4400
4401 Here is an example of how to read data using a QDataStream on raw
4402 data in memory without copying the raw data into a QByteArray:
4403
4404 \snippet code/src_corelib_text_qbytearray.cpp 43
4405
4406 \warning A byte array created with fromRawData() is \e not '\\0'-terminated,
4407 unless the raw data contains a '\\0' byte at position \a size. While that
4408 does not matter for QDataStream or functions like indexOf(), passing the
4409 byte array to a function accepting a \c{const char *} expected to be
4410 '\\0'-terminated will fail.
4411
4412 \sa setRawData(), data(), constData(), nullTerminate(), nullTerminated()
4413*/
4414
4415/*!
4416 \since 4.7
4417
4418 Resets the QByteArray to use the first \a size bytes of the
4419 \a data array. The bytes are \e not copied. The QByteArray will
4420 contain the \a data pointer. The caller guarantees that \a data
4421 will not be deleted or modified as long as this QByteArray and any
4422 copies of it exist that have not been modified.
4423
4424 This function can be used instead of fromRawData() to re-use
4425 existing QByteArray objects to save memory re-allocations.
4426
4427 \sa fromRawData(), data(), constData(), nullTerminate(), nullTerminated()
4428*/
4429QByteArray &QByteArray::setRawData(const char *data, qsizetype size)
4430{
4431 if (!data || !size)
4432 clear();
4433 else
4434 *this = fromRawData(data, size);
4435 return *this;
4436}
4437
4438namespace {
4439struct fromBase64_helper_result {
4440 qsizetype decodedLength;
4441 QByteArray::Base64DecodingStatus status;
4442};
4443
4444fromBase64_helper_result fromBase64_helper(const char *input, qsizetype inputSize,
4445 char *output /* may alias input */,
4446 QByteArray::Base64Options options)
4447{
4448 fromBase64_helper_result result{ 0, QByteArray::Base64DecodingStatus::Ok };
4449
4450 unsigned int buf = 0;
4451 int nbits = 0;
4452
4453 qsizetype offset = 0;
4454 for (qsizetype i = 0; i < inputSize; ++i) {
4455 int ch = input[i];
4456 int d;
4457
4458 if (ch >= 'A' && ch <= 'Z') {
4459 d = ch - 'A';
4460 } else if (ch >= 'a' && ch <= 'z') {
4461 d = ch - 'a' + 26;
4462 } else if (ch >= '0' && ch <= '9') {
4463 d = ch - '0' + 52;
4464 } else if (ch == '+' && (options & QByteArray::Base64UrlEncoding) == 0) {
4465 d = 62;
4466 } else if (ch == '-' && (options & QByteArray::Base64UrlEncoding) != 0) {
4467 d = 62;
4468 } else if (ch == '/' && (options & QByteArray::Base64UrlEncoding) == 0) {
4469 d = 63;
4470 } else if (ch == '_' && (options & QByteArray::Base64UrlEncoding) != 0) {
4471 d = 63;
4472 } else {
4473 if (options & QByteArray::AbortOnBase64DecodingErrors) {
4474 if (ch == '=') {
4475 // can have 1 or 2 '=' signs, in both cases padding base64Size to
4476 // a multiple of 4. Any other case is illegal.
4477 if ((inputSize % 4) != 0) {
4478 result.status = QByteArray::Base64DecodingStatus::IllegalInputLength;
4479 return result;
4480 } else if ((i == inputSize - 1) ||
4481 (i == inputSize - 2 && input[++i] == '=')) {
4482 d = -1; // ... and exit the loop, normally
4483 } else {
4484 result.status = QByteArray::Base64DecodingStatus::IllegalPadding;
4485 return result;
4486 }
4487 } else {
4488 result.status = QByteArray::Base64DecodingStatus::IllegalCharacter;
4489 return result;
4490 }
4491 } else {
4492 d = -1;
4493 }
4494 }
4495
4496 if (d != -1) {
4497 buf = (buf << 6) | d;
4498 nbits += 6;
4499 if (nbits >= 8) {
4500 nbits -= 8;
4501 Q_ASSERT(offset < i);
4502 output[offset++] = buf >> nbits;
4503 buf &= (1 << nbits) - 1;
4504 }
4505 }
4506 }
4507
4508 result.decodedLength = offset;
4509 return result;
4510}
4511} // anonymous namespace
4512
4513/*!
4514 \fn QByteArray::FromBase64Result QByteArray::fromBase64Encoding(QByteArray &&base64, Base64Options options)
4515 \fn QByteArray::FromBase64Result QByteArray::fromBase64Encoding(const QByteArray &base64, Base64Options options)
4516 \since 5.15
4517 \overload
4518
4519 Decodes the Base64 array \a base64, using the options
4520 defined by \a options. If \a options contains \c{IgnoreBase64DecodingErrors}
4521 (the default), the input is not checked for validity; invalid
4522 characters in the input are skipped, enabling the decoding process to
4523 continue with subsequent characters. If \a options contains
4524 \c{AbortOnBase64DecodingErrors}, then decoding will stop at the first
4525 invalid character.
4526
4527 For example:
4528
4529 \snippet code/src_corelib_text_qbytearray.cpp 44ter
4530
4531 The algorithm used to decode Base64-encoded data is defined in \l{RFC 4648}.
4532
4533 Returns a QByteArrayFromBase64Result object, containing the decoded
4534 data and a flag telling whether decoding was successful. If the
4535 \c{AbortOnBase64DecodingErrors} option was passed and the input
4536 data was invalid, it is unspecified what the decoded data contains.
4537
4538 \sa toBase64()
4539*/
4540QByteArray::FromBase64Result QByteArray::fromBase64Encoding(QByteArray &&base64, Base64Options options)
4541{
4542 // try to avoid a detach when calling data(), as it would over-allocate
4543 // (we need less space when decoding than the one required by the full copy)
4544 if (base64.isDetached()) {
4545 const auto base64result = fromBase64_helper(base64.data(),
4546 base64.size(),
4547 base64.data(), // in-place
4548 options);
4549 base64.truncate(base64result.decodedLength);
4550 return { std::move(base64), base64result.status };
4551 }
4552
4553 return fromBase64Encoding(base64, options);
4554}
4555
4556
4557QByteArray::FromBase64Result QByteArray::fromBase64Encoding(const QByteArray &base64, Base64Options options)
4558{
4559 const auto base64Size = base64.size();
4560 QByteArray result((base64Size * 3) / 4, Qt::Uninitialized);
4561 const auto base64result = fromBase64_helper(base64.data(),
4562 base64Size,
4563 const_cast<char *>(result.constData()),
4564 options);
4565 result.truncate(base64result.decodedLength);
4566 return { std::move(result), base64result.status };
4567}
4568
4569/*!
4570 \since 5.2
4571
4572 Returns a decoded copy of the Base64 array \a base64, using the options
4573 defined by \a options. If \a options contains \c{IgnoreBase64DecodingErrors}
4574 (the default), the input is not checked for validity; invalid
4575 characters in the input are skipped, enabling the decoding process to
4576 continue with subsequent characters. If \a options contains
4577 \c{AbortOnBase64DecodingErrors}, then decoding will stop at the first
4578 invalid character.
4579
4580 For example:
4581
4582 \snippet code/src_corelib_text_qbytearray.cpp 44
4583
4584 The algorithm used to decode Base64-encoded data is defined in \l{RFC 4648}.
4585
4586 Returns the decoded data, or, if the \c{AbortOnBase64DecodingErrors}
4587 option was passed and the input data was invalid, an empty byte array.
4588
4589 \note The fromBase64Encoding() function is recommended in new code.
4590
4591 \sa toBase64(), fromBase64Encoding()
4592*/
4593QByteArray QByteArray::fromBase64(const QByteArray &base64, Base64Options options)
4594{
4595 if (auto result = fromBase64Encoding(base64, options))
4596 return std::move(result.decoded);
4597 return QByteArray();
4598}
4599
4600/*!
4601 Returns a decoded copy of the hex encoded array \a hexEncoded. Input is not
4602 checked for validity; invalid characters in the input are skipped, enabling
4603 the decoding process to continue with subsequent characters.
4604
4605 For example:
4606
4607 \snippet code/src_corelib_text_qbytearray.cpp 45
4608
4609 \sa toHex()
4610*/
4611QByteArray QByteArray::fromHex(const QByteArray &hexEncoded)
4612{
4613 QByteArray res((hexEncoded.size() + 1)/ 2, Qt::Uninitialized);
4614 uchar *result = (uchar *)res.data() + res.size();
4615
4616 bool odd_digit = true;
4617 for (qsizetype i = hexEncoded.size() - 1; i >= 0; --i) {
4618 uchar ch = uchar(hexEncoded.at(i));
4619 int tmp = QtMiscUtils::fromHex(ch);
4620 if (tmp == -1)
4621 continue;
4622 if (odd_digit) {
4623 --result;
4624 *result = tmp;
4625 odd_digit = false;
4626 } else {
4627 *result |= tmp << 4;
4628 odd_digit = true;
4629 }
4630 }
4631
4632 res.remove(0, result - (const uchar *)res.constData());
4633 return res;
4634}
4635
4636/*!
4637 Returns a hex encoded copy of the byte array.
4638
4639 The hex encoding uses the numbers 0-9 and the letters a-f.
4640
4641 If \a separator is not '\0', the separator character is inserted between
4642 the hex bytes.
4643
4644 Example:
4645 \snippet code/src_corelib_text_qbytearray.cpp 50
4646
4647 \since 5.9
4648 \sa fromHex()
4649*/
4650QByteArray QByteArray::toHex(char separator) const
4651{
4652 if (isEmpty())
4653 return QByteArray();
4654
4655 const qsizetype length = separator ? (size() * 3 - 1) : (size() * 2);
4656 QByteArray hex(length, Qt::Uninitialized);
4657 char *hexData = hex.data();
4658 const uchar *data = (const uchar *)this->data();
4659 for (qsizetype i = 0, o = 0; i < size(); ++i) {
4660 hexData[o++] = QtMiscUtils::toHexLower(data[i] >> 4);
4661 hexData[o++] = QtMiscUtils::toHexLower(data[i] & 0xf);
4662
4663 if ((separator) && (o < length))
4664 hexData[o++] = separator;
4665 }
4666 return hex;
4667}
4668
4669static qsizetype q_fromPercentEncoding(QByteArrayView src, char percent, QSpan<char> buffer)
4670{
4671 char *data = buffer.begin();
4672 const char *inputPtr = src.begin();
4673
4674 qsizetype i = 0;
4675 const qsizetype len = src.size();
4676 while (i < len) {
4677 char c = inputPtr[i];
4678 if (c == percent && i + 2 < len) {
4679 if (int a = QtMiscUtils::fromHex(uchar(inputPtr[++i])); a != -1)
4680 *data = a << 4;
4681 if (int b = QtMiscUtils::fromHex(uchar(inputPtr[++i])); b != -1)
4682 *data |= b;
4683 } else {
4684 *data = c;
4685 }
4686 ++data;
4687 ++i;
4688 }
4689
4690 return data - buffer.begin();
4691}
4692
4693/*!
4694 \fn QByteArray QByteArray::percentDecoded(char percent) const &
4695 \since 6.4
4696
4697 Decodes URI/URL-style percent-encoding.
4698
4699 Returns a byte array containing the decoded text. The \a percent parameter
4700 allows use of a different character than '%' (for instance, '_' or '=') as
4701 the escape character.
4702
4703 For example:
4704 \snippet code/src_corelib_text_qbytearray.cpp 54
4705
4706 \note Given invalid input (such as a string containing the sequence "%G5",
4707 which is not a valid hexadecimal number) the output will be invalid as
4708 well. As an example: the sequence "%G5" could be decoded to 'W'.
4709
4710 \sa toPercentEncoding(), QUrl::fromPercentEncoding()
4711*/
4712
4713/*!
4714 \fn QByteArray QByteArray::percentDecoded(char percent) &&
4715 \since 6.11
4716 \overload
4717*/
4718
4719/*!
4720 \since 4.4
4721
4722 Decodes \a input from URI/URL-style percent-encoding.
4723
4724 Returns a byte array containing the decoded text. The \a percent parameter
4725 allows use of a different character than '%' (for instance, '_' or '=') as
4726 the escape character. Equivalent to input.percentDecoded(percent).
4727
4728 For example:
4729 \snippet code/src_corelib_text_qbytearray.cpp 51
4730
4731 \sa percentDecoded()
4732*/
4733QByteArray QByteArray::fromPercentEncoding(const QByteArray &input, char percent)
4734{
4735 if (input.isEmpty())
4736 return input; // Preserves isNull().
4737
4738 QByteArray out{input.size(), Qt::Uninitialized};
4739 qsizetype len = q_fromPercentEncoding(input, percent, out);
4740 out.truncate(len);
4741 return out;
4742}
4743
4744/*!
4745 \overload
4746 \since 6.11
4747*/
4748QByteArray QByteArray::fromPercentEncoding(QByteArray &&input, char percent)
4749{
4750 if (input.d.needsDetach())
4751 return fromPercentEncoding(input, percent); // lvalue overload
4752
4753 if (input.isEmpty())
4754 return std::move(input); // Preserves isNull().
4755
4756 qsizetype len = q_fromPercentEncoding(input, percent, input);
4757 input.truncate(len);
4758 return std::move(input);
4759}
4760
4761/*! \fn QByteArray QByteArray::fromStdString(const std::string &str)
4762 \since 5.4
4763
4764 Returns a copy of the \a str string as a QByteArray.
4765
4766 \sa toStdString(), QString::fromStdString()
4767*/
4768QByteArray QByteArray::fromStdString(const std::string &s)
4769{
4770 return QByteArray(s.data(), qsizetype(s.size()));
4771}
4772
4773/*!
4774 \fn std::string QByteArray::toStdString() const
4775 \since 5.4
4776
4777 Returns a std::string object with the data contained in this
4778 QByteArray.
4779
4780 This operator is mostly useful to pass a QByteArray to a function
4781 that accepts a std::string object.
4782
4783 \sa fromStdString(), QString::toStdString()
4784*/
4785std::string QByteArray::toStdString() const
4786{
4787 return std::string(data(), size_t(size()));
4788}
4789
4790/*!
4791 \fn QByteArray::operator std::string_view() const noexcept
4792 \target qbytearray-operator-std-string_view
4793 \since 6.10
4794
4795 Converts this QByteArray object to a \c{std::string_view} object.
4796 The returned string view will span over the entirety of the byte
4797 array.
4798*/
4799
4800/*!
4801 \since 4.4
4802
4803 Returns a URI/URL-style percent-encoded copy of this byte array. The
4804 \a percent parameter allows you to override the default '%'
4805 character for another.
4806
4807 By default, this function will encode all bytes that are not one of the
4808 following:
4809
4810 ALPHA ("a" to "z" and "A" to "Z") / DIGIT (0 to 9) / "-" / "." / "_" / "~"
4811
4812 To prevent bytes from being encoded pass them to \a exclude. To force bytes
4813 to be encoded pass them to \a include. The \a percent character is always
4814 encoded.
4815
4816 Example:
4817
4818 \snippet code/src_corelib_text_qbytearray.cpp 52
4819
4820 The hex encoding uses the numbers 0-9 and the uppercase letters A-F.
4821
4822 \sa fromPercentEncoding(), QUrl::toPercentEncoding()
4823*/
4824QByteArray QByteArray::toPercentEncoding(const QByteArray &exclude, const QByteArray &include,
4825 char percent) const
4826{
4827 if (isNull())
4828 return QByteArray(); // preserve null
4829 if (isEmpty())
4830 return QByteArray(data(), 0);
4831
4832 const auto contains = [](const QByteArray &view, char c) {
4833 // As view.contains(c), but optimised to bypass a lot of overhead:
4834 return view.size() > 0 && memchr(view.data(), c, view.size()) != nullptr;
4835 };
4836
4837 QByteArray result = *this;
4838 char *output = nullptr;
4839 qsizetype length = 0;
4840
4841 for (unsigned char c : *this) {
4842 if (char(c) != percent
4843 && ((c >= 0x61 && c <= 0x7A) // ALPHA
4844 || (c >= 0x41 && c <= 0x5A) // ALPHA
4845 || (c >= 0x30 && c <= 0x39) // DIGIT
4846 || c == 0x2D // -
4847 || c == 0x2E // .
4848 || c == 0x5F // _
4849 || c == 0x7E // ~
4850 || contains(exclude, c))
4851 && !contains(include, c)) {
4852 if (output)
4853 output[length] = c;
4854 ++length;
4855 } else {
4856 if (!output) {
4857 // detach now
4858 result.resize(size() * 3); // worst case
4859 output = result.data();
4860 }
4861 output[length++] = percent;
4862 output[length++] = QtMiscUtils::toHexUpper((c & 0xf0) >> 4);
4863 output[length++] = QtMiscUtils::toHexUpper(c & 0xf);
4864 }
4865 }
4866 if (output)
4867 result.truncate(length);
4868
4869 return result;
4870}
4871
4872#if defined(Q_OS_WASM) || defined(Q_QDOC)
4873
4874/*!
4875 Constructs a new QByteArray containing a copy of the Uint8Array \a uint8array.
4876
4877 This function transfers data from a JavaScript data buffer - which
4878 is not addressable from C++ code - to heap memory owned by a QByteArray.
4879 The Uint8Array can be released once this function returns and a copy
4880 has been made.
4881
4882 The \a uint8array argument must an emscripten::val referencing an Uint8Array
4883 object, e.g. obtained from a global JavaScript variable:
4884
4885 \snippet code/src_corelib_text_qbytearray.cpp 55
4886
4887 This function returns a null QByteArray if the size of the Uint8Array
4888 exceeds the maximum capacity of QByteArray, or if the \a uint8array
4889 argument is not of the Uint8Array type.
4890
4891 \since 6.5
4892 \ingroup platform-type-conversions
4893
4894 \sa toEcmaUint8Array()
4895*/
4896
4897QByteArray QByteArray::fromEcmaUint8Array(emscripten::val uint8array)
4898{
4899 return qstdweb::Uint8Array(uint8array).copyToQByteArray();
4900}
4901
4902/*!
4903 Creates a Uint8Array from a QByteArray.
4904
4905 This function transfers data from heap memory owned by a QByteArray
4906 to a JavaScript data buffer. The function allocates and copies into an
4907 ArrayBuffer, and returns a Uint8Array view to that buffer.
4908
4909 The JavaScript objects own a copy of the data, and this
4910 QByteArray can be safely deleted after the copy has been made.
4911
4912 \snippet code/src_corelib_text_qbytearray.cpp 56
4913
4914 \since 6.5
4915 \ingroup platform-type-conversions
4916
4917 \sa fromEcmaUint8Array()
4918*/
4919emscripten::val QByteArray::toEcmaUint8Array()
4920{
4921 return qstdweb::Uint8Array::copyFrom(*this).val();
4922}
4923
4924#endif
4925
4926/*! \typedef QByteArray::ConstIterator
4927 \internal
4928*/
4929
4930/*! \typedef QByteArray::Iterator
4931 \internal
4932*/
4933
4934/*! \typedef QByteArray::const_iterator
4935
4936 This typedef provides an STL-style const iterator for QByteArray.
4937
4938 \sa QByteArray::const_reverse_iterator, QByteArray::iterator
4939*/
4940
4941/*! \typedef QByteArray::iterator
4942
4943 This typedef provides an STL-style non-const iterator for QByteArray.
4944
4945 \sa QByteArray::reverse_iterator, QByteArray::const_iterator
4946*/
4947
4948/*! \typedef QByteArray::const_reverse_iterator
4949 \since 5.6
4950
4951 This typedef provides an STL-style const reverse iterator for QByteArray.
4952
4953 \sa QByteArray::reverse_iterator, QByteArray::const_iterator
4954*/
4955
4956/*! \typedef QByteArray::reverse_iterator
4957 \since 5.6
4958
4959 This typedef provides an STL-style non-const reverse iterator for QByteArray.
4960
4961 \sa QByteArray::const_reverse_iterator, QByteArray::iterator
4962*/
4963
4964/*! \typedef QByteArray::size_type
4965 \internal
4966*/
4967
4968/*! \typedef QByteArray::difference_type
4969 \internal
4970*/
4971
4972/*! \typedef QByteArray::const_reference
4973 \internal
4974*/
4975
4976/*! \typedef QByteArray::reference
4977 \internal
4978*/
4979
4980/*! \typedef QByteArray::const_pointer
4981 \internal
4982*/
4983
4984/*! \typedef QByteArray::pointer
4985 \internal
4986*/
4987
4988/*! \typedef QByteArray::value_type
4989 \internal
4990 */
4991
4992/*!
4993 \fn DataPtr &QByteArray::data_ptr()
4994 \internal
4995*/
4996
4997/*!
4998 \typedef QByteArray::DataPtr
4999 \internal
5000*/
5001
5002/*!
5003 \macro QByteArrayLiteral(ba)
5004 \relates QByteArray
5005
5006 The macro generates the data for a QByteArray out of the string literal \a
5007 ba at compile time. Creating a QByteArray from it is free in this case, and
5008 the generated byte array data is stored in the read-only segment of the
5009 compiled object file.
5010
5011 For instance:
5012
5013 \snippet code/src_corelib_text_qbytearray.cpp 53
5014
5015 Using QByteArrayLiteral instead of a double quoted plain C++ string literal
5016 can significantly speed up creation of QByteArray instances from data known
5017 at compile time.
5018
5019 \sa QStringLiteral
5020*/
5021
5022#if QT_DEPRECATED_SINCE(6, 8)
5023/*!
5024 \fn QtLiterals::operator""_qba(const char *str, size_t size)
5025
5026 \relates QByteArray
5027 \since 6.2
5028 \deprecated [6.8] Use \c _ba from Qt::StringLiterals namespace instead.
5029
5030 Literal operator that creates a QByteArray out of the first \a size characters
5031 in the char string literal \a str.
5032
5033 The QByteArray is created at compile time, and the generated string data is stored
5034 in the read-only segment of the compiled object file. Duplicate literals may share
5035 the same read-only memory. This functionality is interchangeable with
5036 QByteArrayLiteral, but saves typing when many string literals are present in the
5037 code.
5038
5039 The following code creates a QByteArray:
5040 \code
5041 auto str = "hello"_qba;
5042 \endcode
5043
5044 \sa QByteArrayLiteral, QtLiterals::operator""_qs(const char16_t *str, size_t size)
5045*/
5046#endif // QT_DEPRECATED_SINCE(6, 8)
5047
5048/*!
5049 \fn Qt::Literals::StringLiterals::operator""_ba(const char *str, size_t size)
5050
5051 \relates QByteArray
5052 \since 6.4
5053
5054 Literal operator that creates a QByteArray out of the first \a size characters
5055 in the char string literal \a str.
5056
5057 The QByteArray is created at compile time, and the generated string data is stored
5058 in the read-only segment of the compiled object file. Duplicate literals may share
5059 the same read-only memory. This functionality is interchangeable with
5060 QByteArrayLiteral, but saves typing when many string literals are present in the
5061 code.
5062
5063 The following code creates a QByteArray:
5064 \code
5065 using namespace Qt::StringLiterals;
5066
5067 auto str = "hello"_ba;
5068 \endcode
5069
5070 \sa Qt::Literals::StringLiterals
5071*/
5072
5073/*!
5074 \class QByteArray::FromBase64Result
5075 \inmodule QtCore
5076 \ingroup tools
5077 \since 5.15
5078
5079 \brief The QByteArray::FromBase64Result class holds the result of
5080 a call to QByteArray::fromBase64Encoding.
5081
5082 Objects of this class can be used to check whether the conversion
5083 was successful, and if so, retrieve the decoded QByteArray. The
5084 conversion operators defined for QByteArray::FromBase64Result make
5085 its usage straightforward:
5086
5087 \snippet code/src_corelib_text_qbytearray.cpp 44ter
5088
5089 Alternatively, it is possible to access the conversion status
5090 and the decoded data directly:
5091
5092 \snippet code/src_corelib_text_qbytearray.cpp 44quater
5093
5094 \sa QByteArray::fromBase64
5095*/
5096
5097/*!
5098 \variable QByteArray::FromBase64Result::decoded
5099
5100 Contains the decoded byte array.
5101*/
5102
5103/*!
5104 \variable QByteArray::FromBase64Result::decodingStatus
5105
5106 Contains whether the decoding was successful, expressed as a value
5107 of type QByteArray::Base64DecodingStatus.
5108*/
5109
5110/*!
5111 \fn QByteArray::FromBase64Result::operator bool() const
5112
5113 Returns whether the decoding was successful. This is equivalent
5114 to checking whether the \c{decodingStatus} member is equal to
5115 QByteArray::Base64DecodingStatus::Ok.
5116*/
5117
5118/*!
5119 \fn const QByteArray &QByteArray::FromBase64Result::operator*() const &
5120 \fn const QByteArray &&QByteArray::FromBase64Result::operator*() const &&
5121 \fn QByteArray &QByteArray::FromBase64Result::operator*() &
5122 \fn QByteArray &&QByteArray::FromBase64Result::operator*() &&
5123
5124 Returns the decoded byte array.
5125*/
5126
5127/*!
5128 \fn bool QByteArray::FromBase64Result::operator==(const QByteArray::FromBase64Result &lhs, const QByteArray::FromBase64Result &rhs) noexcept
5129
5130 Returns \c true if \a lhs and \a rhs are equal, otherwise returns \c false.
5131
5132 \a lhs and \a rhs are equal if and only if they contain the same decoding
5133 status and, if the status is QByteArray::Base64DecodingStatus::Ok, if and
5134 only if they contain the same decoded data.
5135*/
5136
5137/*!
5138 \fn bool QByteArray::FromBase64Result::operator!=(const QByteArray::FromBase64Result &lhs, const QByteArray::FromBase64Result &rhs) noexcept
5139
5140 Returns \c true if \a lhs and \a rhs are different, otherwise
5141 returns \c false.
5142*/
5143
5144/*!
5145 \qhashold{QByteArray::FromBase64Result}
5146*/
5147size_t qHash(const QByteArray::FromBase64Result &key, size_t seed) noexcept
5148{
5149 return qHashMulti(seed, key.decoded, static_cast<int>(key.decodingStatus));
5150}
5151
5152/*! \fn template <typename T> qsizetype erase(QByteArray &ba, const T &t)
5153 \relates QByteArray
5154 \since 6.1
5155
5156 Removes all elements that compare equal to \a t from the
5157 byte array \a ba. Returns the number of elements removed, if any.
5158
5159 \sa erase_if
5160*/
5161
5162/*! \fn template <typename Predicate> qsizetype erase_if(QByteArray &ba, Predicate pred)
5163 \relates QByteArray
5164 \since 6.1
5165
5166 Removes all elements for which the predicate \a pred returns true
5167 from the byte array \a ba. Returns the number of elements removed, if
5168 any.
5169
5170 \sa erase
5171*/
5172
5173QT_END_NAMESPACE
\inmodule QtCore
QDataStream & operator>>(QDataStream &in, QByteArray &ba)
Reads a byte array into ba from the stream in and returns a reference to the stream.
quint16 qChecksum(QByteArrayView data, Qt::ChecksumType standard)
Definition qlist.h:81
static constexpr bool isLowerCaseAscii(char c)
static const quint16 crc_tbl[16]
QByteArray qCompress(const uchar *data, qsizetype nbytes, int compressionLevel)
ZLibOp
@ Decompression
static Q_DECL_COLD_FUNCTION const char * zlibOpAsString(ZLibOp op)
static QByteArray toCase(const QByteArray &input, QByteArray *rvalue, uchar(*lookup)(uchar))
static qsizetype q_fromPercentEncoding(QByteArrayView src, char percent, QSpan< char > buffer)
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