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