PySide6.QtCore.QCborStreamWriter¶
- class QCborStreamWriter¶
- The - QCborStreamWriterclass is a simple CBOR encoder operating on a one-way stream. More…- Synopsis¶- Methods¶- def - __init__()
- def - append()
- def - appendNull()
- def - device()
- def - endArray()
- def - endMap()
- def - setDevice()
- def - startArray()
- def - startMap()
 - Note - This documentation may contain snippets that were automatically translated from C++ to Python. We always welcome contributions to the snippet translation. If you see an issue with the translation, you can also let us know by creating a ticket on https:/bugreports.qt.io/projects/PYSIDE - Detailed Description¶- Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - This class can be used to quickly encode a stream of CBOR content directly to either a - QByteArrayor- QIODevice. CBOR is the Concise Binary Object Representation, a very compact form of binary data encoding that is compatible with JSON. It was created by the IETF Constrained RESTful Environments (CoRE) WG, which has used it in many new RFCs. It is meant to be used alongside the CoAP protocol.- QCborStreamWriterprovides a StAX-like API, similar to that of- QXmlStreamWriter. It is rather low-level and requires a bit of knowledge of CBOR encoding. For a simpler API, see- QCborValueand especially the encoding function- toCbor().- The typical use of - QCborStreamWriteris to create the object on the target- QByteArrayor- QIODevice, then call one of the- append()overloads with the desired type to be encoded. To create arrays and maps,- QCborStreamWriterprovides- startArray()and- startMap()overloads, which must be terminated by the corresponding- endArray()and- endMap()functions.- The following example encodes the equivalent of this JSON content: - { “label”: “journald”, “autoDetect”: false, “condition”: “libs.journald”, “output”: [ “privateFeature” ] } - writer.startMap(4) # 4 elements in the map writer.append("label") writer.append("journald") writer.append("autoDetect") writer.append(False) writer.append("condition") writer.append("libs.journald") writer.append("output") writer.startArray(1) writer.append("privateFeature") writer.endArray() writer.endMap() - CBOR support¶- QCborStreamWritersupports all CBOR features required to create canonical and strict streams. It implements almost all of the features specified in RFC 7049.- The following table lists the CBOR features that - QCborStreamWritersupports.- Feature - Support - Unsigned numbers - Yes (full range) - Negative numbers - Yes (full range) - Byte strings - Yes - Text strings - Yes - Chunked strings - No - Tags - Yes (arbitrary) - Booleans - Yes - Null - Yes - Undefined - Yes - Arbitrary simple values - Yes - Half-precision float (16-bit) - Yes - Single-precision float (32-bit) - Yes - Double-precision float (64-bit) - Yes - Infinities and NaN floating point - Yes - Determinate-length arrays and maps - Yes - Indeterminate-length arrays and maps - Yes - Map key types other than strings and integers - Yes (arbitrary) - Canonical CBOR encoding¶- Canonical CBOR encoding is defined by Section 3.9 of RFC 7049. Canonical encoding is not a requirement for Qt’s CBOR decoding functionality, but it may be required for some protocols. In particular, protocols that require the ability to reproduce the same stream identically may require this. - In order to be considered “canonical”, a CBOR stream must meet the following requirements: - Integers must be as small as possible. - QCborStreamWriteralways does this (no user action is required and it is not possible to write overlong integers).
- Array, map and string lengths must be as short as possible. As above, - QCborStreamWriterautomatically does this.
- Arrays, maps and strings must use explicit length. - QCborStreamWriteralways does this for strings; for arrays and maps, be sure to call- startArray()and- startMap()overloads with explicit length.
- Keys in every map must be sorted in ascending order. - QCborStreamWriteroffers no help in this item: the developer must ensure that before calling- append()for the map pairs.
- Floating point values should be as small as possible. - QCborStreamWriterwill not convert floating point values; it is up to the developer to perform this check prior to calling- append()(see those functions’ examples).
 - Strict CBOR mode¶- Strict mode is defined by Section 3.10 of RFC 7049. As for Canonical encoding above, - QCborStreamWritermakes it possible to create strict CBOR streams, but does not require them or validate that the output is so.- Keys in a map must be unique. - QCborStreamWriterperforms no validation of map keys.
- Tags may be required to be paired only with the correct types, according to their specification. - QCborStreamWriterperforms no validation of tag usage.
- Text Strings must be properly-encoded UTF-8. - QCborStreamWriteralways writes proper UTF-8 for strings added with- append(), but performs no validation for strings added with- appendTextString().
 - Invalid CBOR stream¶- It is also possible to misuse - QCborStreamWriterand produce invalid CBOR streams that will fail to be decoded by a receiver. The following actions will produce invalid streams:- Append a tag and not append the corresponding tagged value ( - QCborStreamWriterproduces no diagnostic).
- Append too many or too few items to an array or map with explicit length ( - endMap()and- endArray()will return false and- QCborStreamWriterwill log with- qWarning()).
 - {Parsing and displaying CBOR data}, {Serialization Converter}, {Saving and Loading a Game} - See also - __init__(data)¶
- Parameters:
- data – - QByteArray
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - Creates a - QCborStreamWriterobject that will append the stream to- data. All streaming is done immediately to the byte array, without the need for flushing any buffers.- The following example writes a number to a byte array then returns it. - def encodedNumber(value): ba = QByteArray() writer = QCborStreamWriter(ba) writer.append(value) return ba - QCborStreamWriterdoes not take ownership of- data.- __init__(device)
- Parameters:
- device – - QIODevice
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - Creates a - QCborStreamWriterobject that will write the stream to- device. The device must be opened before the first- append()call is made. This constructor can be used with any class that derives from- QIODevice, such as- QFile,- QProcessor QTcpSocket.- QCborStreamWriterhas no buffering, so every- append()call will result in one or more calls to the device’s- write()method.- The following example writes an empty map to a file: - f = QFile("output", QIODevice.WriteOnly) writer = QCborStreamWriter(f) writer.startMap(0) writer.endMap() - QCborStreamWriterdoes not take ownership of- device.- See also - append(tag)¶
- Parameters:
- tag – - QCborKnownTags
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - This is an overloaded function. - Appends the CBOR tag - tagto the stream, creating a CBOR Tag value. All tags must be followed by another type which they provide meaning for.- In the following example, we append a CBOR Tag 1 (Unix - time_t) and an integer representing the current time to the stream, obtained using the- time()function:- append(st)
- Parameters:
- st – - QCborSimpleType
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - This is an overloaded function. - Appends the CBOR simple type - stto the stream, creating a CBOR Simple Type value. In the following example, we write the simple type for Null as well as for type 32, which Qt has no support for.- writer.append(QCborSimpleType.Null) writer.append(QCborSimpleType(32)) - Note - Using Simple Types for which there is no specification can lead to validation errors by the remote receiver. In addition, simple type values 24 through 31 (inclusive) are reserved and must not be used. - See also - append(tag)
- Parameters:
- tag – - QCborTag
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - This is an overloaded function. - Appends the CBOR tag - tagto the stream, creating a CBOR Tag value. All tags must be followed by another type which they provide meaning for.- In the following example, we append a CBOR Tag 36 (Regular Expression) and a - QRegularExpression‘s pattern to the stream:- append(str)
- Parameters:
- str – - QLatin1String
 
 - append(str)
- Parameters:
- str – str 
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - This is an overloaded function. - Appends the text string - strto the stream, creating a CBOR Text String value.- QCborStreamWriterwill attempt to write the entire string in one chunk.- The following example writes an arbitrary - QStringto the stream:- def writeString(writer, str): writer.append(str) - See also - append(b)
- Parameters:
- b – bool 
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - This is an overloaded function. - Appends the boolean value - bto the stream, creating either a CBOR False value or a CBOR True value. This function is equivalent to (and implemented as):- writer.append(b if QCborSimpleType.True else QCborSimpleType.False) - See also - append(ba)
- Parameters:
- ba – - QByteArray
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - This is an overloaded function. - Appends the byte array - bato the stream, creating a CBOR Byte String value.- QCborStreamWriterwill attempt to write the entire string in one chunk.- The following example will load and append the contents of a file to the stream: - def writeFile(writer, fileName): f = QFile(fileName) if f.open(QIODevice.ReadOnly): writer.append(f.readAll()) - As the example shows, unlike JSON, CBOR requires no escaping for binary content. - append(d)
- Parameters:
- d – float 
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - This is an overloaded function. - Appends the floating point number - dto the stream, creating a CBOR 64-bit Double-Precision Floating Point value.- QCborStreamWriteralways appends the number as-is, performing no check for whether the number is the canonical form for NaN, an infinite, whether it is denormal or if it could be written with a shorter format.- The following code performs all those checks, except for the denormal one, which is expected to be taken into account by the system FPU or floating point emulation directly. - def writeDouble(writer, d): f = float() if qIsNaN(d): writer.append(qfloat16(qQNaN())) elif qIsInf(d): writer.append(d < 0 if -qInf() else qInf()) elif (f = d) == d: f16 = f if f16 == f: writer.append(f16) else: writer.append(f) else: writer.append(d) - Determining if a double can be converted to an integral with no loss of precision is left as an exercise to the reader. - See also - append(f)
- Parameters:
- f – float 
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - This is an overloaded function. - Appends the floating point number - fto the stream, creating a CBOR 32-bit Single-Precision Floating Point value. The following code can be used to convert a C++- doubleto- floatif there’s no loss of precision and append it, or instead append the- double.- append(i)
- Parameters:
- i – int 
 
 - append(i)
- Parameters:
- i – int 
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - This is an overloaded function. - Appends the 64-bit signed value - ito the CBOR stream. This will create either a CBOR Unsigned Integer or CBOR NegativeInteger value based on the sign of the parameter. In the following example, we write the values 0, -1, 2 32 and- INT64_MAX:- writer.append(0) writer.append(-1) writer.append(Q_INT64_C(4294967296)) writer.append(std.numeric_limits<qint64>.max()) - See also - append(u)
- Parameters:
- u – int 
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - This is an overloaded function. - Appends the 64-bit unsigned value - uto the CBOR stream, creating a CBOR Unsigned Integer value. In the following example, we write the values 0, 2 32 and- UINT64_MAX:- writer.append(0U) writer.append(Q_UINT64_C(4294967296)) writer.append(std.numeric_limits<quint64>.max()) - See also - append(u)
- Parameters:
- u – int 
 
 - append(str[, size=-1])
- Parameters:
- str – str 
- size – int 
 
 
 - This is an overloaded function. - Appends - sizebytes of text starting from- strto the stream, creating a CBOR Text String value.- QCborStreamWriterwill attempt to write the entire string in one chunk. If- sizeis -1, this function will write- strlen(\a str)bytes.- The string pointed to by - stris expected to be properly encoded UTF-8.- QCborStreamWriterperforms no validation that this is the case.- Unlike the - QLatin1StringViewoverload of- append(), this function is not limited to 2 GB. However, note that neither- QCborStreamReadernor- QCborValuesupport reading CBOR streams with text strings larger than 2 GB.- See also - append(QLatin1StringView)- append(QStringView)- isString()- readString()- appendByteString(data, len)¶
- Parameters:
- data – str 
- len – int 
 
 
 - Appends - lenbytes of data starting from- datato the stream, creating a CBOR Byte String value.- QCborStreamWriterwill attempt to write the entire string in one chunk.- Unlike the - QByteArrayoverload of- append(), this function is not limited by- QByteArray‘s size limits. However, note that neither- readByteArray()nor- QCborValuesupport reading CBOR streams with byte arrays larger than 2 GB.- appendNull()¶
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - Appends a CBOR Null value to the stream. This function is equivalent to (and implemented as): - writer.append(QCborSimpleType.Null) - See also - nullptr_t)- append(QCborSimpleType)- isNull()- appendTextString(utf8, len)¶
- Parameters:
- utf8 – str 
- len – int 
 
 
 - Appends - lenbytes of text starting from- utf8to the stream, creating a CBOR Text String value.- QCborStreamWriterwill attempt to write the entire string in one chunk.- The string pointed to by - utf8is expected to be properly encoded UTF-8.- QCborStreamWriterperforms no validation that this is the case.- Unlike the - QLatin1StringViewoverload of- append(), this function is not limited to 2 GB. However, note that neither- readString()nor- QCborValuesupport reading CBOR streams with text strings larger than 2 GB.- See also - append(QLatin1StringView)- append(QStringView)- isString()- readString()- appendUndefined()¶
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - Appends a CBOR Undefined value to the stream. This function is equivalent to (and implemented as): - writer.append(QCborSimpleType.Undefined) - See also - append(QCborSimpleType)- isUndefined()- Returns the - QIODevicethat this- QCborStreamWriterobject is writing to. The device must have previously been set with either the constructor or with- setDevice().- If this object was created by writing to a - QByteArray, this function will return an internal instance of- QBuffer, which is owned by- QCborStreamWriter.- See also - endArray()¶
- Return type:
- bool 
 
 - Terminates the array started by either overload of - startArray()and returns true if the correct number of elements was added to the array. This function must be called for every- startArray()used.- A return of false indicates error in the application and an unrecoverable error in this stream. - QCborStreamWriteralso writes a warning using- qWarning()if that happens.- Calling this function when the current container is not an array is also an error, though - QCborStreamWritercannot currently detect this condition.- See also - startArray()- startArray(quint64)- endMap()- endMap()¶
- Return type:
- bool 
 
 - Terminates the map started by either overload of - startMap()and returns true if the correct number of elements was added to the array. This function must be called for every- startMap()used.- A return of false indicates error in the application and an unrecoverable error in this stream. - QCborStreamWriteralso writes a warning using- qWarning()if that happens.- Calling this function when the current container is not a map is also an error, though - QCborStreamWritercannot currently detect this condition.- See also - startMap()- startMap(quint64)- endArray()- Replaces the device or byte array that this - QCborStreamWriterobject is writing to with- device.- See also - startArray()¶
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - Starts a CBOR Array with indeterminate length in the CBOR stream. Each startArray() call must be paired with one - endArray()call and the current CBOR element extends until the end of the array.- The array created by this function has no explicit length. Instead, its length is implied by the elements contained in it. Note, however, that use of indeterminate-length arrays is not compliant with canonical CBOR encoding. - The following example appends elements from the list of strings passed as input: - def appendList(writer, values): writer.startArray() for s in values: writer.append(s) writer.endArray() - See also - startArray(quint64)- endArray()- startMap()- isArray()- isLengthKnown()- startArray(count)
- Parameters:
- count – int 
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - This is an overloaded function. - Starts a CBOR Array with explicit length of - countitems in the CBOR stream. Each- startArraycall must be paired with one- endArray()call and the current CBOR element extends until the end of the array.- The array created by this function has an explicit length and therefore exactly - countitems must be added to the CBOR stream. Adding fewer or more items will result in failure during- endArray()and the CBOR stream will be corrupt. However, explicit-length arrays are required by canonical CBOR encoding.- The following example appends all strings found in the - QStringListpassed as input:- def appendList(writer, list): writer.startArray(list.size()) for s in list: writer.append(s) writer.endArray() - Size limitations: The parameter to this function is quint64, which would seem to allow up to 2 64-1 elements in the array. However, both - QCborStreamWriterand- QCborStreamReaderare currently limited to 2 32-2 items on 32-bit systems and 2 64-2 items on 64-bit ones. Also note that- QCborArrayis currently limited to 2 27 elements on 32-bit platforms and 2 59 elements on 64-bit ones.- startMap()¶
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - Starts a CBOR Map with indeterminate length in the CBOR stream. Each startMap() call must be paired with one - endMap()call and the current CBOR element extends until the end of the map.- The map created by this function has no explicit length. Instead, its length is implied by the elements contained in it. Note, however, that use of indeterminate-length maps is not compliant with canonical CBOR encoding (canonical encoding also requires keys to be unique and in sorted order). - The following example appends elements from the list of int and string pairs passed as input: - def appendMap(writer, QList<std.pair<int, values): writer.startMap() for pair in values: writer.append(pair.first) writer.append(pair.second) writer.endMap() - See also - startMap(quint64)- endMap()- startArray()- isMap()- isLengthKnown()- startMap(count)
- Parameters:
- count – int 
 
 - Warning - This section contains snippets that were automatically translated from C++ to Python and may contain errors. - This is an overloaded function. - Starts a CBOR Map with explicit length of - countitems in the CBOR stream. Each- startMapcall must be paired with one- endMap()call and the current CBOR element extends until the end of the map.- The map created by this function has an explicit length and therefore exactly - countpairs of items must be added to the CBOR stream. Adding fewer or more items will result in failure during- endMap()and the CBOR stream will be corrupt. However, explicit-length map are required by canonical CBOR encoding.- The following example appends all strings found in the - QMappassed as input:- def appendMap(writer, QMap<int, map): writer.startMap(map.size()) for it in map: writer.append(it.key()) writer.append(it.value()) writer.endMap() - Size limitations: The parameter to this function is quint64, which would seem to allow up to 2 64-1 pairs in the map. However, both - QCborStreamWriterand- QCborStreamReaderare currently limited to 2 31-1 items on 32-bit systems and 2 63-1 items on 64-bit ones. Also note that- QCborMapis currently limited to 2 26 elements on 32-bit platforms and 2 58 on 64-bit ones.- See also