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