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