Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qcborvalue.cpp
Go to the documentation of this file.
1// Copyright (C) 2022 Intel Corporation.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:data-parser
4
5#include "qcborvalue.h"
6#include "qcborvalue_p.h"
7#include "qdatastream.h"
8#include "qcborarray.h"
9#include "qcbormap.h"
10
11#if QT_CONFIG(cborstreamreader)
12#include "qcborstreamreader.h"
13#endif
14
15#if QT_CONFIG(cborstreamwriter)
16#include "qcborstreamwriter.h"
17#endif
18
19#include <QtCore/qdebug.h>
20#include <qendian.h>
21#include <qlocale.h>
22#include <qdatetime.h>
23#include <qtimezone.h>
24#include <private/qnumeric_p.h>
25#include <private/qsimd_p.h>
26
27#include <new>
28
30
31QT_DEFINE_QESDP_SPECIALIZATION_DTOR(QCborContainerPrivate)
32
33// Worst case memory allocation for a corrupt stream: 64 MB for 32-bit, 256 MB for 64-bit
34static constexpr quint64 MaxAcceptableElementMemoryUse =
35 (sizeof(void*) == 4 ? 64 : 256) * 1024 * 1024;
36
37// Internal limits to ensure we don't blow up the memory when parsing a corrupt
38// (possibly crafted to exploit) CBOR stream. The recursion impacts both the
39// maps/arrays we'll open when parsing and the thread's stack, as the parser is
40// itself recursive. If someone really needs more than 1024 layers of nesting,
41// they probably have a weird use-case for which custom parsing and
42// serialization code would make sense. The limit on element count is the
43// preallocated limit: if the stream does actually have more elements, we will
44// grow the container.
45Q_DECL_UNUSED static constexpr int MaximumRecursionDepth = 1024;
46Q_DECL_UNUSED static constexpr quint64 MaximumPreallocatedElementCount =
47 MaxAcceptableElementMemoryUse / MaximumRecursionDepth / sizeof(QtCbor::Element) - 1;
48
49/*!
50 \class QCborValue
51 \inmodule QtCore
52 \ingroup cbor
53 \ingroup qtserialization
54 \reentrant
55 \since 5.12
56
57 \brief The QCborValue class encapsulates a value in CBOR.
58
59 \compares strong
60
61 This class can be used to hold one of the many types available in CBOR.
62 CBOR is the Concise Binary Object Representation, a very compact form of
63 binary data encoding that is a superset of JSON. It was created by the IETF
64 Constrained RESTful Environments (CoRE) WG, which has used it in many
65 new RFCs. It is meant to be used alongside the
66 \l{RFC 7252}{CoAP protocol}.
67
68 CBOR has three groups of built-in types:
69
70 \list
71 \li Basic types: integers, floating point (double), boolean, null, etc.
72 \li String-like types: strings and byte arrays
73 \li Containers: arrays and maps
74 \endlist
75
76 Additionally, CBOR supports a form of type extensibility by associating a
77 "tag" to one of the above types to convey more information. For example, a
78 UUID is represented by a tag and a byte array containing the 16 bytes of
79 the UUID content. QCborValue supports creating and decoding several of those
80 extended types directly with Qt classes (like QUuid).
81
82 For the complete list, see \l QCborValue::Type. The type of a QCborValue can
83 be queried using type() or one of the "isXxxx" functions.
84
85 \section1 Extended types and tagged values
86
87 A tagged value is a normal QCborValue that is paired with a number that
88 is its tag. See \l QCborKnownTags for more information on what tags are in
89 the API as well as the full, official list. Such combinations form extended
90 types.
91
92 QCborValue has support for certain extended types in the API, like URL
93 (with \l QUrl) and UUID (with \l QUuid). Other extended types not supported
94 in the API are represented by a QCborValue of \l {Type}{Tag} type. The tag
95 can later be retrieved by tag() and the tagged value using taggedValue().
96
97 In order to support future compatibility, QCborValues containing extended
98 Qt types compare equal to the tag type of the same contents. In other
99 words, the following expression is true:
100
101 \snippet code/src_corelib_serialization_qcborvalue.cpp 0
102
103 \section1 Undefined and null values
104
105 QCborValue can contain a value of "null", which is not of any specific type.
106 It resembles the C++ \c {std::nullptr_t} type, whose only possible value is
107 \nullptr. QCborValue has a constructor taking such a type and creates a
108 null QCborValue.
109
110 Null values are used to indicate that an optional value is not present. In
111 that aspect, it is similar to the C++ Standard Library type \c
112 {std::optional} when that is disengaged. Unlike the C++ type, CBOR nulls
113 are simply of type "Null" and it is not possible to determine what concrete
114 type it is replacing.
115
116 QCborValue can also be of the undefined type, which represents a value of
117 "undefined". In fact, that is what the QCborValue default constructor
118 creates.
119
120 Undefined values are different from null values. While nulls are used to
121 indicate an optional value that is not provided, Undefined is usually
122 used to indicate that an expected value could not be provided, usually due
123 to an error or a precondition that could not be satisfied.
124
125 Such values are completely valid and may appear in CBOR streams, unlike
126 JSON content and QJsonValue's undefined bit. But like QJsonValue's
127 Undefined, it is returned by a CBOR container's value() or read-only
128 operator[] for invalid look-ups (index out of range for QCborArray, or key
129 not found for QCborMap). It is not possible to tell such a case apart from
130 the value of Undefined, so if that is required, check the QCborArray size
131 and use the QCborMap iterator API.
132
133 \section1 Simple types
134
135 CBOR supports additional simple types that, like Null and Undefined, carry
136 no other value. They are called interchangeably "Simple Types" and "Simple
137 Values". CBOR encodes booleans as two distinct types (one for \c true and
138 one for \c false), but QCborValue has a convenience API for them.
139
140 There are currently no other defined CBOR simple types. QCborValue supports
141 them simply by their number with API like isSimpleType() and
142 toSimpleType(), available for compatibility with future specifications
143 before the Qt API can be updated. Their use before such a specification is
144 discouraged, as other CBOR implementations may not support them fully.
145
146 \section1 CBOR support
147
148 QCborValue supports all CBOR features required to create canonical and
149 strict streams. It implements almost all of the features specified in \l
150 {RFC 7049}.
151
152 The following table lists the CBOR features that QCborValue supports.
153
154 \table
155 \header \li Feature \li Support
156 \row \li Unsigned numbers \li Yes (\l qint64 range)
157 \row \li Negative numbers \li Yes (\l qint64 range)
158 \row \li Byte strings \li Yes
159 \row \li Text strings \li Yes
160 \row \li Chunked strings \li See below
161 \row \li Tags \li Yes (arbitrary)
162 \row \li Booleans \li Yes
163 \row \li Null \li Yes
164 \row \li Undefined \li Yes
165 \row \li Arbitrary simple values \li Yes
166 \row \li Half-precision float (16-bit) \li Yes
167 \row \li Single-precision float (32-bit) \li Yes
168 \row \li Double-precision float (64-bit) \li Yes
169 \row \li Infinities and NaN floating point \li Yes
170 \row \li Determinate-length arrays and maps \li Yes
171 \row \li Indeterminate-length arrays and maps \li Yes
172 \row \li Map key types other than strings and integers \li Yes (arbitrary)
173 \endtable
174
175 Integers in QCborValue are limited to the range of the \l qint64 type. That
176 is, from -9,223,372,036,854,775,808 (-2\sup{63}) to
177 9,223,372,036,854,775,807 (2\sup{63} - 1). CBOR itself can represent integer
178 values outside of this range, which QCborValue does not support. When
179 decoding a stream using fromCbor() containing one of those values,
180 QCborValue will convert automatically to \l {Type}{Double}, but that may
181 lose up to 11 bits of precision.
182
183 fromCbor() is able to decode chunked strings, but will always merge the
184 chunks together into a single QCborValue. For that reason, it always writes
185 non-chunked strings when using toCbor() (which is required by the Canonical
186 format anyway).
187
188 QCborValue will always convert half- and single-precision floating point
189 values in the CBOR stream to double-precision. The toCbor() function can
190 take a parameter indicating to recreate them.
191
192 \section1 QCborValueRef
193
194 QCborValueRef is a helper class for QCborArray and QCborMap. It is the type
195 you get when using one of the mutating APIs in those classes. Unlike
196 QCborValue, new values can be assigned to that class. When that is done, the
197 array or map it refers to will be modified with the new value. In all other
198 aspects, its API is identical to QCborValue.
199
200 \sa QCborArray, QCborMap, QCborStreamReader, QCborStreamWriter,
201 QJsonValue, QJsonDocument, {Serialization Converter}, {Saving and Loading a Game}
202 {Parsing and displaying CBOR data}
203 */
204
205/*!
206 \class QCborParserError
207 \inmodule QtCore
208 \ingroup cbor
209 \reentrant
210 \since 5.12
211
212 \brief The QCborParserError is used by QCborValue to report a parsing error.
213
214 This class is used by \l {QCborValue::fromCbor(const QByteArray &ba,
215 QCborParserError *error)} to report a parser error and the byte offset
216 where the error was detected.
217
218 \sa QCborValue, QCborError
219 */
220
221/*!
222 \variable QCborParserError::offset
223
224 This field contains the offset from the beginning of the data where the
225 error was detected. The offset should point to the beginning of the item
226 that contained the error, even if the error itself was elsewhere (for
227 example, for UTF-8 decoding issues).
228
229 \sa QCborValue::fromCbor()
230 */
231
232/*!
233 \variable QCborParserError::error
234
235 This field contains the error code that indicates what decoding problem was
236 found.
237
238 \sa QCborValue::fromCbor()
239 */
240
241/*!
242 \fn QString QCborParserError::errorString() const
243
244 Returns a string representation of the error code. This string is not
245 translated.
246
247 \sa QCborError::toString(), QCborValue::fromCbor()
248 */
249
250/*!
251 \enum QCborValue::EncodingOption
252
253 This enum is used in the options argument to toCbor(), modifying the
254 behavior of the encoder.
255
256 \omitvalue SortKeysInMaps
257 \value NoTransformation (Default) Performs no transformations.
258 \value UseFloat Tells the encoder to use IEEE 754 single-precision floating point
259 (that is, \c float) whenever possible.
260 \value UseFloat16 Tells the encoder to use IEEE 754 half-precision floating point
261 (that is, \c qfloat16), whenever possible. Implies \c UseFloat.
262 \value UseIntegers Tells the encoder to use integers whenever a value of type \l
263 {Type}{Double} contains an integer.
264
265 The use of \c UseFloat16 is required to encode the stream in Canonical
266 Format, but is not otherwise necessary.
267
268 \sa toCbor()
269 */
270
271/*!
272 \enum QCborValue::DiagnosticNotationOption
273
274 This enum is used in the option argument to toDiagnosticNotation(), to
275 modify the output format.
276
277 \value Compact Does not use any line-breaks, producing a compact representation.
278 \value LineWrapped Uses line-breaks, one QCborValue per line.
279 \value ExtendedFormat Uses some different options to represent values, not found in
280 RFC 7049. Those options are subject to change.
281
282 Currently, \c ExtendedFormat will change how byte arrays are represented.
283 Without it, they are always hex-encoded and without spaces. With it,
284 QCborValue::toCbor() will either use hex with spaces, base64 or base64url
285 encoding, depending on the context.
286
287 \sa toDiagnosticNotation()
288 */
289
290/*!
291 \enum QCborValue::Type
292
293 This enum represents the QCborValue type. It is returned by the type()
294 function.
295
296 The CBOR built-in types are:
297
298 \value Integer \c qint64: An integer value
299 \value ByteArray \l QByteArray: a byte array ("byte string")
300 \value String \l QString: a Unicode string ("text string")
301 \value Array \l QCborArray: an array of QCborValues
302 \value Map \l QCborMap: an associative container of QCborValues
303 \value SimpleType \l QCborSimpleType: one of several simple types/values
304 \value False \c bool: the simple type for value \c false
305 \value True \c bool: the simple type for value \c true
306 \value Null \c std::nullptr_t: the simple type for the null value
307 \value Undefined (no type) the simple type for the undefined value
308 \value Double \c double: a double-precision floating point
309 \value Invalid Not a valid value, this usually indicates a CBOR decoding error
310
311 Additionally, QCborValue can represent extended types:
312
313 \value Tag An unknown or unrecognized extended type, represented by its
314 tag (a \l QCborTag) and the tagged value (a QCborValue)
315 \value DateTime \l QDateTime: a date and time stamp
316 \value Url \l QUrl: a URL or URI
317 \value RegularExpression \l QRegularExpression: the pattern of a regular expression
318 \value Uuid \l QUuid: a UUID
319
320 \sa type()
321 */
322
323/*!
324 \fn QCborValue::QCborValue()
325
326 Creates a QCborValue of the \l {Type}{Undefined} type.
327
328 CBOR undefined values are used to indicate missing information, usually as
329 a result of a previous operation that did not complete as expected. They
330 are also used by the QCborArray and QCborMap API to indicate the searched
331 item was not found.
332
333 Undefined values are represented by the \l {QCborSimpleType}{Undefined
334 simple type}. Because of that, QCborValues with undefined values will also
335 return true for isSimpleType() and
336 \c{isSimpleType(QCborSimpleType::Undefined)}.
337
338 Undefined values are different from null values.
339
340 QCborValue objects with undefined values are also different from invalid
341 QCborValue objects. The API will not create invalid QCborValues, but they
342 may exist as a result of a parsing error.
343
344 \sa isUndefined(), isNull(), isSimpleType()
345 */
346
347/*!
348 \fn QCborValue::QCborValue(Type t_)
349
350 Creates a QCborValue of type \a t_. The value associated with such a type
351 (if any) will be default constructed.
352
353 \sa type()
354 */
355
356/*!
357 \fn QCborValue::QCborValue(std::nullptr_t)
358
359 Creates a QCborValue of the \l {Type}{Null} type.
360
361 CBOR null values are used to indicate optional values that were not
362 provided. They are distinct from undefined values, in that null values are
363 usually not the result of an earlier error or problem.
364
365 \sa isNull(), isUndefined(), isSimpleType()
366 */
367
368/*!
369 \fn QCborValue::QCborValue(bool b)
370
371 Creates a QCborValue with boolean value \a b. The value can later be
372 retrieved using toBool().
373
374 Internally, CBOR booleans are represented by a pair of types, one for true
375 and one for false. For that reason, boolean QCborValues will return true
376 for isSimpleType() and one of \c{isSimpleType(QCborSimpleType::False)} or
377 \c{isSimpleType(QCborSimpleType::True)}.
378
379 \sa toBool(), isBool(), isTrue(), isFalse(), isSimpleType()
380 */
381
382/*!
383 \fn QCborValue::QCborValue(qint64 i)
384
385 Creates a QCborValue with integer value \a i. The value can later be
386 retrieved using toInteger().
387
388 CBOR integer values are distinct from floating point values. Therefore,
389 QCborValue objects with integers will compare differently to QCborValue
390 objects containing floating-point, even if the values contained in the
391 objects are equivalent.
392
393 \sa toInteger(), isInteger(), isDouble()
394 */
395
396/*!
397 \fn QCborValue::QCborValue(double d)
398
399 Creates a QCborValue with floating point value \a d. The value can later be
400 retrieved using toDouble().
401
402 CBOR floating point values are distinct from integer values. Therefore,
403 QCborValue objects with integers will compare differently to QCborValue
404 objects containing floating-point, even if the values contained in the
405 objects are equivalent.
406
407 \sa toDouble(), isDouble(), isInteger()
408 */
409
410/*!
411 \fn QCborValue::QCborValue(QCborSimpleType st)
412
413 Creates a QCborValue of simple type \a st. The type can later be retrieved
414 using toSimpleType() as well as isSimpleType(st).
415
416 CBOR simple types are types that do not have any associated value, like
417 C++'s \c{std::nullptr_t} type, whose only possible value is \nullptr.
418
419 If \a st is \c{QCborSimpleType::Null}, the resulting QCborValue will be of
420 the \l{Type}{Null} type and similarly for \c{QCborSimpleType::Undefined}.
421 If \a st is \c{QCborSimpleType::False} or \c{QCborSimpleType::True}, the
422 created QCborValue will be a boolean containing a value of false or true,
423 respectively.
424
425 This function can be used with simple types not defined in the API. For
426 example, to create a QCborValue with simple type 12, one could write:
427
428 \snippet code/src_corelib_serialization_qcborvalue.cpp 1
429
430 Simple types should not be used until a specification for them has been
431 published, since other implementations may not support them properly.
432 Simple type values 24 to 31 are reserved and must not be used.
433
434 isSimpleType(), isNull(), isUndefined(), isTrue(), isFalse()
435 */
436
437/*!
438 \fn QCborValue::QCborValue(QCborKnownTags tag, const QCborValue &taggedValue)
439 \overload
440
441 Creates a QCborValue for the extended type represented by the tag value \a
442 tag, tagging value \a taggedValue. The tag can later be retrieved using
443 tag() and the tagged value using taggedValue().
444
445 \sa isTag(), tag(), taggedValue(), QCborKnownTags
446 */
447
448/*!
449 \fn QCborValue::~QCborValue()
450
451 Disposes of the current QCborValue object and frees any associated resources.
452 */
453
454/*!
455 \fn QCborValue::QCborValue(QCborValue &&other)
456 \overload
457
458 Moves the contents of the \a other QCborValue object into this one and frees
459 the resources of this one.
460 */
461
462/*!
463 \fn QCborValue &&QCborValue::operator=(QCborValue &&other)
464 \overload
465
466 Moves the contents of the \a other QCborValue object into this one and frees
467 the resources of this one. Returns a reference to this object.
468 */
469
470/*!
471 \fn void QCborValue::swap(QCborValue &other)
472 \memberswap{value}
473 */
474
475/*!
476 \fn QCborValue::Type QCborValue::type() const
477
478 Returns the type of this QCborValue. The type can also later be retrieved by one
479 of the "isXxx" functions.
480
481 \sa isInteger(), isByteArray(), isString(), isArray(), isMap(),
482 isTag(), isFalse(), isTrue(), isBool(), isNull(), isUndefined, isDouble(),
483 isDateTime(), isUrl(), isRegularExpression(), isUuid()
484 */
485
486/*!
487 \fn bool QCborValue::isInteger() const
488
489 Returns true if this QCborValue is of the integer type. The integer value
490 can be retrieved using toInteger().
491
492 \sa type(), toInteger()
493 */
494
495/*!
496 \fn bool QCborValue::isByteArray() const
497
498 Returns true if this QCborValue is of the byte array type. The byte array
499 value can be retrieved using toByteArray().
500
501 \sa type(), toByteArray()
502 */
503
504/*!
505 \fn bool QCborValue::isString() const
506
507 Returns true if this QCborValue is of the string type. The string value
508 can be retrieved using toString().
509
510 \sa type(), toString()
511 */
512
513/*!
514 \fn bool QCborValue::isArray() const
515
516 Returns true if this QCborValue is of the array type. The array value can
517 be retrieved using toArray().
518
519 \sa type(), toArray()
520 */
521
522/*!
523 \fn bool QCborValue::isMap() const
524
525 Returns true if this QCborValue is of the map type. The map value can be
526 retrieved using toMap().
527
528 \sa type(), toMap()
529 */
530
531/*!
532 \fn bool QCborValue::isTag() const
533
534 Returns true if this QCborValue is of the tag type. The tag value can be
535 retrieved using tag() and the tagged value using taggedValue().
536
537 This function also returns true for extended types that the API
538 recognizes. For code that handles extended types directly before the Qt API
539 is updated to support them, it is possible to recreate the tag + tagged
540 value pair by using taggedValue().
541
542 \sa type(), tag(), taggedValue()
543 */
544
545/*!
546 \fn bool QCborValue::isFalse() const
547
548 Returns true if this QCborValue is a boolean with false value. This
549 function exists because, internally, CBOR booleans are stored as two
550 separate types, one for true and one for false.
551
552 \sa type(), isBool(), isTrue(), toBool()
553 */
554
555/*!
556 \fn bool QCborValue::isTrue() const
557
558 Returns true if this QCborValue is a boolean with true value. This
559 function exists because, internally, CBOR booleans are stored as two
560 separate types, one for false and one for true.
561
562 \sa type(), isBool(), isFalse(), toBool()
563 */
564
565/*!
566 \fn bool QCborValue::isBool() const
567
568 Returns true if this QCborValue is a boolean. The value can be retrieved
569 using toBool().
570
571 \sa type(), toBool(), isTrue(), isFalse()
572 */
573
574/*!
575 \fn bool QCborValue::isUndefined() const
576
577 Returns true if this QCborValue is of the undefined type.
578
579 CBOR undefined values are used to indicate missing information, usually as
580 a result of a previous operation that did not complete as expected. They
581 are also used by the QCborArray and QCborMap API to indicate the searched
582 item was not found.
583
584 Undefined values are distinct from null values.
585
586 QCborValue objects with undefined values are also different from invalid
587 QCborValue objects. The API will not create invalid QCborValues, but they
588 may exist as a result of a parsing error.
589
590 \sa type(), isNull(), isInvalid()
591 */
592
593/*!
594 \fn bool QCborValue::isNull() const
595
596 Returns true if this QCborValue is of the null type.
597
598 CBOR null values are used to indicate optional values that were not
599 provided. They are distinct from undefined values, in that null values are
600 usually not the result of an earlier error or problem.
601
602 Null values are distinct from undefined values and from invalid QCborValue
603 objects. The API will not create invalid QCborValues, but they may exist as
604 a result of a parsing error.
605
606 \sa type(), isUndefined(), isInvalid()
607 */
608
609/*!
610 \fn bool QCborValue::isDouble() const
611
612 Returns true if this QCborValue is of the floating-point type. The value
613 can be retrieved using toDouble().
614
615 \sa type(), toDouble()
616 */
617
618/*!
619 \fn bool QCborValue::isDateTime() const
620
621 Returns true if this QCborValue is of the date/time type. The value can be
622 retrieved using toDateTime(). Date/times are extended types that use the
623 tag \l{QCborKnownTags}{DateTime}.
624
625 Additionally, when decoding from a CBOR stream, QCborValue will interpret
626 tags of value \l{QCborKnownTags}{UnixTime_t} and convert them to the
627 equivalent date/time.
628
629 \sa type(), toDateTime()
630 */
631
632/*!
633 \fn bool QCborValue::isUrl() const
634
635 Returns true if this QCborValue is of the URL type. The URL value
636 can be retrieved using toUrl().
637
638 \sa type(), toUrl()
639 */
640
641/*!
642 \fn bool QCborValue::isRegularExpression() const
643
644 Returns true if this QCborValue contains a regular expression's pattern.
645 The pattern can be retrieved using toRegularExpression().
646
647 \sa type(), toRegularExpression()
648 */
649
650/*!
651 \fn bool QCborValue::isUuid() const
652
653 Returns true if this QCborValue contains a UUID. The value can be retrieved
654 using toUuid().
655
656 \sa type(), toUuid()
657 */
658
659/*!
660 \fn bool QCborValue::isInvalid() const
661
662 Returns true if this QCborValue is not of any valid type. Invalid
663 QCborValues are distinct from those with undefined values and they usually
664 represent a decoding error.
665
666 \sa isUndefined(), isNull()
667 */
668
669/*!
670 \fn bool QCborValue::isContainer() const
671
672 This convenience function returns true if the QCborValue is either an array
673 or a map.
674
675 \sa isArray(), isMap()
676 */
677
678/*!
679 \fn bool QCborValue::isSimpleType() const
680
681 Returns true if this QCborValue is of one of the CBOR simple types. The
682 type itself can later be retrieved using type(), even for types that don't have an
683 enumeration in the API. They can also be checked with the
684 \l{isSimpleType(QCborSimpleType)} overload.
685
686 \sa QCborSimpleType, isSimpleType(QCborSimpleType), toSimpleType()
687 */
688
689/*!
690 \fn bool QCborValue::isSimpleType(QCborSimpleType st) const
691 \overload
692
693 Returns true if this QCborValue is of a simple type and toSimpleType()
694 would return \a st, false otherwise. This function can be used to check for
695 any CBOR simple type, even those for which there is no enumeration in the
696 API. For example, for the simple type of value 12, you could write:
697
698 \snippet code/src_corelib_serialization_qcborvalue.cpp 2
699
700 \sa QCborValue::QCborValue(QCborSimpleType), isSimpleType(), isFalse(),
701 isTrue(), isNull, isUndefined(), toSimpleType()
702 */
703
704/*!
705 \fn QCborSimpleType QCborValue::toSimpleType(QCborSimpleType defaultValue) const
706
707 Returns the simple type this QCborValue is of, if it is a simple type. If
708 it is not a simple type, it returns \a defaultValue.
709
710 The following types are simple types and this function will return the
711 listed values:
712
713 \table
714 \row \li QCborValue::False \li QCborSimpleType::False
715 \row \li QCborValue::True \li QCborSimpleType::True
716 \row \li QCborValue::Null \li QCborSimpleType::Null
717 \row \li QCborValue::Undefined \li QCborSimpleType::Undefined
718 \endtable
719
720 \sa type(), isSimpleType(), isBool(), isTrue(), isFalse(), isTrue(),
721 isNull(), isUndefined()
722 */
723
724/*!
725 \fn qint64 QCborValue::toInteger(qint64 defaultValue) const
726
727 Returns the integer value stored in this QCborValue, if it is of the
728 integer type. If it is of the Double type, this function returns the
729 floating point value converted to integer. In any other case, it returns \a
730 defaultValue.
731
732 \sa isInteger(), isDouble(), toDouble()
733 */
734
735/*!
736 \fn bool QCborValue::toBool(bool defaultValue) const
737
738 Returns the boolean value stored in this QCborValue, if it is of a boolean
739 type. Otherwise, it returns \a defaultValue.
740
741 \sa isBool(), isTrue(), isFalse()
742 */
743
744/*!
745 \fn double QCborValue::toDouble(double defaultValue) const
746
747 Returns the floating point value stored in this QCborValue, if it is of the
748 Double type. If it is of the Integer type, this function returns the
749 integer value converted to double. In any other case, it returns \a
750 defaultValue.
751
752 \sa isDouble(), isInteger(), toInteger()
753 */
754
755using namespace QtCbor;
757
759{
760 if (d == x)
761 return d;
762 if (d)
763 d->deref();
764 if (x)
765 x->ref.ref();
766 return d = x;
767}
768
770{
771 qint64 tag = d->elements.at(0).value;
772 auto &e = d->elements[1];
773 const ByteData *b = d->byteData(e);
774
775 auto replaceByteData = [&](const char *buf, qsizetype len, Element::ValueFlags f) {
776 d->data.clear();
777 d->usedData = 0;
778 e.flags = Element::HasByteData | f;
779 e.value = d->addByteData(buf, len);
780 };
781
782 switch (tag) {
783#if QT_CONFIG(datestring)
784 case qint64(QCborKnownTags::DateTimeString):
785 case qint64(QCborKnownTags::UnixTime_t): {
786 QDateTime dt;
787 if (tag == qint64(QCborKnownTags::DateTimeString) && b &&
788 e.type == QCborValue::String && (e.flags & Element::StringIsUtf16) == 0) {
789 // The data is supposed to be US-ASCII. If it isn't (contains UTF-8),
790 // QDateTime::fromString will fail anyway.
791 dt = QDateTime::fromString(b->asLatin1(), Qt::ISODateWithMs);
792 } else if (tag == qint64(QCborKnownTags::UnixTime_t)) {
793 qint64 msecs;
794 bool ok = false;
795 if (e.type == QCborValue::Integer) {
796 ok = !qMulOverflow<1000>(e.value, &msecs);
797 } else if (e.type == QCborValue::Double) {
798 ok = convertDoubleTo(round(e.fpvalue() * 1000), &msecs);
799 }
800 if (ok)
801 dt = QDateTime::fromMSecsSinceEpoch(msecs, QTimeZone::UTC);
802 else
803 break;
804 }
805 if (QString dtString = dt.toString(Qt::ISODateWithMs); !dtString.isEmpty())
806 return setToExtendedDateTimeType(d, dtString);
807 break;
808 }
809#endif
810
811#ifndef QT_BOOTSTRAPPED
812 case qint64(QCborKnownTags::Url):
813 if (e.type == QCborValue::String) {
814 if (b) {
815 // normalize to a short (decoded) form, so as to save space
816 QUrl url(e.flags & Element::StringIsUtf16 ?
817 b->asQStringRaw() :
818 b->toUtf8String(), QUrl::StrictMode);
819 if (url.isValid()) {
820 QByteArray encoded = url.toString(QUrl::DecodeReserved).toUtf8();
821 replaceByteData(encoded, encoded.size(), {});
822 }
823 }
824 return QCborValue::Url;
825 }
826 break;
827#endif // QT_BOOTSTRAPPED
828
829#if QT_CONFIG(regularexpression)
830 case quint64(QCborKnownTags::RegularExpression):
831 if (e.type == QCborValue::String) {
832 // no normalization is necessary
833 return QCborValue::RegularExpression;
834 }
835 break;
836#endif // QT_CONFIG(regularexpression)
837
838 case qint64(QCborKnownTags::Uuid):
839 if (e.type == QCborValue::ByteArray) {
840 // force the size to 16
841 char buf[sizeof(QUuid)] = {};
842 if (b)
843 memcpy(buf, b->byte(), qMin(sizeof(buf), size_t(b->len)));
844 replaceByteData(buf, sizeof(buf), {});
845
846 return QCborValue::Uuid;
847 }
848 break;
849 }
850
851 // no enriching happened
852 return QCborValue::Tag;
853}
854
855#if QT_CONFIG(cborstreamwriter) && !defined(QT_BOOTSTRAPPED)
856static void writeDoubleToCbor(QCborStreamWriter &writer, double d, QCborValue::EncodingOptions opt)
857{
858 if (qt_is_nan(d)) {
859 if (opt & QCborValue::UseFloat) {
860 if ((opt & QCborValue::UseFloat16) == QCborValue::UseFloat16)
861 return writer.append(std::numeric_limits<qfloat16>::quiet_NaN());
862 return writer.append(std::numeric_limits<float>::quiet_NaN());
863 }
864 return writer.append(qt_qnan());
865 }
866
867 if (qt_is_inf(d)) {
868 d = d > 0 ? qt_inf() : -qt_inf();
869 } else if (opt & QCborValue::UseIntegers) {
870 quint64 i;
871 if (convertDoubleTo(d, &i)) {
872 if (d < 0)
873 return writer.append(QCborNegativeInteger(i));
874 return writer.append(i);
875 }
876 }
877
878 if (opt & QCborValue::UseFloat) {
879 float f = float(d);
880 if (f == d) {
881 // no data loss, we could use float
882 if ((opt & QCborValue::UseFloat16) == QCborValue::UseFloat16) {
883 qfloat16 f16 = qfloat16(f);
884 if (f16 == f)
885 return writer.append(f16);
886 }
887
888 return writer.append(f);
889 }
890 }
891
892 writer.append(d);
893}
894#endif // QT_CONFIG(cborstreamwriter) && !QT_BOOTSTRAPPED
895
896static inline int typeOrder(QCborValue::Type e1, QCborValue::Type e2)
897{
898 auto comparable = [](QCborValue::Type type) {
899 if (type >= 0x10000) // see QCborValue::isTag_helper()
900 return QCborValue::Tag;
901 return type;
902 };
903 return comparable(e1) - comparable(e2);
904}
905
906QCborContainerPrivate::~QCborContainerPrivate()
907{
908 // Do the depth-first search of all containers, and delete them
909 // bottom-to-top, so that the d-tor never recurses.
910 // We cannot use an approach with storing the elements to be removed in
911 // a container, because the container itself may throw on reallocation, and
912 // we do not want it in the d-tor.
913 // So, use the nextToDelete member of QCborContainerPrivate to first create
914 // a linked list of containers to be checked, and then build another linked
915 // list of the elements to be removed.
916 QCborContainerPrivate *pendingContainers = nullptr;
917 QCborContainerPrivate *toBeDeleted = nullptr;
918
919 auto appendNestedContainers = [&pendingContainers](QCborContainerPrivate *priv) {
920 for (const Element &e : std::as_const(priv->elements)) {
921 // only append if it actually has to be deleted
922 if ((e.flags & Element::IsContainer) == 0)
923 continue; // not a container
924 if (e.container->ref.deref())
925 continue; // still referenced
926 if (e.container->elements.isEmpty()) {
927 // empty container - delete immediately
928 delete e.container;
929 } else {
930 e.container->nextToDelete = pendingContainers;
931 pendingContainers = e.container;
932 }
933 }
934 };
935
936 // first, add our nested containers
937 appendNestedContainers(this);
938
939 // then try do descend deeper into the tree
940 while (pendingContainers) {
941 QCborContainerPrivate *priv = pendingContainers;
942 pendingContainers = priv->nextToDelete;
943
944 // Move priv into the list of containers that can now be deleted.
945 priv->nextToDelete = toBeDeleted;
946 toBeDeleted = priv;
947
948 // collect priv's children
949 appendNestedContainers(priv);
950 }
951
952 // Now actually delete everything
953 while (toBeDeleted) {
954 QCborContainerPrivate *priv = toBeDeleted;
955 toBeDeleted = priv->nextToDelete;
956
957 // Clear the elements, so that we do not recurse again.
958 // We cannot use QList::clear(), because it might allocate.
959 // Use move-assignment instead.
960 priv->elements = QList<Element>();
961
962 delete priv;
963 }
964}
965
967{
968 if (usedData > data.size() / 2)
969 return;
970
971 // 50% savings if we recreate the byte data
972 QByteArray newData;
973 QByteArray::size_type newUsedData = 0;
974 // Compact only elements that have byte data.
975 // Nested containers will be compacted when their data changes.
976 for (auto &e : elements) {
977 if (e.flags & Element::HasByteData) {
978 if (const ByteData *b = byteData(e))
979 e.value = addByteDataImpl(newData, newUsedData, b->byte(), b->len);
980 }
981 }
982 data = newData;
983 usedData = newUsedData;
984}
985
987{
988 if (!d) {
989 d = new QCborContainerPrivate;
990 } else {
991 // in case QList::reserve throws
992 QExplicitlySharedDataPointer u(new QCborContainerPrivate(*d));
993 if (reserved >= 0) {
994 u->elements.reserve(reserved);
995 u->compact();
996 }
997
998 d = u.take();
999 d->ref.storeRelaxed(0);
1000
1001 for (auto &e : std::as_const(d->elements)) {
1002 if (e.flags & Element::IsContainer)
1003 e.container->ref.ref();
1004 }
1005 }
1006 return d;
1007}
1008
1010{
1011 if (!d || d->ref.loadRelaxed() != 1)
1012 return clone(d, reserved);
1013 return d;
1014}
1015
1016/*!
1017 \internal
1018 Prepare for an insertion at position \a index
1019
1020 Detaches and ensures there are at least index entries in the array, padding
1021 with Undefined as needed.
1022*/
1024{
1025 Q_ASSERT(index >= 0);
1026 d = detach(d, index + 1);
1027 Q_ASSERT(d);
1028 qsizetype j = d->elements.size();
1029 while (j++ < index)
1031 return d;
1032}
1033
1034// Copies or moves \a value into element at position \a e. If \a disp is
1035// CopyContainer, then this function increases the reference count of the
1036// container, but otherwise leaves it unmodified. If \a disp is MoveContainer,
1037// then it transfers ownership (move semantics) and the caller must set
1038// value.container back to nullptr.
1040{
1041 if (value.n < 0) {
1042 // This QCborValue is an array, map, or tagged value (container points
1043 // to itself).
1044
1045 // detect self-assignment
1046 if (Q_UNLIKELY(this == value.container)) {
1047 Q_ASSERT(ref.loadRelaxed() >= 2);
1048 if (disp == MoveContainer)
1049 ref.deref(); // not deref() because it can't drop to 0
1050 QCborContainerPrivate *d = QCborContainerPrivate::clone(this);
1051 d->elements.detach();
1052 d->ref.storeRelaxed(1);
1053 e.container = d;
1054 } else {
1055 e.container = value.container;
1056 if (disp == CopyContainer)
1057 e.container->ref.ref();
1058 }
1059
1060 e.type = value.type();
1061 e.flags = Element::IsContainer;
1062 } else {
1063 // String data, copy contents
1064 e = value.container->elements.at(value.n);
1065
1066 // Copy string data, if any
1067 if (const ByteData *b = value.container->byteData(value.n)) {
1068 const auto flags = e.flags;
1069 // The element e has an invalid e.value, because it is copied from
1070 // value. It means that calling compact() will trigger an assertion
1071 // or just silently corrupt the data.
1072 // Temporarily unset the Element::HasByteData flag in order to skip
1073 // the element e in the call to compact().
1074 e.flags = e.flags & ~Element::HasByteData;
1075 if (this == value.container) {
1076 const QByteArray valueData = b->toByteArray();
1077 compact();
1078 e.value = addByteData(valueData, valueData.size());
1079 } else {
1080 compact();
1081 e.value = addByteData(b->byte(), b->len);
1082 }
1083 // restore the flags
1084 e.flags = flags;
1085 }
1086
1087 if (disp == MoveContainer)
1088 value.container->deref();
1089 }
1090}
1091
1092// in qstring.cpp
1093void qt_to_latin1_unchecked(uchar *dst, const char16_t *uc, qsizetype len);
1094
1096{
1097 qsizetype len = s.size();
1098 QtCbor::Element e;
1099 e.value = addByteData(nullptr, len);
1100 e.type = QCborValue::String;
1102 elements.append(e);
1103
1104 char *ptr = data.data() + e.value + sizeof(ByteData);
1105 uchar *l = reinterpret_cast<uchar *>(ptr);
1106 qt_to_latin1_unchecked(l, s.utf16(), len);
1107}
1108
1110{
1111 appendByteData(reinterpret_cast<const char *>(s.utf16()), s.size() * 2,
1112 QCborValue::String, QtCbor::Element::StringIsUtf16);
1113}
1114
1116{
1117 // create a new container for the returned value, containing the byte data
1118 // from this element, if it's worth it
1119 Q_ASSERT(e.flags & Element::HasByteData);
1120 auto b = byteData(e);
1121 auto container = new QCborContainerPrivate;
1122
1123 if (b->len + qsizetype(sizeof(*b)) < data.size() / 4) {
1124 // make a shallow copy of the byte data
1125 container->appendByteData(b->byte(), b->len, e.type, e.flags);
1126 usedData -= b->len + qsizetype(sizeof(*b));
1127 compact();
1128 } else {
1129 // just share with the original byte data
1130 container->data = data;
1131 container->elements.reserve(1);
1132 container->elements.append(e);
1133 }
1134
1135 return makeValue(e.type, 0, container);
1136}
1137
1138// Similar to QStringIterator::next() but returns malformed surrogate pair
1139// itself when one is detected, and returns the length in UTF-8.
1140static auto nextUtf32Character(const char16_t *&ptr, const char16_t *end) noexcept
1141{
1142 Q_ASSERT(ptr != end);
1143 struct R {
1144 char32_t c;
1145 qsizetype len; // in UTF-8 code units (bytes)
1146 };
1147
1148 const char16_t c = *ptr++;
1149
1150 if (c < 0x0800) {
1151 if (c < 0x0080)
1152 return R{c, 1};
1153 return R{c, 2};
1154 } else if (!QChar::isHighSurrogate(c) || ptr == end) {
1155 return R{c, 3};
1156 } else {
1157 return R{QChar::surrogateToUcs4(c, *ptr++), 4};
1158 }
1159}
1160
1161static qsizetype stringLengthInUtf8(const char16_t *ptr, const char16_t *end) noexcept
1162{
1163 qsizetype len = 0;
1164 while (ptr < end)
1165 len += nextUtf32Character(ptr, end).len;
1166 return len;
1167}
1168
1169static int compareStringsInUtf8(QStringView lhs, QStringView rhs, Comparison mode) noexcept
1170{
1171 if (mode == Comparison::ForEquality)
1172 return lhs == rhs ? 0 : 1;
1173
1174 // The UTF-16 length is *usually* comparable, but not always. There are
1175 // pathological cases where they can be wrong, so we need to compare as if
1176 // we were doing it in UTF-8. That includes the case of UTF-16 surrogate
1177 // pairs, because qstring.cpp sorts them before U+E000-U+FFFF.
1178 int diff = 0;
1179 qsizetype len1 = 0;
1180 qsizetype len2 = 0;
1181 const char16_t *src1 = lhs.utf16();
1182 const char16_t *src2 = rhs.utf16();
1183 const char16_t *end1 = src1 + lhs.size();
1184 const char16_t *end2 = src2 + rhs.size();
1185
1186 // first, scan until we find a difference (if any)
1187 do {
1188 auto r1 = nextUtf32Character(src1, end1);
1189 auto r2 = nextUtf32Character(src2, end2);
1190 len1 += r1.len;
1191 len2 += r2.len;
1192 diff = int(r1.c) - int(r2.c); // no underflow due to limited range
1193 } while (src1 < end1 && src2 < end2 && diff == 0);
1194
1195 // compute the full length past this first difference
1196 len1 += stringLengthInUtf8(src1, end1);
1197 len2 += stringLengthInUtf8(src2, end2);
1198 if (len1 == len2)
1199 return diff;
1200 return len1 < len2 ? -1 : 1;
1201}
1202
1203static int compareStringsInUtf8(QUtf8StringView lhs, QStringView rhs, Comparison mode) noexcept
1204{
1205 // CBOR requires that the shortest of the two strings be sorted first, so
1206 // we have to calculate the UTF-8 length of the UTF-16 string while
1207 // comparing. Unlike the UTF-32 comparison above, we convert the UTF-16
1208 // string to UTF-8 so we only need to decode one string.
1209
1210 const qsizetype len1 = lhs.size();
1211 const auto src1 = reinterpret_cast<const uchar *>(lhs.data());
1212 const char16_t *src2 = rhs.utf16();
1213 const char16_t *const end2 = src2 + rhs.size();
1214
1215 // Compare the two strings until we find a difference.
1216 int diff = 0;
1217 qptrdiff idx1 = 0;
1218 qsizetype len2 = 0;
1219 do {
1220 uchar utf8[4]; // longest possible Unicode character in UTF-8
1221 uchar *ptr = utf8;
1222 char16_t uc = *src2++;
1223 int r = QUtf8Functions::toUtf8<QUtf8BaseTraits>(uc, ptr, src2, end2);
1224 Q_UNUSED(r); // ignore failure to encode proper UTF-16 surrogates
1225
1226 qptrdiff n = ptr - utf8;
1227 len2 += n;
1228 if (len1 - idx1 < n)
1229 return -1; // lhs is definitely shorter
1230 diff = memcmp(src1 + idx1, utf8, n);
1231 idx1 += n;
1232 } while (diff == 0 && idx1 < len1 && src2 < end2);
1233
1234 if (mode == Comparison::ForEquality && diff)
1235 return diff;
1236 if ((idx1 == len1) != (src2 == end2)) {
1237 // One of the strings ended earlier than the other
1238 return idx1 == len1 ? -1 : 1;
1239 }
1240
1241 // We found a difference and neither string ended, so continue calculating
1242 // the UTF-8 length of rhs.
1243 len2 += stringLengthInUtf8(src2, end2);
1244
1245 if (len1 != len2)
1246 return len1 < len2 ? -1 : 1;
1247 return diff;
1248}
1249
1250static int compareStringsInUtf8(QStringView lhs, QUtf8StringView rhs, Comparison mode) noexcept
1251{
1252 return -compareStringsInUtf8(rhs, lhs, mode);
1253}
1254
1255QT_WARNING_DISABLE_MSVC(4146) // unary minus operator applied to unsigned type, result still unsigned
1256static int compareContainer(const QCborContainerPrivate *c1, const QCborContainerPrivate *c2,
1257 Comparison mode) noexcept;
1258static int compareElementNoData(const Element &e1, const Element &e2) noexcept
1259{
1260 Q_ASSERT(e1.type == e2.type);
1261
1262 if (e1.type == QCborValue::Integer) {
1263 // CBOR sorting order is 0, 1, 2, ..., INT64_MAX, -1, -2, -3, ... INT64_MIN
1264 // So we transform:
1265 // 0 -> 0
1266 // 1 -> 1
1267 // INT64_MAX -> INT64_MAX
1268 // -1 -> INT64_MAX + 1 = INT64_MAX - (-1)
1269 // -2 -> INT64_MAX + 2 = INT64_MAX - (-2)
1270 // INT64_MIN -> UINT64_MAX = INT64_MAX - INT64_MIN
1271 // Note how the unsigned arithmetic is well defined in C++ (it's
1272 // always performed modulo 2^64).
1273 auto makeSortable = [](qint64 v) {
1274 quint64 u = quint64(v);
1275 if (v < 0)
1276 return quint64(std::numeric_limits<qint64>::max()) + (-u);
1277 return u;
1278 };
1279 quint64 u1 = makeSortable(e1.value);
1280 quint64 u2 = makeSortable(e2.value);
1281 if (u1 < u2)
1282 return -1;
1283 if (u1 > u2)
1284 return 1;
1285 }
1286
1287 if (e1.type == QCborValue::Tag || e1.type == QCborValue::Double) {
1288 // Perform unsigned comparisons for the tag value and floating point
1289 quint64 u1 = quint64(e1.value);
1290 quint64 u2 = quint64(e2.value);
1291 if (u1 != u2)
1292 return u1 < u2 ? -1 : 1;
1293 }
1294
1295 // Any other type is equal at this point:
1296 // - simple types carry no value
1297 // - empty strings, arrays and maps
1298 return 0;
1299}
1300
1302 const QCborContainerPrivate *c2, const Element &e2,
1303 Comparison mode) noexcept
1304{
1305 int cmp = typeOrder(e1.type, e2.type);
1306 if (cmp != 0)
1307 return cmp;
1308
1309 if ((e1.flags & Element::IsContainer) || (e2.flags & Element::IsContainer))
1310 return compareContainer(e1.flags & Element::IsContainer ? e1.container : nullptr,
1311 e2.flags & Element::IsContainer ? e2.container : nullptr, mode);
1312
1313 // string data?
1314 const ByteData *b1 = c1 ? c1->byteData(e1) : nullptr;
1315 const ByteData *b2 = c2 ? c2->byteData(e2) : nullptr;
1316 if (b1 || b2) {
1317 auto len1 = b1 ? b1->len : 0;
1318 auto len2 = b2 ? b2->len : 0;
1319 if (len1 == 0 || len2 == 0)
1320 return len1 < len2 ? -1 : len1 == len2 ? 0 : 1;
1321
1322 // we definitely have data from this point forward
1323 Q_ASSERT(b1);
1324 Q_ASSERT(b2);
1325
1326 // Officially with CBOR, we sort first the string with the shortest
1327 // UTF-8 length. Since US-ASCII is just a subset of UTF-8, its length
1328 // is the UTF-8 length. But the UTF-16 length may not be directly
1329 // comparable.
1330 if ((e1.flags & Element::StringIsUtf16) && (e2.flags & Element::StringIsUtf16))
1331 return compareStringsInUtf8(b1->asStringView(), b2->asStringView(), mode);
1332
1333 if (!(e1.flags & Element::StringIsUtf16) && !(e2.flags & Element::StringIsUtf16)) {
1334 // Neither is UTF-16, so lengths are comparable too
1335 // (this case includes byte arrays too)
1336 if (len1 == len2) {
1337 if (mode == Comparison::ForEquality) {
1338 // GCC optimizes this to __memcmpeq(); Clang to bcmp()
1339 return memcmp(b1->byte(), b2->byte(), size_t(len1)) == 0 ? 0 : 1;
1340 }
1341 return memcmp(b1->byte(), b2->byte(), size_t(len1));
1342 }
1343 return len1 < len2 ? -1 : 1;
1344 }
1345
1346 // Only one is UTF-16
1347 if (e1.flags & Element::StringIsUtf16)
1348 return compareStringsInUtf8(b1->asStringView(), b2->asUtf8StringView(), mode);
1349 else
1350 return compareStringsInUtf8(b1->asUtf8StringView(), b2->asStringView(), mode);
1351 }
1352
1353 return compareElementNoData(e1, e2);
1354}
1355
1357 Comparison mode) noexcept
1358{
1359 auto len1 = c1 ? c1->elements.size() : 0;
1360 auto len2 = c2 ? c2->elements.size() : 0;
1361 if (len1 != len2) {
1362 // sort the shorter container first
1363 return len1 < len2 ? -1 : 1;
1364 }
1365
1366 for (qsizetype i = 0; i < len1; ++i) {
1367 const Element &e1 = c1->elements.at(i);
1368 const Element &e2 = c2->elements.at(i);
1369 int cmp = compareElementRecursive(c1, e1, c2, e2, mode);
1370 if (cmp)
1371 return cmp;
1372 }
1373
1374 return 0;
1375}
1376
1378 const QCborContainerPrivate *c2, Element e2,
1379 Comparison mode) noexcept
1380{
1381 return compareElementRecursive(c1, e1, c2, e2, mode);
1382}
1383
1384/*!
1385 \fn bool QCborValue::operator==(const QCborValue &lhs, const QCborValue &rhs)
1386
1387 Compares \a lhs and \a rhs, and returns true if they hold the same
1388 contents, false otherwise. If each QCborValue contains an array or map, the
1389 comparison is recursive to elements contained in them.
1390
1391 For more information on CBOR equality in Qt, see, compare().
1392
1393 \sa compare(), QCborMap::operator==(), operator!=(), operator<()
1394 */
1395
1396/*!
1397 \fn bool QCborValue::operator!=(const QCborValue &lhs, const QCborValue &rhs)
1398
1399 Compares \a lhs and \a rhs, and returns true if contents differ,
1400 false otherwise. If each QCborValue contains an array or map, the comparison
1401 is recursive to elements contained in them.
1402
1403 For more information on CBOR equality in Qt, see, QCborValue::compare().
1404
1405 \sa compare(), QCborMap::operator==(), operator==(), operator<()
1406 */
1407bool comparesEqual(const QCborValue &lhs,
1408 const QCborValue &rhs) noexcept
1409{
1410 Element e1 = QCborContainerPrivate::elementFromValue(lhs);
1411 Element e2 = QCborContainerPrivate::elementFromValue(rhs);
1412 return compareElementRecursive(lhs.container, e1, rhs.container, e2,
1414}
1415
1416/*!
1417 \fn bool QCborValue::operator<(const QCborValue &lhs, const QCborValue &rhs)
1418
1419 Compares \a lhs and \a rhs, and returns true if \a lhs should be
1420 sorted before \a rhs, false otherwise. If each QCborValue contains an
1421 array or map, the comparison is recursive to elements contained in them.
1422
1423 For more information on CBOR sorting order, see QCborValue::compare().
1424
1425 \sa compare(), QCborValue::operator==(), QCborMap::operator==(),
1426 operator==(), operator!=()
1427 */
1428
1429/*!
1430 \fn bool QCborValue::operator<=(const QCborValue &lhs, const QCborValue &rhs)
1431
1432 Compares \a lhs and \a rhs, and returns true if \a lhs should be
1433 sorted before \a rhs or is being equal to \a rhs, false otherwise.
1434 If each QCborValue contains an array or map, the comparison is recursive
1435 to elements contained in them.
1436
1437 For more information on CBOR sorting order, see QCborValue::compare().
1438
1439 \sa compare(), QCborValue::operator<(), QCborMap::operator==(),
1440 operator==(), operator!=()
1441*/
1442
1443/*!
1444 \fn bool QCborValue::operator>(const QCborValue &lhs, const QCborValue &rhs)
1445
1446 Compares \a lhs and \a rhs, and returns true if \a lhs should be
1447 sorted after \a rhs, false otherwise. If each QCborValue contains an
1448 array or map, the comparison is recursive to elements contained in them.
1449
1450 For more information on CBOR sorting order, see QCborValue::compare().
1451
1452 \sa compare(), QCborValue::operator>=(), QCborMap::operator==(),
1453 operator==(), operator!=()
1454*/
1455
1456/*!
1457 \fn bool QCborValue::operator>=(const QCborValue &lhs, const QCborValue &rhs)
1458
1459 Compares \a lhs and \a rhs, and returns true if \a lhs should be
1460 sorted after \a rhs or is being equal to \a rhs, false otherwise.
1461 If each QCborValue contains an array or map, the comparison is recursive
1462 to elements contained in them.
1463
1464 For more information on CBOR sorting order, see QCborValue::compare().
1465
1466 \sa compare(), QCborValue::operator>(), QCborMap::operator==(),
1467 operator==(), operator!=()
1468*/
1469
1470/*!
1471 Compares this value and \a other, and returns an integer that indicates
1472 whether this value should be sorted prior to (if the result is negative) or
1473 after \a other (if the result is positive). If this function returns 0, the
1474 two values are equal and hold the same contents.
1475
1476 If each QCborValue contains an array or map, the comparison is recursive to
1477 elements contained in them.
1478
1479 \section3 Not-a-number (NaN) comparisons
1480
1481 QCborValue compares the exact bit representation of the NaN, as provided in
1482 the constructor. This means NaNs will compare equal if they have the same
1483 representation, unlike what one may expect for floating point comparisons.
1484 However, NaNs with different payloads or sign will compare unequal.
1485
1486 This implies QCborValue provides strong and total ordering semantics.
1487
1488 \section3 Extended types
1489
1490 QCborValue compares equal a QCborValue containing an extended type, like
1491 \l{Type}{Url} and \l{Type}{Url} and its equivalent tagged representation.
1492 So, for example, the following expression is true:
1493
1494 \snippet code/src_corelib_serialization_qcborvalue.cpp 3
1495
1496 Do note that Qt types like \l QUrl and \l QDateTime will normalize and
1497 otherwise modify their arguments. The expression above is true only because
1498 the string on the right side is the normalized value that the QCborValue on
1499 the left would take. If, for example, the "https" part were uppercase in
1500 both sides, the comparison would fail. For information on normalizations
1501 performed by QCborValue, please consult the documentation of the
1502 constructor taking the Qt type in question.
1503
1504 \section3 Sorting order
1505
1506 Sorting order in CBOR is defined in
1507 \l{RFC 7049, section 3.9}, which
1508 discusses the sorting of keys in a map when following the Canonical
1509 encoding. According to the specification, "sorting is performed on the
1510 bytes of the representation of the key data items" and lists as
1511 consequences that:
1512
1513 \list
1514 \li "If two keys have different lengths, the shorter one sorts earlier;"
1515 \li "If two keys have the same length, the one with the lower value in
1516 (byte-wise) lexical order sorts earlier."
1517 \endlist
1518
1519 This results in surprising sorting of QCborValues, where the result of this
1520 function is different from that which would later be retrieved by comparing the
1521 contained elements. For example, the QCborValue containing string "zzz"
1522 sorts before the QCborValue with string "foobar", even though when
1523 comparing as \l{QString::compare()}{QStrings} or
1524 \l{QByteArray}{QByteArrays} the "zzz" sorts after "foobar"
1525 (dictionary order).
1526
1527 The specification does not clearly indicate what sorting order should be
1528 done for values of different types (it says sorting should not pay
1529 "attention to the 3/5 bit splitting for major types"). QCborValue makes the
1530 assumption that types should be sorted too. The numeric values of the
1531 QCborValue::Type enumeration are in that order, with the exception of the
1532 extended types, which compare as their tagged equivalents.
1533
1534 \note Sorting order is preliminary and is subject to change. Applications
1535 should not depend on the order returned by this function for the time
1536 being.
1537
1538 \sa QCborArray::compare(), QCborMap::compare(), operator==()
1539 */
1540int QCborValue::compare(const QCborValue &other) const
1541{
1542 Element e1 = QCborContainerPrivate::elementFromValue(*this);
1543 Element e2 = QCborContainerPrivate::elementFromValue(other);
1544 return compareElementRecursive(container, e1, other.container, e2, Comparison::ForOrdering);
1545}
1546
1547bool comparesEqual(const QCborArray &lhs, const QCborArray &rhs) noexcept
1548{
1549 return compareContainer(lhs.d.constData(), rhs.d.constData(), Comparison::ForEquality) == 0;
1550}
1551
1552int QCborArray::compare(const QCborArray &other) const noexcept
1553{
1554 return compareContainer(d.data(), other.d.data(), Comparison::ForOrdering);
1555}
1556
1557bool QCborArray::comparesEqual_helper(const QCborArray &lhs, const QCborValue &rhs) noexcept
1558{
1559 if (typeOrder(QCborValue::Array, rhs.type()))
1560 return false;
1561 return compareContainer(lhs.d.constData(), rhs.container, Comparison::ForEquality) == 0;
1562}
1563
1564Qt::strong_ordering
1565QCborArray::compareThreeWay_helper(const QCborArray &lhs, const QCborValue &rhs) noexcept
1566{
1567 int c = typeOrder(QCborValue::Array, rhs.type());
1568 if (c == 0)
1569 c = compareContainer(lhs.d.constData(), rhs.container, Comparison::ForOrdering);
1570 return Qt::compareThreeWay(c, 0);
1571}
1572
1573bool comparesEqual(const QCborMap &lhs, const QCborMap &rhs) noexcept
1574{
1575 return compareContainer(lhs.d.constData(), rhs.d.constData(), Comparison::ForEquality) == 0;
1576}
1577
1578int QCborMap::compare(const QCborMap &other) const noexcept
1579{
1580 return compareContainer(d.data(), other.d.data(), Comparison::ForOrdering);
1581}
1582
1583bool QCborMap::comparesEqual_helper(const QCborMap &lhs, const QCborValue &rhs) noexcept
1584{
1585 if (typeOrder(QCborValue::Map, rhs.type()))
1586 return false;
1587 return compareContainer(lhs.d.constData(), rhs.container, Comparison::ForEquality) == 0;
1588}
1589
1590Qt::strong_ordering
1591QCborMap::compareThreeWay_helper(const QCborMap &lhs, const QCborValue &rhs) noexcept
1592{
1593 int c = typeOrder(QCborValue::Map, rhs.type());
1594 if (c == 0)
1595 c = compareContainer(lhs.d.constData(), rhs.container, Comparison::ForOrdering);
1596 return Qt::compareThreeWay(c, 0);
1597}
1598
1599#if QT_CONFIG(cborstreamwriter) && !defined(QT_BOOTSTRAPPED)
1600static void encodeToCbor(QCborStreamWriter &writer, const QCborContainerPrivate *d, qsizetype idx,
1601 QCborValue::EncodingOptions opt)
1602{
1603 if (idx == -QCborValue::Array || idx == -QCborValue::Map) {
1604 bool isArray = (idx == -QCborValue::Array);
1605 qsizetype len = d ? d->elements.size() : 0;
1606 if (isArray)
1607 writer.startArray(quint64(len));
1608 else
1609 writer.startMap(quint64(len) / 2);
1610
1611 for (idx = 0; idx < len; ++idx)
1612 encodeToCbor(writer, d, idx, opt);
1613
1614 if (isArray)
1615 writer.endArray();
1616 else
1617 writer.endMap();
1618 } else if (idx < 0) {
1619 Q_ASSERT_X(d != nullptr, "QCborValue", "Unexpected null container");
1620 if (d->elements.size() != 2) {
1621 // invalid state!
1622 qWarning("QCborValue: invalid tag state; are you encoding something that was improperly decoded?");
1623 return;
1624 }
1625
1626 // write the tag and the tagged element
1627 writer.append(QCborTag(d->elements.at(0).value));
1628 encodeToCbor(writer, d, 1, opt);
1629 } else {
1630 Q_ASSERT_X(d != nullptr, "QCborValue", "Unexpected null container");
1631 // just one element
1632 auto e = d->elements.at(idx);
1633 const ByteData *b = d->byteData(idx);
1634 switch (e.type) {
1635 case QCborValue::Integer:
1636 return writer.append(qint64(e.value));
1637
1638 case QCborValue::ByteArray:
1639 if (b)
1640 return writer.appendByteString(b->byte(), b->len);
1641 return writer.appendByteString("", 0);
1642
1643 case QCborValue::String:
1644 if (b) {
1645 if (e.flags & Element::StringIsUtf16)
1646 return writer.append(b->asStringView());
1647 return writer.appendTextString(b->byte(), b->len);
1648 }
1649 return writer.append(QLatin1StringView());
1650
1651 case QCborValue::Array:
1652 case QCborValue::Map:
1653 case QCborValue::Tag:
1654 // recurse
1655 return encodeToCbor(writer,
1656 e.flags & Element::IsContainer ? e.container : nullptr,
1657 -qsizetype(e.type), opt);
1658
1659 case QCborValue::SimpleType:
1660 case QCborValue::False:
1661 case QCborValue::True:
1662 case QCborValue::Null:
1663 case QCborValue::Undefined:
1664 break;
1665
1666 case QCborValue::Double:
1667 return writeDoubleToCbor(writer, e.fpvalue(), opt);
1668
1669 case QCborValue::Invalid:
1670 return;
1671
1672 case QCborValue::DateTime:
1673 case QCborValue::Url:
1674 case QCborValue::RegularExpression:
1675 case QCborValue::Uuid:
1676 // recurse as tag
1677 return encodeToCbor(writer, e.container, -QCborValue::Tag, opt);
1678 }
1679
1680 // maybe it's a simple type
1681 int simpleType = e.type - QCborValue::SimpleType;
1682 if (unsigned(simpleType) < 0x100)
1683 return writer.append(QCborSimpleType(simpleType));
1684
1685 // if we got here, we've got an unknown type
1686 qWarning("QCborValue: found unknown type 0x%x", e.type);
1687 }
1688}
1689#endif // QT_CONFIG(cborstreamwriter) && !QT_BOOTSTRAPPED
1690
1691#if QT_CONFIG(cborstreamreader)
1692// confirm that our basic Types match QCborStreamReader::Types
1693static_assert(int(QCborValue::Integer) == int(QCborStreamReader::UnsignedInteger));
1694static_assert(int(QCborValue::ByteArray) == int(QCborStreamReader::ByteArray));
1695static_assert(int(QCborValue::String) == int(QCborStreamReader::String));
1696static_assert(int(QCborValue::Array) == int(QCborStreamReader::Array));
1697static_assert(int(QCborValue::Map) == int(QCborStreamReader::Map));
1698static_assert(int(QCborValue::Tag) == int(QCborStreamReader::Tag));
1699
1700static inline double integerOutOfRange(const QCborStreamReader &reader)
1701{
1702 Q_ASSERT(reader.isInteger());
1703 if (reader.isUnsignedInteger()) {
1704 quint64 v = reader.toUnsignedInteger();
1705 if (qint64(v) < 0)
1706 return double(v);
1707 } else {
1708 quint64 v = quint64(reader.toNegativeInteger());
1709 if (qint64(v - 1) < 0)
1710 return -double(v);
1711 }
1712
1713 // result is in range
1714 return 0;
1715}
1716
1717static Element decodeBasicValueFromCbor(QCborStreamReader &reader)
1718{
1719 Element e = {};
1720
1721 switch (reader.type()) {
1722 case QCborStreamReader::UnsignedInteger:
1723 case QCborStreamReader::NegativeInteger:
1724 if (double d = integerOutOfRange(reader)) {
1725 e.type = QCborValue::Double;
1726 qToUnaligned(d, &e.value);
1727 } else {
1728 e.type = QCborValue::Integer;
1729 e.value = reader.toInteger();
1730 }
1731 break;
1732 case QCborStreamReader::SimpleType:
1733 e.type = QCborValue::Type(quint8(reader.toSimpleType()) + 0x100);
1734 break;
1735 case QCborStreamReader::Float16:
1736 e.type = QCborValue::Double;
1737 qToUnaligned(double(reader.toFloat16()), &e.value);
1738 break;
1739 case QCborStreamReader::Float:
1740 e.type = QCborValue::Double;
1741 qToUnaligned(double(reader.toFloat()), &e.value);
1742 break;
1743 case QCborStreamReader::Double:
1744 e.type = QCborValue::Double;
1745 qToUnaligned(reader.toDouble(), &e.value);
1746 break;
1747
1748 default:
1749 Q_UNREACHABLE();
1750 }
1751
1752 reader.next();
1753 return e;
1754}
1755
1756// Clamp allocation to avoid crashing due to corrupt stream. This also
1757// ensures we never overflow qsizetype. The returned length is doubled for Map
1758// entries to account for key-value pairs.
1759static qsizetype clampedContainerLength(const QCborStreamReader &reader)
1760{
1761 if (!reader.isLengthKnown())
1762 return 0;
1763 int mapShift = reader.isMap() ? 1 : 0;
1764 quint64 shiftedMaxElements = MaximumPreallocatedElementCount >> mapShift;
1765 qsizetype len = qsizetype(qMin(reader.length(), shiftedMaxElements));
1766 return len << mapShift;
1767}
1768
1769static inline QCborContainerPrivate *createContainerFromCbor(QCborStreamReader &reader, int remainingRecursionDepth)
1770{
1771 if (Q_UNLIKELY(remainingRecursionDepth == 0)) {
1772 QCborContainerPrivate::setErrorInReader(reader, { QCborError::NestingTooDeep });
1773 return nullptr;
1774 }
1775
1776 QCborContainerPrivate *d = nullptr;
1777 {
1778 // in case QList::reserve throws
1779 QExplicitlySharedDataPointer u(new QCborContainerPrivate);
1780 if (qsizetype len = clampedContainerLength(reader))
1781 u->elements.reserve(len);
1782 d = u.take();
1783 }
1784
1785 reader.enterContainer();
1786 if (reader.lastError() != QCborError::NoError) {
1787 d->elements.clear();
1788 return d;
1789 }
1790
1791 while (reader.hasNext() && reader.lastError() == QCborError::NoError)
1792 d->decodeValueFromCbor(reader, remainingRecursionDepth - 1);
1793
1794 if (reader.lastError() == QCborError::NoError)
1795 reader.leaveContainer();
1796 else
1797 d->elements.squeeze();
1798
1799 return d;
1800}
1801
1802static QCborValue taggedValueFromCbor(QCborStreamReader &reader, int remainingRecursionDepth)
1803{
1804 if (Q_UNLIKELY(remainingRecursionDepth == 0)) {
1805 QCborContainerPrivate::setErrorInReader(reader, { QCborError::NestingTooDeep });
1806 return QCborValue::Invalid;
1807 }
1808
1809 auto d = new QCborContainerPrivate;
1810 d->append(reader.toTag());
1811 reader.next();
1812
1813 if (reader.lastError() == QCborError::NoError) {
1814 // decode tagged value
1815 d->decodeValueFromCbor(reader, remainingRecursionDepth - 1);
1816 }
1817
1818 QCborValue::Type type;
1819 if (reader.lastError() == QCborError::NoError) {
1820 // post-process to create our extended types
1821 type = convertToExtendedType(d);
1822 } else {
1823 // decoding error
1824 type = QCborValue::Invalid;
1825 }
1826
1827 // note: may return invalid state!
1828 return QCborContainerPrivate::makeValue(type, -1, d);
1829}
1830
1831// in qcborstream.cpp
1832extern void qt_cbor_stream_set_error(QCborStreamReaderPrivate *d, QCborError error);
1833inline void QCborContainerPrivate::setErrorInReader(QCborStreamReader &reader, QCborError error)
1834{
1835 qt_cbor_stream_set_error(reader.d.get(), error);
1836}
1837
1838extern QCborStreamReader::StringResultCode qt_cbor_append_string_chunk(QCborStreamReader &reader, QByteArray *data);
1839
1840void QCborContainerPrivate::decodeStringFromCbor(QCborStreamReader &reader)
1841{
1842 if (reader.lastError() != QCborError::NoError)
1843 return;
1844
1845 qsizetype len = reader.currentStringChunkSize();
1846 if (len < 0)
1847 return; // error
1848 if (len > reader.bytesAvailable()) {
1849 // don't even try to allocate the first block, we can't succeed
1850 return setErrorInReader(reader, { QCborError::EndOfFile });
1851 }
1852
1853 auto resetSize = qScopeGuard([this, oldSize = data.size()] {
1854 data.resize(oldSize);
1855 if (oldSize < data.capacity() / 2)
1856 data.squeeze();
1857 });
1858
1859 // allocate the entry in the array and in the byte data: if this is a
1860 // single chunk (the typical case), it's the only allocation
1861 Element e = {};
1862 e.type = QCborValue::Type(reader.type());
1863 if (len || !reader.isLengthKnown()) {
1864 // The use of size_t means none of the operations here can overflow because
1865 // all inputs are less than half SIZE_MAX.
1866 size_t offset = data.size();
1867
1868 // add space for aligned ByteData (this can't overflow)
1869 offset += sizeof(QtCbor::ByteData) + alignof(QtCbor::ByteData) - 1;
1870 offset &= ~(alignof(QtCbor::ByteData) - 1);
1871 if (offset > size_t(QByteArray::maxSize())) {
1872 // overflow
1873 setErrorInReader(reader, { QCborError::DataTooLarge });
1874 return;
1875 }
1876
1877 // and calculate the size we want to have
1878 // (there's a non-zero chance that we won't need this memory at all,
1879 // so cap how much we allocate)
1880 size_t newCapacity = offset + qMin(size_t(len), MaxAcceptableElementMemoryUse);
1881 if (newCapacity > size_t(QByteArray::maxSize())) {
1882 // this may cause an allocation failure
1883 newCapacity = QByteArray::maxSize();
1884 }
1885 if (newCapacity > size_t(data.capacity()))
1886 data.reserve(newCapacity);
1887 data.resize(offset);
1888 e.value = offset - sizeof(QtCbor::ByteData);
1889 e.flags = Element::HasByteData;
1890 }
1891
1892 // read chunks
1893 bool isAscii = (e.type == QCborValue::String);
1894 QCborStreamReader::StringResultCode status = qt_cbor_append_string_chunk(reader, &data);
1895 while (status == QCborStreamReader::Ok) {
1896 if (e.type == QCborValue::String && len) {
1897 // verify UTF-8 string validity
1898 auto utf8result = QUtf8::isValidUtf8(QByteArrayView(data).last(len));
1899 if (!utf8result.isValidUtf8) {
1900 setErrorInReader(reader, { QCborError::InvalidUtf8String });
1901 return;
1902 }
1903 isAscii = isAscii && utf8result.isValidAscii;
1904 }
1905
1906 len = reader.currentStringChunkSize();
1907 if (len < 0) {
1908 // QCborStreamReader has already failed
1909 Q_ASSERT(reader.lastError() != QCborError::NoError);
1910 return;
1911 }
1912 QCborError err = {};
1913 if (len > reader.bytesAvailable())
1914 err = { QCborError::EndOfFile };
1915 else if (size_t(data.size()) + size_t(len) > size_t(QByteArray::maxSize()))
1916 err = { QCborError::DataTooLarge };
1917 if (err) {
1918 setErrorInReader(reader, err);
1919 return;
1920 }
1921
1922 status = qt_cbor_append_string_chunk(reader, &data);
1923 }
1924
1925 // update size
1926 if (status == QCborStreamReader::EndOfString && e.flags & Element::HasByteData) {
1927 Q_ASSERT(data.isDetached());
1928 const char *ptr = data.constData() + e.value;
1929QT_WARNING_PUSH
1930#if Q_CC_GNU >= 1600 && Q_CC_GNU < 1700
1931 QT_WARNING_DISABLE_GCC("-Warray-bounds")
1932#endif
1933 auto b = new (const_cast<char *>(ptr)) ByteData;
1934QT_WARNING_POP
1935 b->len = data.size() - e.value - int(sizeof(*b));
1936 usedData += b->len;
1937
1938 if (isAscii) {
1939 // set the flag if it is US-ASCII only (as it often is)
1940 Q_ASSERT(e.type == QCborValue::String);
1941 e.flags |= Element::StringIsAscii;
1942 }
1943
1944 // check that this UTF-8 text string can be loaded onto a QString
1945 if (e.type == QCborValue::String) {
1946 if (Q_UNLIKELY(b->len > QString::maxSize())) {
1947 setErrorInReader(reader, { QCborError::DataTooLarge });
1948 return;
1949 }
1950 }
1951 }
1952
1953 if (status == QCborStreamReader::EndOfString) {
1954 elements.append(e);
1955 resetSize.dismiss();
1956 }
1957}
1958
1959void QCborContainerPrivate::decodeValueFromCbor(QCborStreamReader &reader, int remainingRecursionDepth)
1960{
1961 QCborStreamReader::Type t = reader.type();
1962 switch (t) {
1963 case QCborStreamReader::UnsignedInteger:
1964 case QCborStreamReader::NegativeInteger:
1965 case QCborStreamReader::SimpleType:
1966 case QCborStreamReader::Float16:
1967 case QCborStreamReader::Float:
1968 case QCborStreamReader::Double:
1969 elements.append(decodeBasicValueFromCbor(reader));
1970 break;
1971
1972 case QCborStreamReader::ByteArray:
1973 case QCborStreamReader::String:
1974 decodeStringFromCbor(reader);
1975 break;
1976
1977 case QCborStreamReader::Array:
1978 case QCborStreamReader::Map:
1979 return append(makeValue(t == QCborStreamReader::Array ? QCborValue::Array : QCborValue::Map, -1,
1980 createContainerFromCbor(reader, remainingRecursionDepth),
1981 MoveContainer));
1982
1983 case QCborStreamReader::Tag:
1984 return append(taggedValueFromCbor(reader, remainingRecursionDepth));
1985
1986 case QCborStreamReader::Invalid:
1987 return; // probably a decode error
1988 }
1989}
1990#endif // QT_CONFIG(cborstreamreader)
1991
1992/*!
1993 Creates a QCborValue with byte array value \a ba. The value can later be
1994 retrieved using toByteArray().
1995
1996 \sa toByteArray(), isByteArray(), isString()
1997 */
1998QCborValue::QCborValue(const QByteArray &ba)
1999 : n(0), container(new QCborContainerPrivate), t(ByteArray)
2000{
2001 container->appendByteData(ba.constData(), ba.size(), t);
2002 container->ref.storeRelaxed(1);
2003}
2004
2005/*!
2006 Creates a QCborValue with string value \a s. The value can later be
2007 retrieved using toString().
2008
2009 \sa toString(), isString(), isByteArray()
2010 */
2011QCborValue::QCborValue(const QString &s) : QCborValue(qToStringViewIgnoringNull(s)) {}
2012
2013/*!
2014 Creates a QCborValue with string value \a s. The value can later be
2015 retrieved using toString().
2016
2017 \sa toString(), isString(), isByteArray()
2018*/
2019QCborValue::QCborValue(QStringView s)
2020 : n(0), container(new QCborContainerPrivate), t(String)
2021{
2022 container->append(s);
2023 container->ref.storeRelaxed(1);
2024}
2025
2026/*!
2027 \overload
2028
2029 Creates a QCborValue with the Latin-1 string viewed by \a s.
2030 The value can later be retrieved using toString().
2031
2032 \sa toString(), isString(), isByteArray()
2033 */
2034QCborValue::QCborValue(QLatin1StringView s)
2035 : n(0), container(new QCborContainerPrivate), t(String)
2036{
2037 container->append(s);
2038 container->ref.storeRelaxed(1);
2039}
2040
2041/*!
2042 \fn QCborValue::QCborValue(const QCborArray &a)
2043 \fn QCborValue::QCborValue(QCborArray &&a)
2044
2045 Creates a QCborValue with the array \a a. The array can later be retrieved
2046 using toArray().
2047
2048 \sa toArray(), isArray(), isMap()
2049 */
2050QCborValue::QCborValue(const QCborArray &a)
2051 : n(-1), container(a.d.data()), t(Array)
2052{
2053 if (container)
2054 container->ref.ref();
2055}
2056
2057/*!
2058 \fn QCborValue::QCborValue(const QCborMap &m)
2059 \fn QCborValue::QCborValue(QCborMap &&m)
2060
2061 Creates a QCborValue with the map \a m. The map can later be retrieved
2062 using toMap().
2063
2064 \sa toMap(), isMap(), isArray()
2065 */
2066QCborValue::QCborValue(const QCborMap &m)
2067 : n(-1), container(m.d.data()), t(Map)
2068{
2069 if (container)
2070 container->ref.ref();
2071}
2072
2073/*!
2074 \fn QCborValue::QCborValue(QCborTag tag, const QCborValue &tv)
2075 \fn QCborValue::QCborValue(QCborKnownTags tag, const QCborValue &tv)
2076
2077 Creates a QCborValue for the extended type represented by the tag value \a
2078 tag, tagging value \a tv. The tag can later be retrieved using tag() and
2079 the tagged value using taggedValue().
2080
2081 \sa isTag(), tag(), taggedValue(), QCborKnownTags
2082 */
2083QCborValue::QCborValue(QCborTag tag, const QCborValue &tv)
2084 : n(-1), container(new QCborContainerPrivate), t(Tag)
2085{
2086 container->ref.storeRelaxed(1);
2087 container->append(tag);
2088 container->append(tv);
2089 t = convertToExtendedType(container);
2090}
2091
2092/*!
2093 Copies the contents of \a other into this object.
2094 */
2095QCborValue::QCborValue(const QCborValue &other) noexcept
2096 : n(other.n), container(other.container), t(other.t)
2097{
2098 if (container)
2099 container->ref.ref();
2100}
2101
2102#if QT_CONFIG(datestring)
2103static QCborValue::Type setToExtendedDateTimeType(QCborContainerPrivate *d, QStringView text)
2104{
2105 // when called from convertToExtendedType(), *d isn't pristine
2106 d->data.resize(0);
2107 d->elements.resize(0);
2108 d->elements.reserve(2);
2109
2110 d->append(QCborTag(QCborKnownTags::DateTimeString));
2111 d->appendAsciiString(text);
2112 return text.isEmpty() ? QCborValue::Tag : QCborValue::DateTime;
2113}
2114
2115/*!
2116 Creates a QCborValue object of the date/time extended type and containing
2117 the value represented by \a dt. The value can later be retrieved using
2118 toDateTime().
2119
2120 The CBOR date/time types are extension types using tags: either a string
2121 (in ISO date format) tagged as a \l{QCborKnownTags}{DateTime} or a number
2122 (of seconds since the start of 1970, UTC) tagged as a
2123 \l{QCborKnownTags}{UnixTime_t}. When parsing CBOR streams, QCborValue will
2124 convert \l{QCborKnownTags}{UnixTime_t} to the string-based type.
2125
2126 \sa toDateTime(), isDateTime(), taggedValue()
2127 */
2128QCborValue::QCborValue(const QDateTime &dt)
2129 : n(-1), container(new QCborContainerPrivate),
2130 t(setToExtendedDateTimeType(container, dt.toString(Qt::ISODateWithMs)))
2131{
2132 container->ref.storeRelaxed(1);
2133}
2134#endif
2135
2136#ifndef QT_BOOTSTRAPPED
2137/*!
2138 Creates a QCborValue object of the URL extended type and containing the
2139 value represented by \a url. The value can later be retrieved using toUrl().
2140
2141 The CBOR URL type is an extended type represented by a string tagged as an
2142 \l{QCborKnownTags}{Url}.
2143
2144 \sa toUrl(), isUrl(), taggedValue()
2145 */
2146QCborValue::QCborValue(const QUrl &url)
2147 : QCborValue(QCborKnownTags::Url, url.toString(QUrl::DecodeReserved).toUtf8())
2148{
2149 // change types
2150 t = Url;
2151 container->elements[1].type = String;
2152}
2153
2154#if QT_CONFIG(regularexpression)
2155/*!
2156 Creates a QCborValue object of the regular expression pattern extended type
2157 and containing the value represented by \a rx. The value can later be retrieved
2158 using toRegularExpression().
2159
2160 The CBOR regular expression type is an extended type represented by a
2161 string tagged as an \l{QCborKnownTags}{RegularExpression}. Note that CBOR
2162 regular expressions only store the patterns, so any flags that the
2163 QRegularExpression object may carry will be lost.
2164
2165 \sa toRegularExpression(), isRegularExpression(), taggedValue()
2166 */
2167QCborValue::QCborValue(const QRegularExpression &rx)
2168 : QCborValue(QCborKnownTags::RegularExpression, rx.pattern())
2169{
2170 // change type
2171 t = RegularExpression;
2172}
2173#endif // QT_CONFIG(regularexpression)
2174
2175/*!
2176 Creates a QCborValue object of the UUID extended type and containing the
2177 value represented by \a uuid. The value can later be retrieved using
2178 toUuid().
2179
2180 The CBOR UUID type is an extended type represented by a byte array tagged
2181 as an \l{QCborKnownTags}{Uuid}.
2182
2183 \sa toUuid(), isUuid(), taggedValue()
2184 */
2185QCborValue::QCborValue(const QUuid &uuid)
2186 : QCborValue(QCborKnownTags::Uuid, uuid.toRfc4122())
2187{
2188 // change our type
2189 t = Uuid;
2190}
2191#endif
2192
2193/*!
2194 \internal
2195
2196 Completes construction of a QCborValue whose Type constructor requested a
2197 tagged or extended type (see isTag_helper()). Such types keep their value in
2198 a container holding the tag and the tagged value, so a bare QCborValue(Type)
2199 would otherwise be an empty, container-less object that does not compare
2200 equal to one built from a default-constructed value (QTBUG-149398).
2201 */
2202void QCborValue::adjustDefaultConstructedExtendedType()
2203{
2204 switch (t) {
2205 case Tag:
2206 *this = QCborValue(QCborTag(-1), QCborValue());
2207 return;
2208 case DateTime:
2209 // same as:
2210 //*this = QCborValue(QDateTime());
2211 *this = QCborValue(QCborKnownTags::DateTimeString, QString());
2212 return;
2213 case Url:
2214 // same as:
2215 //*this = QCborValue(QUrl());
2216 *this = QCborValue(QCborKnownTags::Url, QString());
2217 return;
2218 case RegularExpression:
2219 // same as:
2220 //*this = QCborValue(QRegularExpression());
2221 *this = QCborValue(QCborKnownTags::RegularExpression, QString());
2222 return;
2223 case Uuid:
2224 // same as:
2225 //*this = QCborValue(QUuid());
2226 *this = QCborValue(QCborKnownTags::Uuid, QByteArray(sizeof(QUuid), '\0'));
2227 return;
2228
2229 // not extended types:
2230 case Integer:
2231 case ByteArray:
2232 case String:
2233 case Array:
2234 case Map:
2235 case SimpleType:
2236 case False:
2237 case True:
2238 case Null:
2239 case Undefined:
2240 case Double:
2241 case Invalid:
2242 Q_UNREACHABLE();
2243 }
2244}
2245
2246// destructor
2247void QCborValue::dispose()
2248{
2249 container->deref();
2250}
2251
2252/*!
2253 Replaces the contents of this QCborObject with a copy of \a other.
2254 */
2255QCborValue &QCborValue::operator=(const QCborValue &other) noexcept
2256{
2257 n = other.n;
2258 assignContainer(container, other.container);
2259 t = other.t;
2260 return *this;
2261}
2262
2263/*!
2264 Returns the tag of this extended QCborValue object, if it is of the tag
2265 type, \a defaultValue otherwise.
2266
2267 CBOR represents extended types by associating a number (the tag) with a
2268 stored representation. This function returns that number. To retrieve the
2269 representation, use taggedValue().
2270
2271 \sa isTag(), taggedValue(), isDateTime(), isUrl(), isRegularExpression(), isUuid()
2272 */
2273QCborTag QCborValue::tag(QCborTag defaultValue) const
2274{
2275 return isTag() && container && container->elements.size() == 2 ?
2276 QCborTag(container->elements.at(0).value) : defaultValue;
2277}
2278
2279/*!
2280 Returns the tagged value of this extended QCborValue object, if it is of
2281 the tag type, \a defaultValue otherwise.
2282
2283 CBOR represents extended types by associating a number (the tag) with a
2284 stored representation. This function returns that representation. To
2285 retrieve the tag, use tag().
2286
2287 \sa isTag(), tag(), isDateTime(), isUrl(), isRegularExpression(), isUuid()
2288 */
2289QCborValue QCborValue::taggedValue(const QCborValue &defaultValue) const
2290{
2291 return isTag() && container && container->elements.size() == 2 ?
2292 container->valueAt(1) : defaultValue;
2293}
2294
2295/*!
2296 Returns the byte array value stored in this QCborValue, if it is of the byte
2297 array type. Otherwise, it returns \a defaultValue.
2298
2299 Note that this function performs no conversion from other types to
2300 QByteArray.
2301
2302 \sa isByteArray(), isString(), toString()
2303 */
2304QByteArray QCborValue::toByteArray(const QByteArray &defaultValue) const
2305{
2306 if (!container || !isByteArray())
2307 return defaultValue;
2308
2309 Q_ASSERT(n >= 0);
2310 return container->byteArrayAt(n);
2311}
2312
2313/*!
2314 Returns the string value stored in this QCborValue, if it is of the string
2315 type. Otherwise, it returns \a defaultValue.
2316
2317 Note that this function performs no conversion from other types to
2318 QString.
2319
2320 \sa toStringView(), isString(), isByteArray(), toByteArray()
2321 */
2322QString QCborValue::toString(const QString &defaultValue) const
2323{
2324 if (!container || !isString())
2325 return defaultValue;
2326
2327 Q_ASSERT(n >= 0);
2328 return container->stringAt(n);
2329}
2330
2331/*!
2332 \since 6.10
2333
2334 Returns the string value stored in this QCborValue, if it is of the string
2335 type. Otherwise, it returns \a defaultValue. Since QCborValue stores
2336 strings in either US-ASCII, UTF-8 or UTF-16, the returned QAnyStringView
2337 may be in any of these encodings.
2338
2339 This function does not allocate memory. The return value is valid until the
2340 next call to a non-const member function on this object. If this object goes
2341 out of scope, the return value is valid until the next call to a non-const
2342 member function on the parent CBOR object (map or array).
2343
2344 Note that this function performs no conversion from other types to
2345 QString.
2346
2347 \sa toString(), isString(), isByteArray(), toByteArray()
2348*/
2349QAnyStringView QCborValue::toStringView(QAnyStringView defaultValue) const
2350{
2351 if (!container || !isString())
2352 return defaultValue;
2353
2354 Q_ASSERT(n >= 0);
2355 return container->anyStringViewAt(n);
2356}
2357
2358#if QT_CONFIG(datestring)
2359/*!
2360 Returns the date/time value stored in this QCborValue, if it is of the
2361 date/time extended type. Otherwise, it returns \a defaultValue.
2362
2363 Note that this function performs no conversion from other types to
2364 QDateTime.
2365
2366 \sa isDateTime(), isTag(), taggedValue()
2367 */
2368QDateTime QCborValue::toDateTime(const QDateTime &defaultValue) const
2369{
2370 if (!container || !isDateTime() || container->elements.size() != 2)
2371 return defaultValue;
2372
2373 Q_ASSERT(n == -1);
2374 const ByteData *byteData = container->byteData(1);
2375 if (!byteData)
2376 return defaultValue; // date/times are never empty, so this must be invalid
2377
2378 // Our data must be US-ASCII.
2379 Q_ASSERT((container->elements.at(1).flags & Element::StringIsUtf16) == 0);
2380 return QDateTime::fromString(byteData->asLatin1(), Qt::ISODateWithMs);
2381}
2382#endif
2383
2384#ifndef QT_BOOTSTRAPPED
2385/*!
2386 Returns the URL value stored in this QCborValue, if it is of the URL
2387 extended type. Otherwise, it returns \a defaultValue.
2388
2389 Note that this function performs no conversion from other types to QUrl.
2390
2391 \sa isUrl(), isTag(), taggedValue()
2392 */
2393QUrl QCborValue::toUrl(const QUrl &defaultValue) const
2394{
2395 if (!container || !isUrl() || container->elements.size() != 2)
2396 return defaultValue;
2397
2398 Q_ASSERT(n == -1);
2399 const ByteData *byteData = container->byteData(1);
2400 if (!byteData)
2401 return QUrl(); // valid, empty URL
2402
2403 return QUrl::fromEncoded(byteData->asByteArrayView());
2404}
2405
2406#if QT_CONFIG(regularexpression)
2407/*!
2408 Returns the regular expression value stored in this QCborValue, if it is of
2409 the regular expression pattern extended type. Otherwise, it returns \a
2410 defaultValue.
2411
2412 Note that this function performs no conversion from other types to
2413 QRegularExpression.
2414
2415 \sa isRegularExpression(), isTag(), taggedValue()
2416 */
2417QRegularExpression QCborValue::toRegularExpression(const QRegularExpression &defaultValue) const
2418{
2419 if (!container || !isRegularExpression() || container->elements.size() != 2)
2420 return defaultValue;
2421
2422 Q_ASSERT(n == -1);
2423 return QRegularExpression(container->stringAt(1));
2424}
2425#endif // QT_CONFIG(regularexpression)
2426
2427/*!
2428 Returns the UUID value stored in this QCborValue, if it is of the UUID
2429 extended type. Otherwise, it returns \a defaultValue.
2430
2431 Note that this function performs no conversion from other types to QUuid.
2432
2433 \sa isUuid(), isTag(), taggedValue()
2434 */
2435QUuid QCborValue::toUuid(const QUuid &defaultValue) const
2436{
2437 if (!container || !isUuid() || container->elements.size() != 2)
2438 return defaultValue;
2439
2440 Q_ASSERT(n == -1);
2441 const ByteData *byteData = container->byteData(1);
2442 if (!byteData)
2443 return defaultValue; // UUIDs must always be 16 bytes, so this must be invalid
2444
2445 return QUuid::fromRfc4122(byteData->asByteArrayView());
2446}
2447#endif
2448
2449/*!
2450 \fn QCborArray QCborValue::toArray() const
2451 \fn QCborArray QCborValue::toArray(const QCborArray &defaultValue) const
2452
2453 Returns the array value stored in this QCborValue, if it is of the array
2454 type. Otherwise, it returns \a defaultValue.
2455
2456 Note that this function performs no conversion from other types to
2457 QCborArray.
2458
2459 \sa isArray(), isByteArray(), isMap(), isContainer(), toMap()
2460 */
2461
2462/*!
2463 \fn QCborArray QCborValueRef::toArray() const
2464 \fn QCborArray QCborValueRef::toArray(const QCborArray &defaultValue) const
2465 \internal
2466
2467 Returns the array value stored in this QCborValue, if it is of the array
2468 type. Otherwise, it returns \a defaultValue.
2469
2470 Note that this function performs no conversion from other types to
2471 QCborArray.
2472
2473 \sa isArray(), isByteArray(), isMap(), isContainer(), toMap()
2474 */
2475QCborArray QCborValue::toArray() const
2476{
2477 return toArray(QCborArray());
2478}
2479
2480QCborArray QCborValue::toArray(const QCborArray &defaultValue) const
2481{
2482 if (!isArray())
2483 return defaultValue;
2484 QCborContainerPrivate *dd = nullptr;
2485 Q_ASSERT(n == -1 || container == nullptr);
2486 if (n < 0)
2487 dd = container;
2488 // return QCborArray(*dd); but that's UB if dd is nullptr
2489 return dd ? QCborArray(*dd) : QCborArray();
2490}
2491
2492/*!
2493 \fn QCborMap QCborValue::toMap() const
2494 \fn QCborMap QCborValue::toMap(const QCborMap &defaultValue) const
2495
2496 Returns the map value stored in this QCborValue, if it is of the map type.
2497 Otherwise, it returns \a defaultValue.
2498
2499 Note that this function performs no conversion from other types to
2500 QCborMap.
2501
2502 \sa isMap(), isArray(), isContainer(), toArray()
2503 */
2504
2505/*!
2506 \fn QCborMap QCborValueRef::toMap() const
2507 \fn QCborMap QCborValueRef::toMap(const QCborMap &defaultValue) const
2508 \internal
2509
2510 Returns the map value stored in this QCborValue, if it is of the map type.
2511 Otherwise, it returns \a defaultValue.
2512
2513 Note that this function performs no conversion from other types to
2514 QCborMap.
2515
2516 \sa isMap(), isArray(), isContainer(), toArray()
2517 */
2518QCborMap QCborValue::toMap() const
2519{
2520 return toMap(QCborMap());
2521}
2522
2523QCborMap QCborValue::toMap(const QCborMap &defaultValue) const
2524{
2525 if (!isMap())
2526 return defaultValue;
2527 QCborContainerPrivate *dd = nullptr;
2528 Q_ASSERT(n == -1 || container == nullptr);
2529 if (n < 0)
2530 dd = container;
2531 // return QCborMap(*dd); but that's UB if dd is nullptr
2532 return dd ? QCborMap(*dd) : QCborMap();
2533}
2534
2535/*!
2536 If this QCborValue is a QCborMap, searches elements for the value whose key
2537 matches \a key. If there's no key matching \a key in the map or if this
2538 QCborValue object is not a map, returns the undefined value.
2539
2540 This function is equivalent to:
2541
2542 \snippet code/src_corelib_serialization_qcborvalue.cpp 4
2543
2544 \sa operator[](qint64), QCborMap::operator[], QCborMap::value(),
2545 QCborMap::find()
2546 */
2547const QCborValue QCborValue::operator[](const QString &key) const
2548{
2549 return QCborContainerPrivate::findCborMapKey(*this, qToStringViewIgnoringNull(key));
2550}
2551
2552/*!
2553 \overload
2554
2555 If this QCborValue is a QCborMap, searches elements for the value whose key
2556 matches \a key. If there's no key matching \a key in the map or if this
2557 QCborValue object is not a map, returns the undefined value.
2558
2559 This function is equivalent to:
2560
2561 \snippet code/src_corelib_serialization_qcborvalue.cpp 5
2562
2563 \sa operator[](qint64), QCborMap::operator[], QCborMap::value(),
2564 QCborMap::find()
2565 */
2566const QCborValue QCborValue::operator[](QLatin1StringView key) const
2567{
2568 return QCborContainerPrivate::findCborMapKey(*this, key);
2569}
2570
2571/*!
2572 \overload
2573
2574 If this QCborValue is a QCborMap, searches elements for the value whose key
2575 matches \a key. If this is a QCborArray, returns the element whose index is
2576 \a key. If there's no matching value in the array or map, or if this
2577 QCborValue object is not an array or map, returns the undefined value.
2578
2579 \sa operator[], QCborMap::operator[], QCborMap::value(),
2580 QCborMap::find(), QCborArray::operator[], QCborArray::at()
2581 */
2582const QCborValue QCborValue::operator[](qint64 key) const
2583{
2584 if (isArray() && container && quint64(key) < quint64(container->elements.size()))
2585 return container->valueAt(key);
2586 return QCborContainerPrivate::findCborMapKey(*this, key);
2587}
2588
2589static bool shouldArrayRemainArray(qint64 key, QCborValue::Type t, QCborContainerPrivate *container)
2590{
2591 constexpr qint64 LargeKey = 0x10000;
2592 if (t != QCborValue::Array)
2593 return false;
2594 if (key < 0)
2595 return false; // negative keys can't be an array index
2596 if (key < LargeKey)
2597 return true;
2598
2599 // Only convert to map if key is greater than array size + 1
2600 qsizetype currentSize = container ? container->elements.size() : 0;
2601 return key <= currentSize;
2602}
2603
2604/*!
2605 \internal
2606 */
2608{
2609 if (Q_LIKELY(!array || array->elements.isEmpty()))
2610 return;
2611
2612 // The Q_LIKELY and the qWarning mark the rest of this function as unlikely
2613 qWarning("Using CBOR array as map forced conversion");
2614
2615 qsizetype size = array->elements.size();
2616 QCborContainerPrivate *map = QCborContainerPrivate::detach(array, size * 2);
2617 map->elements.resize(size * 2);
2618
2619 // this may be an in-place copy, so we have to do it from the end
2620 auto dst = map->elements.begin();
2621 auto src = array->elements.constBegin();
2622 for (qsizetype i = size - 1; i >= 0; --i) {
2623 Q_ASSERT(src->type != QCborValue::Invalid);
2624 dst[i * 2 + 1] = src[i];
2625 }
2626 for (qsizetype i = 0; i < size; ++i)
2627 dst[i * 2] = { i, QCborValue::Integer };
2628
2629 // update reference counts
2630 assignContainer(array, map);
2631}
2632
2633/*!
2634 \internal
2635 */
2636static QCborContainerPrivate *maybeGrow(QCborContainerPrivate *container, qsizetype index)
2637{
2638 auto replace = QCborContainerPrivate::grow(container, index);
2639 Q_ASSERT(replace);
2640 if (replace->elements.size() == index)
2641 replace->append(Undefined());
2642 else
2643 Q_ASSERT(replace->elements.size() > index);
2644 return assignContainer(container, replace);
2645}
2646
2647template <typename KeyType> inline QCborValueRef
2648QCborContainerPrivate::findOrAddMapKey(QCborValue &self, KeyType key)
2649{
2650 // we need a map, so convert if necessary
2651 if (self.isArray())
2652 convertArrayToMap(self.container);
2653 else if (!self.isMap())
2654 self = QCborValue(QCborValue::Map);
2655 self.t = QCborValue::Map;
2656 self.n = -1;
2657
2658 QCborValueRef result = findOrAddMapKey<KeyType>(self.container, key);
2659 assignContainer(self.container, result.d);
2660 return result;
2661}
2662
2663template<typename KeyType> QCborValueRef
2664QCborContainerPrivate::findOrAddMapKey(QCborValueRef self, KeyType key)
2665{
2666 auto &e = self.d->elements[self.i];
2667
2668 // we need a map, so convert if necessary
2669 if (e.type == QCborValue::Array) {
2670 convertArrayToMap(e.container);
2671 } else if (e.type != QCborValue::Map) {
2672 if (e.flags & QtCbor::Element::IsContainer)
2673 e.container->deref();
2674 e.container = nullptr;
2675 }
2677 e.type = QCborValue::Map;
2678
2679 QCborValueRef result = findOrAddMapKey<KeyType>(e.container, key);
2680 assignContainer(e.container, result.d);
2681 return result;
2682}
2683
2684/*!
2685 Returns a QCborValueRef that can be used to read or modify the entry in
2686 this, as a map, with the given \a key. When this QCborValue is a QCborMap,
2687 this function is equivalent to the matching operator[] on that map.
2688
2689 Before returning the reference: if this QCborValue was an array, it is first
2690 converted to a map (so that \c{map[i]} is \c{array[i]} for each index, \c i,
2691 with valid \c{array[i]}); otherwise, if it was not a map it will be
2692 over-written with an empty map.
2693
2694 \sa operator[](qint64), QCborMap::operator[], QCborMap::value(),
2695 QCborMap::find()
2696 */
2697QCborValueRef QCborValue::operator[](const QString &key)
2698{
2699 return QCborContainerPrivate::findOrAddMapKey(*this, qToStringViewIgnoringNull(key));
2700}
2701
2702/*!
2703 \overload
2704
2705 Returns a QCborValueRef that can be used to read or modify the entry in
2706 this, as a map, with the given \a key. When this QCborValue is a QCborMap,
2707 this function is equivalent to the matching operator[] on that map.
2708
2709 Before returning the reference: if this QCborValue was an array, it is first
2710 converted to a map (so that \c{map[i]} is \c{array[i]} for each index, \c i,
2711 with valid \c{array[i]}); otherwise, if it was not a map it will be
2712 over-written with an empty map.
2713
2714 \sa operator[](qint64), QCborMap::operator[], QCborMap::value(),
2715 QCborMap::find()
2716 */
2717QCborValueRef QCborValue::operator[](QLatin1StringView key)
2718{
2719 return QCborContainerPrivate::findOrAddMapKey(*this, key);
2720}
2721
2722/*!
2723 \overload
2724
2725 Returns a QCborValueRef that can be used to read or modify the entry in
2726 this, as a map or array, with the given \a key. When this QCborValue is a
2727 QCborMap or, for 0 <= key < 0x10000, a QCborArray, this function is
2728 equivalent to the matching operator[] on that map or array.
2729
2730 Before returning the reference: if this QCborValue was an array but the key
2731 is out of range, the array is first converted to a map (so that \c{map[i]}
2732 is \c{array[i]} for each index, \c i, with valid \c{array[i]}); otherwise,
2733 if it was not a map it will be over-written with an empty map.
2734
2735 \sa operator[], QCborMap::operator[], QCborMap::value(),
2736 QCborMap::find(), QCborArray::operator[], QCborArray::at()
2737 */
2738QCborValueRef QCborValue::operator[](qint64 key)
2739{
2740 if (shouldArrayRemainArray(key, t, container)) {
2741 container = maybeGrow(container, key);
2742 return { container, qsizetype(key) };
2743 }
2744 return QCborContainerPrivate::findOrAddMapKey(*this, key);
2745}
2746
2747#if QT_CONFIG(cborstreamreader)
2748/*!
2749 Decodes one item from the CBOR stream found in \a reader and returns the
2750 equivalent representation. This function is recursive: if the item is a map
2751 or array, it will decode all items found in that map or array, until the
2752 outermost object is finished.
2753
2754 This function need not be used on the root element of a \l
2755 QCborStreamReader. For example, the following code illustrates how to skip
2756 the CBOR signature tag from the beginning of a file:
2757
2758 \snippet code/src_corelib_serialization_qcborvalue.cpp 6
2759
2760 The returned value may be partially complete and indistinguishable from a
2761 valid QCborValue even if the decoding failed. To determine if there was an
2762 error, check if \l{QCborStreamReader::lastError()}{reader.lastError()} is
2763 indicating an error condition. This function stops decoding immediately
2764 after the first error.
2765
2766 \sa toCbor(), toDiagnosticNotation(), toVariant(), toJsonValue()
2767 */
2768QCborValue QCborValue::fromCbor(QCborStreamReader &reader)
2769{
2770 QCborValue result;
2771 auto t = reader.type();
2772 if (reader.lastError() != QCborError::NoError)
2773 t = QCborStreamReader::Invalid;
2774
2775 switch (t) {
2776 // basic types, no container needed:
2777 case QCborStreamReader::UnsignedInteger:
2778 case QCborStreamReader::NegativeInteger:
2779 case QCborStreamReader::SimpleType:
2780 case QCborStreamReader::Float16:
2781 case QCborStreamReader::Float:
2782 case QCborStreamReader::Double: {
2783 Element e = decodeBasicValueFromCbor(reader);
2784 result.n = e.value;
2785 result.t = e.type;
2786 break;
2787 }
2788
2789 case QCborStreamReader::Invalid:
2790 result.t = QCborValue::Invalid;
2791 break; // probably a decode error
2792
2793 // strings
2794 case QCborStreamReader::ByteArray:
2795 case QCborStreamReader::String:
2796 result.n = 0;
2797 result.t = reader.isString() ? String : ByteArray;
2798 result.container = new QCborContainerPrivate;
2799 result.container->ref.ref();
2800 result.container->decodeStringFromCbor(reader);
2801 break;
2802
2803 // containers
2804 case QCborStreamReader::Array:
2805 case QCborStreamReader::Map:
2806 result.n = -1;
2807 result.t = reader.isArray() ? Array : Map;
2808 result.container = createContainerFromCbor(reader, MaximumRecursionDepth);
2809 break;
2810
2811 // tag
2812 case QCborStreamReader::Tag:
2813 result = taggedValueFromCbor(reader, MaximumRecursionDepth);
2814 break;
2815 }
2816
2817 return result;
2818}
2819
2820/*!
2821 \overload
2822
2823 Decodes one item from the CBOR stream found in the byte array \a ba and
2824 returns the equivalent representation. This function is recursive: if the
2825 item is a map or array, it will decode all items found in that map or
2826 array, until the outermost object is finished.
2827
2828 This function stores the error state, if any, in the object pointed to by
2829 \a error, along with the offset of where the error occurred. If no error
2830 happened, it stores \l{QCborError}{NoError} in the error state and the
2831 number of bytes that it consumed (that is, it stores the offset for the
2832 first unused byte). Using that information makes it possible to parse
2833 further data that may exist in the same byte array.
2834
2835 The returned value may be partially complete and indistinguishable from a
2836 valid QCborValue even if the decoding failed. To determine if there was an
2837 error, check if there was an error stored in \a error. This function stops
2838 decoding immediately after the first error.
2839
2840 \sa toCbor(), toDiagnosticNotation(), toVariant(), toJsonValue()
2841 */
2842QCborValue QCborValue::fromCbor(const QByteArray &ba, QCborParserError *error)
2843{
2844 QCborStreamReader reader(ba);
2845 QCborValue result = fromCbor(reader);
2846 if (error) {
2847 error->error = reader.lastError();
2848 error->offset = reader.currentOffset();
2849 }
2850 return result;
2851}
2852
2853/*!
2854 \fn QCborValue QCborValue::fromCbor(const char *data, qsizetype len, QCborParserError *error)
2855 \fn QCborValue QCborValue::fromCbor(const quint8 *data, qsizetype len, QCborParserError *error)
2856 \overload
2857
2858 Converts \a len bytes of \a data to a QByteArray and then calls the
2859 overload of this function that accepts a QByteArray, also passing \a error,
2860 if provided.
2861*/
2862#endif // QT_CONFIG(cborstreamreader)
2863
2864#if QT_CONFIG(cborstreamwriter) && !defined(QT_BOOTSTRAPPED)
2865/*!
2866 Encodes this QCborValue object to its CBOR representation, using the
2867 options specified in \a opt, and return the byte array containing that
2868 representation.
2869
2870 This function will not fail, except if this QCborValue or any of the
2871 contained items, if this is a map or array, are invalid. Invalid types are
2872 not produced normally by the API, but can result from decoding errors.
2873
2874 By default, this function performs no transformation on the values in the
2875 QCborValue, writing all floating point directly as double-precision (\c
2876 double) types. If the \l{EncodingOption}{UseFloat} option is specified, it
2877 will use single precision (\c float) for any floating point value for which
2878 there's no loss of precision in using that representation. That includes
2879 infinities and NaN values.
2880
2881 Similarly, if \l{EncodingOption}{UseFloat16} is specified, this function
2882 will try to use half-precision (\c qfloat16) floating point if the
2883 conversion to that results in no loss of precision. This is always true for
2884 infinities and NaN.
2885
2886 If \l{EncodingOption}{UseIntegers} is specified, it will use integers for
2887 any floating point value that contains an actual integer.
2888
2889 \sa fromCbor(), fromVariant(), fromJsonValue()
2890 */
2891QByteArray QCborValue::toCbor(EncodingOptions opt) const
2892{
2893 QByteArray result;
2894 QCborStreamWriter writer(&result);
2895 toCbor(writer, opt);
2896 return result;
2897}
2898
2899/*!
2900 \overload
2901
2902 Encodes this QCborValue object to its CBOR representation, using the
2903 options specified in \a opt, to the writer specified by \a writer. The same
2904 writer can be used by multiple QCborValues, for example, in order to encode
2905 different elements in a larger array.
2906
2907 This function will not fail, except if this QCborValue or any of the
2908 contained items, if this is a map or array, are invalid. Invalid types are
2909 not produced normally by the API, but can result from decoding errors.
2910
2911 By default, this function performs no transformation on the values in the
2912 QCborValue, writing all floating point directly as double-precision
2913 (binary64) types. If the \l{EncodingOption}{UseFloat} option is
2914 specified, it will use single precision (binary32) for any floating point
2915 value for which there's no loss of precision in using that representation.
2916 That includes infinities and NaN values.
2917
2918 Similarly, if \l{EncodingOption}{UseFloat16} is specified, this function
2919 will try to use half-precision (binary16) floating point if the conversion
2920 to that results in no loss of precision. This is always true for infinities
2921 and NaN.
2922
2923 If \l{EncodingOption}{UseIntegers} is specified, it will use integers
2924 for any floating point value that contains an actual integer.
2925
2926 \sa fromCbor(), fromVariant(), fromJsonValue()
2927 */
2928Q_NEVER_INLINE void QCborValue::toCbor(QCborStreamWriter &writer, EncodingOptions opt) const
2929{
2930 if (isContainer() || isTag())
2931 return encodeToCbor(writer, container, -type(), opt);
2932 if (container)
2933 return encodeToCbor(writer, container, n, opt);
2934
2935 // very simple types
2936 if (isSimpleType())
2937 return writer.append(toSimpleType());
2938
2939 switch (type()) {
2940 case Integer:
2941 return writer.append(n);
2942
2943 case Double:
2944 return writeDoubleToCbor(writer, fp_helper(), opt);
2945
2946 case Invalid:
2947 return;
2948
2949 case SimpleType:
2950 case False:
2951 case True:
2952 case Null:
2953 case Undefined:
2954 // handled by "if (isSimpleType())"
2955 Q_UNREACHABLE();
2956 break;
2957
2958 case ByteArray:
2959 // Byte array with no container is empty
2960 return writer.appendByteString("", 0);
2961
2962 case String:
2963 // String with no container is empty
2964 return writer.appendTextString("", 0);
2965
2966 case Array:
2967 case Map:
2968 case Tag:
2969 // handled by "if (isContainer() || isTag())"
2970 Q_UNREACHABLE();
2971 break;
2972
2973 case DateTime:
2974 case Url:
2975 case RegularExpression:
2976 case Uuid:
2977 // not possible
2978 Q_UNREACHABLE();
2979 break;
2980 }
2981}
2982
2983# if QT_VERSION < QT_VERSION_CHECK(7, 0, 0)
2984void QCborValueRef::toCbor(QCborStreamWriter &writer, QCborValue::EncodingOptions opt)
2985{
2986 concrete().toCbor(writer, opt);
2987}
2988# endif
2989#endif // QT_CONFIG(cborstreamwriter) && !QT_BOOTSTRAPPED
2990
2991void QCborValueRef::assign(QCborValueRef that, const QCborValue &other)
2992{
2993 that.d->replaceAt(that.i, other);
2994}
2995
2996void QCborValueRef::assign(QCborValueRef that, QCborValue &&other)
2997{
2998 that.d->replaceAt(that.i, other, QCborContainerPrivate::MoveContainer);
2999}
3000
3001void QCborValueRef::assign(QCborValueRef that, const QCborValueRef other)
3002{
3003 // ### optimize?
3004 that = other.concrete();
3005}
3006
3007bool QCborValueConstRef::concreteBoolean(QCborValueConstRef self, bool defaultValue) noexcept
3008{
3009 QtCbor::Element e = self.d->elements.at(self.i);
3010 if (e.type != QCborValue::False && e.type != QCborValue::True)
3011 return defaultValue;
3012 return e.type == QCborValue::True;
3013}
3014
3015double QCborValueConstRef::concreteDouble(QCborValueConstRef self, double defaultValue) noexcept
3016{
3017 QtCbor::Element e = self.d->elements.at(self.i);
3018 if (e.type == QCborValue::Integer)
3019 return e.value;
3020 if (e.type != QCborValue::Double)
3021 return defaultValue;
3022 return e.fpvalue();
3023}
3024
3025qint64 QCborValueConstRef::concreteIntegral(QCborValueConstRef self, qint64 defaultValue) noexcept
3026{
3027 QtCbor::Element e = self.d->elements.at(self.i);
3028 QCborValue::Type t = e.type;
3029 if (t == QCborValue::Double)
3030 return e.fpvalue();
3031 if (t != QCborValue::Integer)
3032 return defaultValue;
3033 return e.value;
3034}
3035
3037 const QByteArray &defaultValue)
3038{
3039 QtCbor::Element e = self.d->elements.at(self.i);
3040 if (e.type != QCborValue::ByteArray)
3041 return defaultValue;
3042 return self.d->byteArrayAt(self.i);
3043}
3044
3045QString QCborValueConstRef::concreteString(QCborValueConstRef self, const QString &defaultValue)
3046{
3047 QtCbor::Element e = self.d->elements.at(self.i);
3048 if (e.type != QCborValue::String)
3049 return defaultValue;
3050 return self.d->stringAt(self.i);
3051}
3052
3053QAnyStringView QCborValueConstRef::concreteStringView(QCborValueConstRef self, QAnyStringView defaultValue)
3054{
3055 QtCbor::Element e = self.d->elements.at(self.i);
3056 if (e.type != QCborValue::String)
3057 return defaultValue;
3058 return self.d->anyStringViewAt(self.i);
3059}
3060
3061bool
3062QCborValueConstRef::comparesEqual_helper(QCborValueConstRef lhs, QCborValueConstRef rhs) noexcept
3063{
3064 QtCbor::Element e1 = lhs.d->elements.at(lhs.i);
3065 QtCbor::Element e2 = rhs.d->elements.at(rhs.i);
3067}
3068
3069Qt::strong_ordering
3070QCborValueConstRef::compareThreeWay_helper(QCborValueConstRef lhs, QCborValueConstRef rhs) noexcept
3071{
3072 QtCbor::Element e1 = lhs.d->elements.at(lhs.i);
3073 QtCbor::Element e2 = rhs.d->elements.at(rhs.i);
3075 return Qt::compareThreeWay(c, 0);
3076}
3077
3078bool
3079QCborValueConstRef::comparesEqual_helper(QCborValueConstRef lhs, const QCborValue &rhs) noexcept
3080{
3081 QtCbor::Element e1 = lhs.d->elements.at(lhs.i);
3082 QtCbor::Element e2 = QCborContainerPrivate::elementFromValue(rhs);
3083 return compareElementRecursive(lhs.d, e1, rhs.container, e2, Comparison::ForEquality) == 0;
3084}
3085
3086Qt::strong_ordering
3087QCborValueConstRef::compareThreeWay_helper(QCborValueConstRef lhs, const QCborValue &rhs) noexcept
3088{
3089 QtCbor::Element e1 = lhs.d->elements.at(lhs.i);
3090 QtCbor::Element e2 = QCborContainerPrivate::elementFromValue(rhs);
3091 int c = compareElementRecursive(lhs.d, e1, rhs.container, e2, Comparison::ForOrdering);
3092 return Qt::compareThreeWay(c, 0);
3093}
3094
3095bool QCborArray::comparesEqual_helper(const QCborArray &lhs, QCborValueConstRef rhs) noexcept
3096{
3097 QtCbor::Element e2 = rhs.d->elements.at(rhs.i);
3098 if (typeOrder(QCborValue::Array, e2.type))
3099 return false;
3100 return compareContainer(lhs.d.constData(), e2.container, Comparison::ForEquality) == 0;
3101}
3102
3103Qt::strong_ordering
3104QCborArray::compareThreeWay_helper(const QCborArray &lhs, QCborValueConstRef rhs) noexcept
3105{
3106 QtCbor::Element e2 = rhs.d->elements.at(rhs.i);
3107 int c = typeOrder(QCborValue::Array, e2.type);
3108 if (c == 0)
3109 c = compareContainer(lhs.d.constData(), e2.container, Comparison::ForOrdering);
3110 return Qt::compareThreeWay(c, 0);
3111}
3112
3113bool QCborMap::comparesEqual_helper(const QCborMap &lhs, QCborValueConstRef rhs) noexcept
3114{
3115 QtCbor::Element e2 = rhs.d->elements.at(rhs.i);
3116 if (typeOrder(QCborValue::Array, e2.type))
3117 return false;
3118 return compareContainer(lhs.d.constData(), e2.container, Comparison::ForEquality) == 0;
3119}
3120
3121Qt::strong_ordering
3122QCborMap::compareThreeWay_helper(const QCborMap &lhs, QCborValueConstRef rhs) noexcept
3123{
3124 QtCbor::Element e2 = rhs.d->elements.at(rhs.i);
3125 int c = typeOrder(QCborValue::Map, e2.type);
3126 if (c == 0)
3127 c = compareContainer(lhs.d.constData(), e2.container, Comparison::ForOrdering);
3128 return Qt::compareThreeWay(c, 0);
3129}
3130
3131QCborValue QCborValueConstRef::concrete(QCborValueConstRef self) noexcept
3132{
3133 return self.d->valueAt(self.i);
3134}
3135
3136QCborValue::Type QCborValueConstRef::concreteType(QCborValueConstRef self) noexcept
3137{
3138 return self.d->elements.at(self.i).type;
3139}
3140
3141const QCborValue QCborValueConstRef::operator[](const QString &key) const
3142{
3143 const QCborValue item = d->valueAt(i);
3144 return item[key];
3145}
3146
3147const QCborValue QCborValueConstRef::operator[](const QLatin1StringView key) const
3148{
3149 const QCborValue item = d->valueAt(i);
3150 return item[key];
3151}
3152
3153const QCborValue QCborValueConstRef::operator[](qint64 key) const
3154{
3155 const QCborValue item = d->valueAt(i);
3156 return item[key];
3157}
3158
3159#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0) && !defined(QT_BOOTSTRAPPED)
3160QCborValue QCborValueRef::concrete(QCborValueRef self) noexcept
3161{
3162 return self.d->valueAt(self.i);
3163}
3164
3165QCborValue::Type QCborValueRef::concreteType(QCborValueRef self) noexcept
3166{
3167 return self.d->elements.at(self.i).type;
3168}
3169
3170/*!
3171 If this QCborValueRef refers to a QCborMap, searches elements for the value
3172 whose key matches \a key. If there's no key matching \a key in the map or if
3173 this QCborValueRef object is not a map, returns the undefined value.
3174
3175 This function is equivalent to:
3176
3177 \code
3178 value.toMap().value(key);
3179 \endcode
3180
3181 \sa operator[](qint64), QCborMap::operator[], QCborMap::value(),
3182 QCborMap::find()
3183 */
3184const QCborValue QCborValueRef::operator[](const QString &key) const
3185{
3186 return QCborValueConstRef::operator[](key);
3187}
3188
3189/*!
3190 \overload
3191
3192 If this QCborValueRef refers to a QCborMap, searches elements for the value
3193 whose key matches \a key. If there's no key matching \a key in the map or if
3194 this QCborValueRef object is not a map, returns the undefined value.
3195
3196 This function is equivalent to:
3197
3198 \code
3199 value.toMap().value(key);
3200 \endcode
3201
3202 \sa operator[](qint64), QCborMap::operator[], QCborMap::value(),
3203 QCborMap::find()
3204 */
3205const QCborValue QCborValueRef::operator[](QLatin1StringView key) const
3206{
3207 return QCborValueConstRef::operator[](key);
3208}
3209
3210/*!
3211 \overload
3212
3213 If this QCborValueRef refers to a QCborMap, searches elements for the value
3214 whose key matches \a key. If this is a QCborArray, returns the element whose
3215 index is \a key. If there's no matching value in the array or map, or if
3216 this QCborValueRef object is not an array or map, returns the undefined
3217 value.
3218
3219 \sa operator[], QCborMap::operator[], QCborMap::value(),
3220 QCborMap::find(), QCborArray::operator[], QCborArray::at()
3221 */
3222const QCborValue QCborValueRef::operator[](qint64 key) const
3223{
3224 return QCborValueConstRef::operator[](key);
3225}
3226
3227/*!
3228 Returns a QCborValueRef that can be used to read or modify the entry in
3229 this, as a map, with the given \a key. When this QCborValueRef refers to a
3230 QCborMap, this function is equivalent to the matching operator[] on that
3231 map.
3232
3233 Before returning the reference: if the QCborValue referenced was an array,
3234 it is first converted to a map (so that \c{map[i]} is \c{array[i]} for each
3235 index, \c i, with valid \c{array[i]}); otherwise, if it was not a map it
3236 will be over-written with an empty map.
3237
3238 \sa operator[](qint64), QCborMap::operator[], QCborMap::value(),
3239 QCborMap::find()
3240 */
3241QCborValueRef QCborValueRef::operator[](const QString &key)
3242{
3243 return QCborContainerPrivate::findOrAddMapKey(*this, qToStringViewIgnoringNull(key));
3244}
3245
3246/*!
3247 \overload
3248
3249 Returns a QCborValueRef that can be used to read or modify the entry in
3250 this, as a map, with the given \a key. When this QCborValue is a QCborMap,
3251 this function is equivalent to the matching operator[] on that map.
3252
3253 Before returning the reference: if the QCborValue referenced was an array,
3254 it is first converted to a map (so that \c{map[i]} is \c{array[i]} for each
3255 index, \c i, with valid \c{array[i]}); otherwise, if it was not a map it
3256 will be over-written with an empty map.
3257
3258 \sa operator[](qint64), QCborMap::operator[], QCborMap::value(),
3259 QCborMap::find()
3260 */
3261QCborValueRef QCborValueRef::operator[](QLatin1StringView key)
3262{
3263 return QCborContainerPrivate::findOrAddMapKey(*this, key);
3264}
3265
3266/*!
3267 \overload
3268
3269 Returns a QCborValueRef that can be used to read or modify the entry in
3270 this, as a map or array, with the given \a key. When this QCborValue is a
3271 QCborMap or, for 0 <= key < 0x10000, a QCborArray, this function is
3272 equivalent to the matching operator[] on that map or array.
3273
3274 Before returning the reference: if the QCborValue referenced was an array
3275 but the key is out of range, the array is first converted to a map (so that
3276 \c{map[i]} is \c{array[i]} for each index, \c i, with valid \c{array[i]});
3277 otherwise, if it was not a map it will be over-written with an empty map.
3278
3279 \sa operator[], QCborMap::operator[], QCborMap::value(),
3280 QCborMap::find(), QCborArray::operator[], QCborArray::at()
3281 */
3282QCborValueRef QCborValueRef::operator[](qint64 key)
3283{
3284 auto &e = d->elements[i];
3285 if (shouldArrayRemainArray(key, e.type, e.container)) {
3286 e.container = maybeGrow(e.container, key);
3287 e.flags |= QtCbor::Element::IsContainer;
3288 return { e.container, qsizetype(key) };
3289 }
3290 return QCborContainerPrivate::findOrAddMapKey(*this, key);
3291}
3292#endif // < Qt 7
3293
3294inline QCborArray::QCborArray(QCborContainerPrivate &dd) noexcept
3295 : d(&dd)
3296{
3297}
3298
3299inline QCborMap::QCborMap(QCborContainerPrivate &dd) noexcept
3300 : d(&dd)
3301{
3302}
3303
3304size_t qHash(const QCborValue &value, size_t seed)
3305{
3306 switch (value.type()) {
3307 case QCborValue::Integer:
3308 return qHash(value.toInteger(), seed);
3309 case QCborValue::ByteArray:
3310 return qHash(value.toByteArray(), seed);
3311 case QCborValue::String:
3312 return qHash(value.toString(), seed);
3313 case QCborValue::Array:
3314 return qHash(value.toArray(), seed);
3315 case QCborValue::Map:
3316 return qHash(value.toMap(), seed);
3317 case QCborValue::Tag:
3318 return qHashMulti(seed, value.tag(), value.taggedValue());
3319 case QCborValue::SimpleType:
3320 break;
3321 case QCborValue::False:
3322 return qHash(false, seed);
3323 case QCborValue::True:
3324 return qHash(true, seed);
3325 case QCborValue::Null:
3326 return qHash(nullptr, seed);
3327 case QCborValue::Undefined:
3328 return seed;
3329 case QCborValue::Double:
3330 return qHash(value.toDouble(), seed);
3331#if QT_CONFIG(datestring)
3332 case QCborValue::DateTime:
3333 return qHash(value.toDateTime(), seed);
3334#endif
3335#ifndef QT_BOOTSTRAPPED
3336 case QCborValue::Url:
3337 return qHash(value.toUrl(), seed);
3338# if QT_CONFIG(regularexpression)
3339 case QCborValue::RegularExpression:
3340 return qHash(value.toRegularExpression(), seed);
3341# endif
3342 case QCborValue::Uuid:
3343 return qHash(value.toUuid(), seed);
3344#endif
3345 case QCborValue::Invalid:
3346 return seed;
3347 default:
3348 break;
3349 }
3350
3351 Q_ASSERT(value.isSimpleType());
3352 return qHash(value.toSimpleType(), seed);
3353}
3354
3355Q_CORE_EXPORT const char *qt_cbor_simpletype_id(QCborSimpleType st)
3356{
3357 switch (st) {
3358 case QCborSimpleType::False:
3359 return "False";
3360 case QCborSimpleType::True:
3361 return "True";
3362 case QCborSimpleType::Null:
3363 return "Null";
3364 case QCborSimpleType::Undefined:
3365 return "Undefined";
3366 }
3367 return nullptr;
3368}
3369
3370Q_CORE_EXPORT const char *qt_cbor_tag_id(QCborTag tag)
3371{
3372 // Casting to QCborKnownTags's underlying type will make the comparison
3373 // below fail if the tag value is out of range.
3374 auto n = std::underlying_type<QCborKnownTags>::type(tag);
3375 if (QCborTag(n) == tag) {
3376 switch (QCborKnownTags(n)) {
3377 case QCborKnownTags::DateTimeString:
3378 return "DateTimeString";
3379 case QCborKnownTags::UnixTime_t:
3380 return "UnixTime_t";
3381 case QCborKnownTags::PositiveBignum:
3382 return "PositiveBignum";
3383 case QCborKnownTags::NegativeBignum:
3384 return "NegativeBignum";
3385 case QCborKnownTags::Decimal:
3386 return "Decimal";
3387 case QCborKnownTags::Bigfloat:
3388 return "Bigfloat";
3389 case QCborKnownTags::COSE_Encrypt0:
3390 return "COSE_Encrypt0";
3391 case QCborKnownTags::COSE_Mac0:
3392 return "COSE_Mac0";
3393 case QCborKnownTags::COSE_Sign1:
3394 return "COSE_Sign1";
3395 case QCborKnownTags::ExpectedBase64url:
3396 return "ExpectedBase64url";
3397 case QCborKnownTags::ExpectedBase64:
3398 return "ExpectedBase64";
3399 case QCborKnownTags::ExpectedBase16:
3400 return "ExpectedBase16";
3401 case QCborKnownTags::EncodedCbor:
3402 return "EncodedCbor";
3403 case QCborKnownTags::Url:
3404 return "Url";
3405 case QCborKnownTags::Base64url:
3406 return "Base64url";
3407 case QCborKnownTags::Base64:
3408 return "Base64";
3409 case QCborKnownTags::RegularExpression:
3410 return "RegularExpression";
3411 case QCborKnownTags::MimeMessage:
3412 return "MimeMessage";
3413 case QCborKnownTags::Uuid:
3414 return "Uuid";
3415 case QCborKnownTags::COSE_Encrypt:
3416 return "COSE_Encrypt";
3417 case QCborKnownTags::COSE_Mac:
3418 return "COSE_Mac";
3419 case QCborKnownTags::COSE_Sign:
3420 return "COSE_Sign";
3421 case QCborKnownTags::Signature:
3422 return "Signature";
3423 }
3424 }
3425 return nullptr;
3426}
3427
3428#if !defined(QT_NO_DEBUG_STREAM)
3429static QDebug debugContents(QDebug &dbg, const QCborValue &v)
3430{
3431 switch (v.type()) {
3432 case QCborValue::Integer:
3433 return dbg << v.toInteger();
3434 case QCborValue::ByteArray:
3435 return dbg << "QByteArray(" << v.toByteArray() << ')';
3436 case QCborValue::String:
3437 return dbg << v.toString();
3438 case QCborValue::Array:
3439 return dbg << v.toArray();
3440 case QCborValue::Map:
3441 return dbg << v.toMap();
3442 case QCborValue::Tag: {
3443 QCborTag tag = v.tag();
3444 const char *id = qt_cbor_tag_id(tag);
3445 if (id)
3446 dbg.nospace() << "QCborKnownTags::" << id << ", ";
3447 else
3448 dbg.nospace() << "QCborTag(" << quint64(tag) << "), ";
3449 return dbg << v.taggedValue();
3450 }
3451 case QCborValue::SimpleType:
3452 break;
3453 case QCborValue::True:
3454 return dbg << true;
3455 case QCborValue::False:
3456 return dbg << false;
3457 case QCborValue::Null:
3458 return dbg << "nullptr";
3459 case QCborValue::Undefined:
3460 return dbg;
3461 case QCborValue::Double: {
3462 qint64 i;
3463 if (convertDoubleTo(v.toDouble(), &i))
3464 return dbg << i << ".0";
3465 else
3466 return dbg << v.toDouble();
3467 }
3468#if QT_CONFIG(datestring)
3469 case QCborValue::DateTime:
3470 return dbg << v.toDateTime();
3471#endif
3472#ifndef QT_BOOTSTRAPPED
3473 case QCborValue::Url:
3474 return dbg << v.toUrl();
3475#if QT_CONFIG(regularexpression)
3476 case QCborValue::RegularExpression:
3477 return dbg << v.toRegularExpression();
3478#endif
3479 case QCborValue::Uuid:
3480 return dbg << v.toUuid();
3481#endif
3482 case QCborValue::Invalid:
3483 return dbg << "<invalid>";
3484 default:
3485 break;
3486 }
3487 if (v.isSimpleType())
3488 return dbg << v.toSimpleType();
3489 return dbg << "<unknown type 0x" << Qt::hex << int(v.type()) << Qt::dec << '>';
3490}
3491QDebug operator<<(QDebug dbg, const QCborValue &v)
3492{
3493 QDebugStateSaver saver(dbg);
3494 dbg.nospace() << "QCborValue(";
3495 return debugContents(dbg, v) << ')';
3496}
3497
3498QDebug operator<<(QDebug dbg, QCborSimpleType st)
3499{
3500 QDebugStateSaver saver(dbg);
3501 const char *id = qt_cbor_simpletype_id(st);
3502 if (id)
3503 return dbg.nospace() << "QCborSimpleType::" << id;
3504
3505 return dbg.nospace() << "QCborSimpleType(" << uint(st) << ')';
3506}
3507
3508QDebug operator<<(QDebug dbg, QCborTag tag)
3509{
3510 QDebugStateSaver saver(dbg);
3511 const char *id = qt_cbor_tag_id(tag);
3512 dbg.nospace() << "QCborTag(";
3513 if (id)
3514 dbg.nospace() << "QCborKnownTags::" << id;
3515 else
3516 dbg.nospace() << quint64(tag);
3517
3518 return dbg << ')';
3519}
3520
3521QDebug operator<<(QDebug dbg, QCborKnownTags tag)
3522{
3523 QDebugStateSaver saver(dbg);
3524 const char *id = qt_cbor_tag_id(QCborTag(int(tag)));
3525 if (id)
3526 return dbg.nospace() << "QCborKnownTags::" << id;
3527
3528 return dbg.nospace() << "QCborKnownTags(" << int(tag) << ')';
3529}
3530
3531QDebug operator<<(QDebug d, QCborError err)
3532{
3533 // Use the Q_GADGET QMetaEnum extraction
3534 return d << err.c;
3535}
3536#endif
3537
3538#ifndef QT_NO_DATASTREAM
3539#if QT_CONFIG(cborstreamwriter)
3540QDataStream &operator<<(QDataStream &stream, const QCborValue &value)
3541{
3542 stream << QCborValue(value).toCbor();
3543 return stream;
3544}
3545#endif
3546
3547#if QT_CONFIG(cborstreamreader)
3548QDataStream &operator>>(QDataStream &stream, QCborValue &value)
3549{
3550 QByteArray buffer;
3551 stream >> buffer;
3552 QCborParserError parseError{};
3553 value = QCborValue::fromCbor(buffer, &parseError);
3554 if (parseError.error)
3555 stream.setStatus(QDataStream::ReadCorruptData);
3556 return stream;
3557}
3558#endif
3559#endif // QT_NO_DATASTREAM
3560
3561
3562QT_END_NAMESPACE
3563
3564#include "qcborarray.cpp"
3565#include "qcbormap.cpp"
3566
3567#ifndef QT_NO_QOBJECT
3568#include "moc_qcborvalue.cpp"
3569#endif
const QtCbor::ByteData * byteData(QtCbor::Element e) const
static int compareElement_helper(const QCborContainerPrivate *c1, QtCbor::Element e1, const QCborContainerPrivate *c2, QtCbor::Element e2, QtCbor::Comparison mode) noexcept
QCborContainerPrivate(const QCborContainerPrivate &)=default
static QCborValueRef findOrAddMapKey(QCborValueRef self, KeyType key)
void appendAsciiString(QStringView s)
void appendNonAsciiString(QStringView s)
void append(QtCbor::Undefined)
QCborValue extractAt_complex(QtCbor::Element e)
void replaceAt_complex(QtCbor::Element &e, const QCborValue &value, ContainerDisposition disp)
QCborContainerPrivate * d
Definition qcborvalue.h:464
Combined button and popup list for selecting options.
static int typeOrder(QCborValue::Type e1, QCborValue::Type e2)
static Q_DECL_UNUSED constexpr int MaximumRecursionDepth
Q_CORE_EXPORT const char * qt_cbor_simpletype_id(QCborSimpleType st)
void qt_to_latin1_unchecked(uchar *dst, const char16_t *uc, qsizetype len)
Definition qstring.cpp:1165
static int compareStringsInUtf8(QStringView lhs, QStringView rhs, Comparison mode) noexcept
static bool shouldArrayRemainArray(qint64 key, QCborValue::Type t, QCborContainerPrivate *container)
static auto nextUtf32Character(const char16_t *&ptr, const char16_t *end) noexcept
static int compareContainer(const QCborContainerPrivate *c1, const QCborContainerPrivate *c2, Comparison mode) noexcept
static QCborContainerPrivate * assignContainer(QCborContainerPrivate *&d, QCborContainerPrivate *x)
static qsizetype stringLengthInUtf8(const char16_t *ptr, const char16_t *end) noexcept
static QCborValue::Type convertToExtendedType(QCborContainerPrivate *d)
static QCborValue::Type setToExtendedDateTimeType(QCborContainerPrivate *d, QStringView dtString)
Q_CORE_EXPORT const char * qt_cbor_tag_id(QCborTag tag)
bool comparesEqual(const QCborArray &lhs, const QCborArray &rhs) noexcept
static QCborContainerPrivate * maybeGrow(QCborContainerPrivate *container, qsizetype index)
static QDebug debugContents(QDebug &dbg, const QCborValue &v)
static int compareElementRecursive(const QCborContainerPrivate *c1, const Element &e1, const QCborContainerPrivate *c2, const Element &e2, Comparison mode) noexcept
static void convertArrayToMap(QCborContainerPrivate *&array)
bool comparesEqual(const QCborMap &lhs, const QCborMap &rhs) noexcept
static int compareElementNoData(const Element &e1, const Element &e2) noexcept
QDebug operator<<(QDebug debug, QDir::Filters filters)
Definition qdir.cpp:2620
QDebug operator<<(QDebug dbg, const QFileInfo &fi)
bool comparesEqual(const QFileInfo &lhs, const QFileInfo &rhs)
constexpr size_t qHash(const QSize &s, size_t seed=0) noexcept
Definition qsize.h:192
const char * byte() const
double fpvalue() const