QCborStreamReader Class

The QCborStreamReader class is a simple CBOR stream decoder, operating on either a QByteArray or QIODevice. More...

Header: #include <QCborStreamReader>
CMake: find_package(Qt6 REQUIRED COMPONENTS Core)
target_link_libraries(mytarget PRIVATE Qt6::Core)
qmake: QT += core

Note: All functions in this class are reentrant.

Public Types

struct StringResult
enum StringResultCode { EndOfString, Ok, Error }
enum Type { UnsignedInteger, NegativeInteger, ByteArray, ByteString, String, …, Invalid }

Public Functions

QCborStreamReader()
QCborStreamReader(QIODevice *device)
QCborStreamReader(const QByteArray &data)
QCborStreamReader(const char *data, qsizetype len)
QCborStreamReader(const quint8 *data, qsizetype len)
~QCborStreamReader()
void addData(const QByteArray &data)
void addData(const char *data, qsizetype len)
void clear()
int containerDepth() const
qint64 currentOffset() const
QIODevice *device() const
bool hasNext() const
bool isLengthKnown() const
QCborError lastError() const
bool leaveContainer()
quint64 length() const
bool next(int maxRecursion = 10000)
QCborStreamReader::Type parentContainerType() const
QCborStreamReader::StringResult<qsizetype> readStringChunk(char *ptr, qsizetype maxlen)
void reparse()
void reset()
void setDevice(QIODevice *device)

Detailed Description

This class can be used to decode a stream of CBOR content directly from either a QByteArray or a 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.

QCborStreamReader provides a StAX-like API, similar to that of QXmlStreamReader. Using it requires a bit of knowledge of CBOR encoding. For a simpler API, see QCborValue and especially the decoding function QCborValue::fromCbor().

Typically, one creates a QCborStreamReader by passing the source QByteArray or QIODevice as a parameter to the constructor, then pop elements off the stream if there were no errors in decoding. There are three kinds of CBOR types:

KindTypesBehavior
Fixed-widthIntegers, Tags, Simple types, Floating pointValue is pre-parsed by QCborStreamReader, so accessor functions are const. Must call next() to advance.
StringsByte arrays, Text stringsLength (if known) is pre-parsed, but the string itself is not. The accessor functions are not const and may allocate memory. Once called, the accessor functions automatically advance to the next element.
ContainersArrays, MapsLength (if known) is pre-parsed. To access the elements, you must call enterContainer(), read all elements, then call leaveContainer(). That function advances to the next element.

So a processor function typically looks like this:

    void handleStream(QCborStreamReader &reader)
    {
        switch (reader.type())
        case QCborStreamReader::UnsignedInteger:
        case QCborStreamReader::NegativeInteger:
        case QCborStreamReader::SimpleType:
        case QCborStreamReader::Float16:
        case QCborStreamReader::Float:
        case QCborStreamReader::Double:
            handleFixedWidth(reader);
            reader.next();
            break;
        case QCborStreamReader::ByteArray:
        case QCborStreamReader::String:
            handleString(reader);
            break;
        case QCborStreamReader::Array:
        case QCborStreamReader::Map:
            reader.enterContainer();
            while (reader.lastError() == QCborError::NoError)
                handleStream(reader);
            if (reader.lastError() == QCborError::NoError)
                reader.leaveContainer();
        }
    }

CBOR support

The following table lists the CBOR features that QCborStreamReader supports.

FeatureSupport
Unsigned numbersYes (full range)
Negative numbersYes (full range)
Byte stringsYes
Text stringsYes
Chunked stringsYes
TagsYes (arbitrary)
BooleansYes
NullYes
UndefinedYes
Arbitrary simple valuesYes
Half-precision float (16-bit)Yes
Single-precision float (32-bit)Yes
Double-precision float (64-bit)Yes
Infinities and NaN floating pointYes
Determinate-length arrays and mapsYes
Indeterminate-length arrays and mapsYes
Map key types other than strings and integersYes (arbitrary)

Dealing with invalid or incomplete CBOR streams

QCborStreamReader is capable of detecting corrupt input on its own. The library it uses has been extensively tested against invalid input of any kind and is quite able to report errors. If any is detected, QCborStreamReader will set lastError() to a value besides QCborError::NoError, indicating which situation was detected.

Most errors detected by QCborStreamReader during normal item parsing are not recoverable. The code using QCborStreamReader may opt to handle the data that was properly decoded or it can opt to discard the entire data.

The only recoverable error is QCborError::EndOfFile, which indicates that more data is required in order to complete the parsing. This situation is useful when data is being read from an asynchronous source, such as a pipe (QProcess) or a socket (QTcpSocket, QUdpSocket, QNetworkReply, etc.). When more data arrives, the surrounding code needs to call either addData(), if parsing from a QByteArray, or reparse(), if it is instead reading directly a the QIDOevice that now has more data available (see setDevice()).

See also QCborStreamWriter, QCborValue, QXmlStreamReader, Parsing and displaying CBOR data, Serialization Converter, and Saving and Loading a Game.

Member Type Documentation

enum QCborStreamReader::StringResultCode

This enum is returned by readString() and readByteArray() and is used to indicate what the status of the parsing is.

ConstantValueDescription
QCborStreamReader::EndOfString0The parsing for the string is complete, with no error.
QCborStreamReader::Ok1The function returned data; there was no error.
QCborStreamReader::Error-1Parsing failed with an error.

enum QCborStreamReader::Type

This enumeration contains all possible CBOR types as decoded by QCborStreamReader. CBOR has 7 major types, plus a number of simple types carrying no value, and floating point values.

ConstantValueDescription
QCborStreamReader::UnsignedInteger0x00(Major type 0) Ranges from 0 to 264 - 1 (18,446,744,073,709,551,616)
QCborStreamReader::NegativeInteger0x20(Major type 1) Ranges from -1 to -264 (-18,446,744,073,709,551,616)
QCborStreamReader::ByteArrayByteString(Major type 2) Arbitrary binary data.
QCborStreamReader::ByteString0x40An alias to ByteArray.
QCborStreamReader::StringTextString(Major type 3) Unicode text, possibly containing NULs.
QCborStreamReader::TextString0x60An alias to String
QCborStreamReader::Array0x80(Major type 4) Array of heterogeneous items.
QCborStreamReader::Map0xa0(Major type 5) Map/dictionary of heterogeneous items.
QCborStreamReader::Tag0xc0(Major type 6) Numbers giving further semantic value to generic CBOR items. See QCborTag for more information.
QCborStreamReader::SimpleType0xe0(Major type 7) Types carrying no further value. Includes booleans (true and false), null, undefined.
QCborStreamReader::Float16HalfFloatIEEE 754 half-precision floating point (qfloat16).
QCborStreamReader::HalfFloat0xf9An alias to Float16.
QCborStreamReader::Float0xfaIEEE 754 single-precision floating point (float).
QCborStreamReader::Double0xfbIEEE 754 double-precision floating point (double).
QCborStreamReader::Invalid0xffNot a valid type, either due to parsing error or due to reaching the end of an array or map.

Member Function Documentation

QCborStreamReader::QCborStreamReader()

Creates a QCborStreamReader object with no source data. After construction, QCborStreamReader will report an error parsing.

You can add more data by calling addData() or by setting a different source device using setDevice().

See also addData() and isValid().

[explicit] QCborStreamReader::QCborStreamReader(QIODevice *device)

This is an overloaded function.

Creates a QCborStreamReader object that will parse the CBOR stream found by reading from device. QCborStreamReader does not take ownership of device, so it must remain valid until this object is destroyed.

[explicit] QCborStreamReader::QCborStreamReader(const QByteArray &data)

This is an overloaded function.

Creates a QCborStreamReader object that will parse the CBOR stream found in data.

QCborStreamReader::QCborStreamReader(const char *data, qsizetype len)

This is an overloaded function.

Creates a QCborStreamReader object with len bytes of data starting at data. The pointer must remain valid until QCborStreamReader is destroyed.

QCborStreamReader::QCborStreamReader(const quint8 *data, qsizetype len)

This is an overloaded function.

Creates a QCborStreamReader object with len bytes of data starting at data. The pointer must remain valid until QCborStreamReader is destroyed.

[noexcept] QCborStreamReader::~QCborStreamReader()

Destroys this QCborStreamReader object and frees any associated resources.

void QCborStreamReader::addData(const QByteArray &data)

Adds data to the CBOR stream and reparses the current element. This function is useful if the end of the data was previously reached while processing the stream, but now more data is available.

void QCborStreamReader::addData(const char *data, qsizetype len)

This is an overloaded function.

Adds len bytes of data starting at data to the CBOR stream and reparses the current element. This function is useful if the end of the data was previously reached while processing the stream, but now more data is available.

void QCborStreamReader::clear()

Clears the decoder state and resets the input source data to an empty byte array. After this function is called, QCborStreamReader will be indicating an error parsing.

Call addData() to add more data to be parsed.

See also reset() and setDevice().

int QCborStreamReader::containerDepth() const

Returns the number of containers that this stream has entered with enterContainer() but not yet left.

See also enterContainer() and leaveContainer().

qint64 QCborStreamReader::currentOffset() const

Returns the offset in the input stream of the item currently being decoded. The current offset is the number of decoded bytes so far only if the source data is a QByteArray or it is a QIODevice that was positioned at its beginning when decoding started.

See also reset(), clear(), and device().

QIODevice *QCborStreamReader::device() const

Returns the QIODevice that was set with either setDevice() or the QCborStreamReader constructor. If this object was reading from a QByteArray, this function returns nullptr instead.

See also setDevice().

[noexcept] bool QCborStreamReader::hasNext() const

Returns true if there are more items to be decoded in the current container or false of we've reached its end. If we're parsing the root element, hasNext() returning false indicates the parsing is complete; otherwise, if the container depth is non-zero, then the outer code needs to call leaveContainer().

See also parentContainerType(), containerDepth(), and leaveContainer().

[noexcept] bool QCborStreamReader::isLengthKnown() const

Returns true if the length of the current array, map, byte array or string is known (explicit in the CBOR stream), false otherwise. This function should only be called if the element is one of those.

If the length is known, it may be obtained by calling length().

If the length of a map or an array is not known, it is implied by the number of elements present in the stream. QCborStreamReader has no API to calculate the length in that condition.

Strings and byte arrays may also have indeterminate length (that is, they may be transmitted in multiple chunks). Those cannot currently be created with QCborStreamWriter, but they could be with other encoders, so QCborStreamReader supports them.

See also length(), QCborStreamWriter::startArray(), and QCborStreamWriter::startMap().

QCborError QCborStreamReader::lastError() const

Returns the last error in decoding the stream, if any. If no error was encountered, this returns an QCborError::NoError.

See also isValid().

bool QCborStreamReader::leaveContainer()

Leaves the array or map whose items were being processed and positions the decoder at the next item after the end of the container. Returns true if leaving the container succeeded, false otherwise (usually, a parsing error). Each call to enterContainer() must be paired with a call to leaveContainer().

This function may only be called if hasNext() has returned false and containerDepth() is not zero. Calling it in any other condition is an error.

See also enterContainer(), parentContainerType(), and containerDepth().

quint64 QCborStreamReader::length() const

Returns the length of the string or byte array, or the number of items in an array or the number, of item pairs in a map, if known. This function must not be called if the length is unknown (that is, if isLengthKnown() returned false). It is an error to do that and it will cause QCborStreamReader to stop parsing the input stream.

See also isLengthKnown(), QCborStreamWriter::startArray(), and QCborStreamWriter::startMap().

bool QCborStreamReader::next(int maxRecursion = 10000)

Advance the CBOR stream decoding one element. You should usually call this function when parsing fixed-width basic elements (that is, integers, simple values, tags and floating point values). But this function can be called when the current item is a string, array or map too and it will skip over that entire element, including all contained elements.

This function returns true if advancing was successful, false otherwise. It may fail if the stream is corrupt, incomplete or if the nesting level of arrays and maps exceeds maxRecursion. Calling this function when hasNext() has returned false is also an error. If this function returns false, lastError() will return the error code detailing what the failure was.

See also lastError(), isValid(), and hasNext().

QCborStreamReader::Type QCborStreamReader::parentContainerType() const

Returns either QCborStreamReader::Array or QCborStreamReader::Map, indicating whether the container that contains the current item was an array or map, respectively. If we're currently parsing the root element, this function returns QCborStreamReader::Invalid.

See also containerDepth() and enterContainer().

QCborStreamReader::StringResult<qsizetype> QCborStreamReader::readStringChunk(char *ptr, qsizetype maxlen)

Reads the current string chunk into the buffer pointed to by ptr, whose size is maxlen. This function returns a StringResult object, with the number of bytes copied into ptr saved in the \l StringResult::data member. The \l StringResult::status member indicates whether there was an error reading the string, whether data was copied or whether this was the last chunk.

This function can be called for both String and ByteArray types. For the latter, this function will read the same data that readByteArray() would have returned. For strings, it returns the UTF-8 equivalent of the QString that would have been returned.

This function is usually used alongside currentStringChunkSize() in a loop. For example:

     QCborStreamReader<qsizetype> result;
     do {
         qsizetype size = reader.currentStringChunkSize();
         qsizetype oldsize = buffer.size();
         buffer.resize(oldsize + size);
         result = reader.readStringChunk(buffer.data() + oldsize, size);
     } while (result.status() == QCborStreamReader::Ok);

Unlike readByteArray() and readString(), this function is not limited by implementation limits of QByteArray and QString.

Note: This function does not perform verification that the UTF-8 contents are properly formatted. That means this function does not produce the QCborError::InvalidUtf8String error, even when readString() does.

See also currentStringChunkSize(), readString(), readByteArray(), isString(), and isByteArray().

void QCborStreamReader::reparse()

Reparses the current element. This function must be called when more data becomes available in the source QIODevice after parsing failed due to reaching the end of the input data before the end of the CBOR stream.

When reading from QByteArray(), the addData() function automatically calls this function. Calling it when the reading had not failed is a no-op.

void QCborStreamReader::reset()

Resets the source back to the beginning and clears the decoder state. If the source data was a QByteArray, QCborStreamReader will restart from the beginning of the array.

If the source data is a QIODevice, this function will call QIODevice::reset(), which will seek to byte position 0. If the CBOR stream is not found at the beginning of the device (e.g., beginning of a file), then this function will likely do the wrong thing. Instead, position the QIODevice to the right offset and call setDevice().

See also clear() and setDevice().

void QCborStreamReader::setDevice(QIODevice *device)

Sets the source of data to device, resetting the decoder to its initial state.

See also device().