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