QCborStreamReader 类

QCborStreamReader 类是简单 CBOR 流解码器,用于操作 QByteArray or QIODevice . 更多...

头: #include <QCborStreamReader>
qmake: QT += core
Since: Qt 5.12

该类在 Qt 5.12 引入。

注意: 此类的所有函数 可重入 .

公共类型

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

公共函数

QCborStreamReader (QIODevice * device )
QCborStreamReader (const QByteArray & data )
QCborStreamReader (const quint8 * data , qsizetype len )
QCborStreamReader (const char * data , qsizetype len )
QCborStreamReader ()
~QCborStreamReader ()
void addData (const QByteArray & data )
void addData (const char * data , qsizetype len )
void addData (const quint8 * data , qsizetype len )
void clear ()
int containerDepth () const
qint64 currentOffset () const
qsizetype currentStringChunkSize () const
QIODevice * device () const
bool enterContainer ()
bool hasNext () const
bool isArray () const
bool isBool () const
bool isByteArray () const
bool isContainer () const
bool isDouble () const
bool isFalse () const
bool isFloat16 () const
bool isFloat () const
bool isInteger () const
bool isInvalid () const
bool isLengthKnown () const
bool isMap () const
bool isNegativeInteger () const
bool isNull () const
bool isSimpleType () const
bool isSimpleType (QCborSimpleType st ) const
bool isString () const
bool isTag () const
bool isTrue () const
bool isUndefined () const
bool isUnsignedInteger () const
bool isValid () const
QCborError lastError ()
bool leaveContainer ()
quint64 length () const
bool next (int maxRecursion = 10000)
QCborStreamReader::Type parentContainerType () const
StringResult<QByteArray> readByteArray ()
StringResult<QString> readString ()
StringResult<qsizetype> readStringChunk (char * ptr , qsizetype maxlen )
void reparse ()
void reset ()
void setDevice (QIODevice * device )
bool toBool () const
double toDouble () const
qfloat16 toFloat16 () const
float toFloat () const
qint64 toInteger () const
QCborNegativeInteger toNegativeInteger () const
QCborSimpleType toSimpleType () const
QCborTag toTag () const
quint64 toUnsignedInteger () const
QCborStreamReader::Type type () const

详细描述

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

Kind 类型 行为
Fixed-width Integers, Tags, Simple types, Floating point Value is pre-parsed by QCborStreamReader, so accessor functions are const . Must call next () to advance.
字符串 Byte arrays, Text strings Length (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.
容器 Arrays, Maps Length (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 支持

The following table lists the CBOR features that QCborStreamReader supports.

特征 支持
无符号数字 Yes (full range)
负数 Yes (full range)
字节字符串 Yes
Text strings Yes
Chunked strings Yes
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)

处理无效或不完整的 CBOR 流

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 ,或 reparse (), if it is instead reading directly a the QIDOevice that now has more data available (see setDevice ()).

另请参阅 QCborStreamWriter , QCborValue ,和 QXmlStreamReader .

成员类型文档编制

enum QCborStreamReader:: StringResultCode

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

常量 描述
QCborStreamReader::EndOfString 0 The parsing for the string is complete, with no error.
QCborStreamReader::Ok 1 The function returned data; there was no error.
QCborStreamReader::Error -1 Parsing 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.

常量 描述
QCborStreamReader::UnsignedInteger 0x00 (Major type 0) Ranges from 0 to 2 64 - 1 (18,446,744,073,709,551,616)
QCborStreamReader::NegativeInteger 0x20 (Major type 1) Ranges from -1 to -2 64 (-18,446,744,073,709,551,616)
QCborStreamReader::ByteArray ByteString (Major type 2) Arbitrary binary data.
QCborStreamReader::ByteString 0x40 An alias to ByteArray.
QCborStreamReader::String TextString (Major type 3) Unicode text, possibly containing NULs.
QCborStreamReader::TextString 0x60 An alias to String
QCborStreamReader::Array 0x80 (Major type 4) Array of heterogeneous items.
QCborStreamReader::Map 0xa0 (Major type 5) Map/dictionary of heterogeneous items.
QCborStreamReader::Tag 0xc0 (Major type 6) Numbers giving further semantic value to generic CBOR items. See QCborTag 了解更多信息。
QCborStreamReader::SimpleType 0xe0 (Major type 7) Types carrying no further value. Includes booleans (true and false), null, undefined.
QCborStreamReader::Float16 HalfFloat IEEE 754 half-precision floating point ( qfloat16 ).
QCborStreamReader::HalfFloat 0xf9 An alias to Float16.
QCborStreamReader::Float 0xfa IEEE 754 single-precision floating point ( float ).
QCborStreamReader::Double 0xfb IEEE 754 double-precision floating point ( double ).
QCborStreamReader::Invalid 0xff Not a valid type, either due to parsing error or due to reaching the end of an array or map.

成员函数文档编制

QCborStreamReader:: QCborStreamReader ( QIODevice * device )

这是重载函数。

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 oject is destroyed.

QCborStreamReader:: QCborStreamReader (const QByteArray & data )

这是重载函数。

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

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

这是重载函数。

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

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

这是重载函数。

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

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 ().

另请参阅 addData () 和 isValid ().

QCborStreamReader:: ~QCborStreamReader ()

销毁此 QCborStreamReader object and frees any associated resources.

void QCborStreamReader:: addData (const QByteArray & data )

添加 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 )

这是重载函数。

添加 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:: addData (const quint8 * data , qsizetype len )

这是重载函数。

添加 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.

调用 addData () to add more data to be parsed.

另请参阅 reset () 和 setDevice ().

int QCborStreamReader:: containerDepth () const

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

另请参阅 enterContainer () 和 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.

另请参阅 reset (), clear (),和 device ().

qsizetype QCborStreamReader:: currentStringChunkSize () const

Returns the size of the current text or byte string chunk. If the CBOR stream contains a non-chunked string (that is, if isLengthKnown () 返回 true ), this function returns the size of the entire string, the same as length ().

This function is useful to pre-allocate the buffer whose pointer can be passed to readStringChunk () later.

另请参阅 readString (), readByteArray (),和 readStringChunk ().

QIODevice *QCborStreamReader:: device () const

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

另请参阅 setDevice ().

bool QCborStreamReader:: enterContainer ()

Enters the array or map that is the current item and prepares for iterating the elements contained in the container. Returns true if entering 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 the current item is an array or a map (that is, if isArray (), isMap () 或 isContainer () is true). Calling it in any other condition is an error.

另请参阅 leaveContainer (), isContainer (), isArray (),和 isMap ().

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 ().

另请参阅 parentContainerType (), containerDepth (),和 leaveContainer ().

bool QCborStreamReader:: isArray () const

Returns true if the type of the current element is an array (that is, if type () 返回 QCborStreamReader::Array ). If this function returns true, you may call enterContainer () to begin parsing that container.

When the current element is an array, you may also call isLengthKnown () to find out if the array's size is explicit in the CBOR stream. If it is, that size can be obtained by calling length ().

The following example pre-allocates a QVariantList given the array's size for more efficient decoding:

   QVariantList populateFromCbor(QCborStreamReader &reader)
   {
       QVariantList list;
       if (reader.isLengthKnown())
           list.reserve(reader.length());
       reader.enterContainer();
       while (reader.lastError() == QCborError::NoError && reader.hasNext())
           list.append(readOneElement(reader));
       if (reader.lastError() == QCborError::NoError)
           reader.leaveContainer();
   }
					

注意: The code above does not validate that the length is a sensible value. If the input stream reports that the length is 1 billion elements, the above function will try to allocate some 16 GB or more of RAM, which can lead to a crash.

另请参阅 type (), isMap (), isLengthKnown (), length (), enterContainer (),和 leaveContainer ().

bool QCborStreamReader:: isBool () const

Returns true if the current element is a boolean value ( true or false ), false if it is anything else. If this function returns true, you may call toBool () to retrieve the value of the boolean. You may also call toSimpleType () and compare to either QCborSimpleValue::True or QCborSimpleValue::False.

另请参阅 type (), isFalse (), isTrue (), toBool (), isSimpleType (),和 toSimpleType ().

bool QCborStreamReader:: isByteArray () const

Returns true if the type of the current element is a byte array (that is, if type () 返回 QCborStreamReader::ByteArray ). If this function returns true, you may call readByteArray () to read that data.

另请参阅 type (), readByteArray (),和 isString ().

bool QCborStreamReader:: isContainer () const

Returns true if the current element is a container (that is, an array or a map), false if it is anything else. If the current element is a container, the isLengthKnown () function may be used to find out if the container's size is explicit in the stream and, if so, length () can be used to get that size.

More importantly, for a container, the enterContainer () function is available to begin iterating through the elements contained therein.

另请参阅 type (), isArray (), isMap (), isLengthKnown (), length (), enterContainer (), leaveContainer (),和 containerDepth ().

bool QCborStreamReader:: isDouble () const

Returns true if the type of the current element is an IEEE 754 double-precision floating point (that is, if type () 返回 QCborStreamReader::Double ). If this function returns true, you may call toDouble () to read that data.

另请参阅 type (), toDouble (), isFloat16 (),和 isFloat ().

bool QCborStreamReader:: isFalse () const

Returns true if the current element is the false value, false if it is anything else.

另请参阅 type (), isTrue (), isBool (), toBool (), isSimpleType (),和 toSimpleType ().

bool QCborStreamReader:: isFloat16 () const

Returns true if the type of the current element is an IEEE 754 half-precision floating point (that is, if type () 返回 QCborStreamReader::Float16 ). If this function returns true, you may call toFloat16 () to read that data.

另请参阅 type (), toFloat16 (), isFloat (),和 isDouble ().

bool QCborStreamReader:: isFloat () const

Returns true if the type of the current element is an IEEE 754 single-precision floating point (that is, if type () 返回 QCborStreamReader::Float ). If this function returns true, you may call toFloat () to read that data.

另请参阅 type (), toFloat (), isFloat16 (),和 isDouble ().

bool QCborStreamReader:: isInteger () const

Returns true if the type of the current element is either an unsigned integer or a negative one (that is, if type () 返回 QCborStreamReader::UnsignedInteger or QCborStreamReader::NegativeInteger ). If this function returns true, you may call toInteger () to read that value.

另请参阅 type (), toInteger (), toUnsignedInteger (), toNegativeInteger (), isUnsignedInteger (),和 isNegativeInteger ().

bool QCborStreamReader:: isInvalid () const

Returns true if the current element is invalid, false otherwise. The current element may be invalid if there was a decoding error or we've just parsed the last element in an array or map.

注意: This function is not to be confused with isNull (). Null is a normal CBOR type that must be handled by the application.

另请参阅 type () 和 isValid ().

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.

另请参阅 length (), QCborStreamWriter::startArray (),和 QCborStreamWriter::startMap ().

bool QCborStreamReader:: isMap () const

Returns true if the type of the current element is a map (that is, if type () 返回 QCborStreamReader::Map ). If this function returns true, you may call enterContainer () to begin parsing that container.

When the current element is a map, you may also call isLengthKnown () to find out if the map's size is explicit in the CBOR stream. If it is, that size can be obtained by calling length ().

The following example pre-allocates a QVariantMap given the map's size for more efficient decoding:

   QVariantMap populateFromCbor(QCborStreamReader &reader)
   {
       QVariantMap map;
       if (reader.isLengthKnown())
           map.reserve(reader.length());
       reader.enterContainer();
       while (reader.lastError() == QCborError::NoError && reader.hasNext()) {
           QString key = readElementAsString(reader);
           map.insert(key, readOneElement(reader));
       }
       if (reader.lastError() == QCborError::NoError)
           reader.leaveContainer();
   }
					

The example above uses a function called readElementAsString to read the map's keys and obtain a string. That is because CBOR maps may contain any type as keys, not just strings. User code needs to either perform this conversion, reject non-string keys, or instead use a different container besides QVariantMap and QVariantHash . For example, if the map is expected to contain integer keys, which is recommended as it reduces stream size and parsing, the correct container would be \l{QMap}<int, QVariant> or \l{QHash}<int, QVariant> .

注意: The code above does not validate that the length is a sensible value. If the input stream reports that the length is 1 billion elements, the above function will try to allocate some 24 GB or more of RAM, which can lead to a crash.

另请参阅 type (), isArray (), isLengthKnown (), length (), enterContainer (),和 leaveContainer ().

bool QCborStreamReader:: isNegativeInteger () const

Returns true if the type of the current element is a negative integer (that is if type () 返回 QCborStreamReader::NegativeInteger ). If this function returns true, you may call toNegativeInteger () 或 toInteger () to read that value.

另请参阅 type (), toNegativeInteger (), toInteger (), isInteger (),和 isUnsignedInteger ().

bool QCborStreamReader:: isNull () const

Returns true if the current element is the null value, false if it is anything else. Null values may be used to indicate the absence of some optional data.

注意: This function is not the opposite of isValid (). A Null value is a valid CBOR value.

另请参阅 type (), isSimpleType (),和 toSimpleType ().

bool QCborStreamReader:: isSimpleType () const

Returns true if the type of the current element is any CBOR simple type, including a boolean value (true and false) as well as null and undefined. To find out which simple type this is, call toSimpleType (). Alternatively, to test for one specific simple type, call the overload that takes a QCborSimpleType 参数。

CBOR simple types are types that do not carry extra value. There are 255 possibilities, but there are currently only four values that have defined meaning. Code is not expected to cope with unknown simple types and may simply discard the stream as invalid if it finds an unknown one.

另请参阅 QCborSimpleType , type (), isSimpleType (QCborSimpleType), and toSimpleType ().

bool QCborStreamReader:: isSimpleType ( QCborSimpleType st ) const

Returns true if the type of the current element is the simple type st , false otherwise. If this function returns true, then toSimpleType () 会返回 st .

CBOR simple types are types that do not carry extra value. There are 255 possibilities, but there are currently only four values that have defined meaning. Code is not expected to cope with unknown simple types and may simply discard the stream as invalid if it finds an unknown one.

另请参阅 QCborSimpleType , type (), isSimpleType (),和 toSimpleType ().

bool QCborStreamReader:: isString () const

Returns true if the type of the current element is a text string (that is, if type () 返回 QCborStreamReader::String ). If this function returns true, you may call readString () to read that data.

另请参阅 type (), readString (),和 isByteArray ().

bool QCborStreamReader:: isTag () const

Returns true if the type of the current element is a CBOR tag (that is, if type () 返回 QCborStreamReader::Tag ). If this function returns true, you may call toTag () to read that data.

另请参阅 type () 和 toTag ().

bool QCborStreamReader:: isTrue () const

Returns true if the current element is the true value, false if it is anything else.

另请参阅 type (), isFalse (), isBool (), toBool (), isSimpleType (),和 toSimpleType ().

bool QCborStreamReader:: isUndefined () const

Returns true if the current element is the undefined value, false if it is anything else. Undefined values may be encoded to indicate that some conversion failed or was not possible when creating the stream. QCborStreamReader never performs any replacement and this function will only return true if the stream contains an explicit undefined value.

另请参阅 type (), isSimpleType (),和 toSimpleType ().

bool QCborStreamReader:: isUnsignedInteger () const

Returns true if the type of the current element is an unsigned integer (that is if type () 返回 QCborStreamReader::UnsignedInteger ). If this function returns true, you may call toUnsignedInteger () 或 toInteger () to read that value.

另请参阅 type (), toUnsignedInteger (), toInteger (), isInteger (),和 isNegativeInteger ().

bool QCborStreamReader:: isValid () const

Returns true if the current element is valid, false otherwise. The current element may be invalid if there was a decoding error or we've just parsed the last element in an array or map.

注意: This function is not the opposite of isNull (). Null is a normal CBOR type that must be handled by the application.

另请参阅 type () 和 isInvalid ().

QCborError QCborStreamReader:: lastError ()

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

另请参阅 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.

另请参阅 enterContainer (), parentContainerType (),和 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.

另请参阅 isLengthKnown (), QCborStreamWriter::startArray (),和 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.

另请参阅 lastError (), isValid (),和 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 .

另请参阅 containerDepth () 和 enterContainer ().

StringResult < QByteArray > QCborStreamReader:: readByteArray ()

Decodes one byte array chunk from the CBOR string and returns it. This function is used for both regular and chunked contents, so the caller must always loop around calling this function, even if isLengthKnown () has is true. The typical use of this function is as follows:

   QBytearray decodeBytearray(QCborStreamReader &reader)
   {
       QBytearray result;
       auto r = reader.readBytearray();
       while (r.code == QCborStreamReader::Ok) {
           result += r.data;
           r = reader.readByteArray();
       }
       if (r.code == QCborStreamReader::Error) {
           // handle error condition
           result.clear();
       }
       return result;
   }
					

This function does not perform any type conversions, including from integers or from strings. Therefore, it may only be called if isByteArray () is true; calling it in any other condition is an error.

另请参阅 readString (), isByteArray (),和 readStringChunk ().

StringResult < QString > QCborStreamReader:: readString ()

Decodes one string chunk from the CBOR string and returns it. This function is used for both regular and chunked string contents, so the caller must always loop around calling this function, even if isLengthKnown () has is true. The typical use of this function is as follows:

   QString decodeString(QCborStreamReader &reader)
   {
       QString result;
       auto r = reader.readString();
       while (r.code == QCborStreamReader::Ok) {
           result += r.data;
           r = reader.readString();
       }
       if (r.code == QCborStreamReader::Error) {
           // handle error condition
           result.clear();
       }
       return result;
   }
					

This function does not perform any type conversions, including from integers or from byte arrays. Therefore, it may only be called if isString () returned true; calling it in any other condition is an error.

另请参阅 readByteArray (), isString (),和 readStringChunk ().

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 字符串 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);
					

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

注意: 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 () 做。

另请参阅 currentStringChunkSize (), readString (), readByteArray (), isString (),和 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 ().

另请参阅 clear () 和 setDevice ().

void QCborStreamReader:: setDevice ( QIODevice * device )

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

另请参阅 device ().

bool QCborStreamReader:: toBool () const

Returns the boolean value of the current element.

This function does not perform any type conversions, including from integer. Therefore, it may only be called if isTrue (), isFalse () 或 isBool () returned true; calling it in any other condition is an error.

另请参阅 isBool (), isTrue (), isFalse (),和 toInteger ().

double QCborStreamReader:: toDouble () const

Returns the 64-bit double-precision floating point value of the current element.

This function does not perform any type conversions, including from other floating point types or from integer values. Therefore, it may only be called if isDouble () is true; calling it in any other condition is an error.

另请参阅 isDouble (), toFloat16 (),和 toFloat ().

qfloat16 QCborStreamReader:: toFloat16 () const

Returns the 16-bit half-precision floating point value of the current element.

This function does not perform any type conversions, including from other floating point types or from integer values. Therefore, it may only be called if isFloat16 () is true; calling it in any other condition is an error.

另请参阅 isFloat16 (), toFloat (),和 toDouble ().

float QCborStreamReader:: toFloat () const

Returns the 32-bit single-precision floating point value of the current element.

This function does not perform any type conversions, including from other floating point types or from integer values. Therefore, it may only be called if isFloat () is true; calling it in any other condition is an error.

另请参阅 isFloat (), toFloat16 (),和 toDouble ().

qint64 QCborStreamReader:: toInteger () const

Returns the integer value of the current element, be it negative, positive or zero. If the value is larger than 2 63 - 1 or smaller than -2 63 , the returned value will overflow and will have an incorrect sign. If handling those values is required, use toUnsignedInteger () 或 toNegativeInteger () 代替。

This function does not perform any type conversions, including from boolean or CBOR tag. Therefore, it may only be called if isInteger () is true; calling it in any other condition is an error.

另请参阅 isInteger (), toUnsignedInteger (),和 toNegativeInteger ().

QCborNegativeInteger QCborStreamReader:: toNegativeInteger () const

Returns the negative integer value of the current element. QCborNegativeValue is a 64-bit unsigned integer containing the absolute value of the negative number that was stored in the CBOR stream. Additionally, QCborNegativeValue(0) represents the number -2 64 .

This function does not perform any type conversions, including from boolean or CBOR tag. Therefore, it may only be called if isNegativeInteger () is true; calling it in any other condition is an error.

This function may be used to obtain numbers beyond the range of the return type of toInteger (). However, use of negative numbers smaller than -2 63 is extremely discouraged.

另请参阅 type (), toInteger (), isNegativeInteger (),和 isUnsignedInteger ().

QCborSimpleType QCborStreamReader:: toSimpleType () const

Returns value of the current simple type.

This function does not perform any type conversions, including from integer. Therefore, it may only be called if isSimpleType () is true; calling it in any other condition is an error.

另请参阅 isSimpleType (), isTrue (), isFalse (), isBool (), isNull (),和 isUndefined ().

QCborTag QCborStreamReader:: toTag () const

Returns the tag value of the current element.

This function does not perform any type conversions, including from integer. Therefore, it may only be called if isTag () is true; calling it in any other condition is an error.

Tags are 64-bit numbers attached to generic CBOR types that give them further meaning. For a list of known tags, see the QCborKnownTags 枚举。

另请参阅 isTag (), toInteger (),和 QCborKnownTags .

quint64 QCborStreamReader:: toUnsignedInteger () const

Returns the unsigned integer value of the current element.

This function does not perform any type conversions, including from boolean or CBOR tag. Therefore, it may only be called if isUnsignedInteger () is true; calling it in any other condition is an error.

This function may be used to obtain numbers beyond the range of the return type of toInteger ().

另请参阅 type (), toInteger (), isUnsignedInteger (),和 isNegativeInteger ().

QCborStreamReader::Type QCborStreamReader:: type () const

Returns the type of the current element. It is one of the valid types or Invalid.

另请参阅 isValid (), isUnsignedInteger (), isNegativeInteger (), isInteger (), isByteArray (), isString (), isArray (), isMap (), isTag (), isSimpleType (), isBool (), isFalse (), isTrue (), isNull (), isUndefined (), isFloat16 (), isFloat (),和 isDouble ().