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