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
qdatastream.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
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 "qdatastream.h"
6
7#if !defined(QT_NO_DATASTREAM) || defined(QT_BOOTSTRAPPED)
8#include "qbuffer.h"
9#include "qfloat16.h"
10#include "qstring.h"
11#include <stdio.h>
12#include <ctype.h>
13#include <stdlib.h>
14#include "qendian.h"
15
16#include <QtCore/q20memory.h>
17
19
20constexpr quint32 QDataStream::NullCode;
21constexpr quint32 QDataStream::ExtendedSize;
22
23/*!
24 \class QDataStream
25 \inmodule QtCore
26 \ingroup qtserialization
27 \reentrant
28 \brief The QDataStream class provides serialization of binary data
29 to a QIODevice.
30
31 \ingroup io
32
33
34 A data stream is a binary stream of encoded information which is
35 100% independent of the host computer's operating system, CPU or
36 byte order. For example, a data stream that is written by a PC
37 under Windows can be read by a Sun SPARC running Solaris.
38
39 You can also use a data stream to read/write \l{raw}{raw
40 unencoded binary data}. If you want a "parsing" input stream, see
41 QTextStream.
42
43 The QDataStream class implements the serialization of C++'s basic
44 data types, like \c char, \c short, \c int, \c{char *}, etc.
45 Serialization of more complex data is accomplished by breaking up
46 the data into primitive units.
47
48 A data stream cooperates closely with a QIODevice. A QIODevice
49 represents an input/output medium one can read data from and write
50 data to. The QFile class is an example of an I/O device.
51
52 Example (write binary data to a stream):
53
54 \snippet code/src_corelib_io_qdatastream.cpp 0
55
56 Example (read binary data from a stream):
57
58 \snippet code/src_corelib_io_qdatastream.cpp 1
59
60 Each item written to the stream is written in a predefined binary
61 format that varies depending on the item's type. Supported Qt
62 types include QBrush, QColor, QDateTime, QFont, QPixmap, QString,
63 QVariant and many others. For the complete list of all Qt types
64 supporting data streaming see \l{Serializing Qt Data Types}.
65
66 For integers it is best to always cast to a Qt integer type for
67 writing, and to read back into the same Qt integer type. This
68 ensures that you get integers of the size you want and insulates
69 you from compiler and platform differences.
70
71 Enumerations can be serialized through QDataStream without the
72 need of manually defining streaming operators. Enum classes are
73 serialized using the declared size.
74
75 The initial I/O device is usually set in the constructor, but can be
76 changed with setDevice(). If you've reached the end of the data
77 (or if there is no I/O device set) atEnd() will return true.
78
79 \section1 Serializing containers and strings
80
81 The serialization format is a length specifier first, then \a l bytes of data.
82 The length specifier is one quint32 if the version is less than 6.7 or if the
83 number of elements is less than 0xfffffffe (2^32 -2). Otherwise there is
84 an extend value 0xfffffffe followed by one quint64 with the actual value.
85 In addition for containers that support isNull(), it is encoded as a single
86 quint32 with all bits set and no data.
87
88 To take one example, if the string size fits into 32 bits, a \c{char *} string
89 is written as a 32-bit integer equal to the length of the string, including
90 the '\\0' byte, followed by all the characters of the string, including the
91 '\\0' byte. If the string size is greater, the value 0xffffffffe is written
92 as a marker of an extended size, followed by 64 bits of the actual size.
93 When reading a \c {char *} string, 4 bytes are read first. If the value is
94 not equal to 0xffffffffe (the marker of extended size), then these 4 bytes
95 are treated as the 32 bit size of the string. Otherwise, the next 8 bytes are
96 read and treated as a 64 bit size of the string. Then, all the characters for
97 the \c {char *} string, including the '\\0' terminator, are read.
98
99 \section1 Versioning
100
101 QDataStream's binary format has evolved since Qt 1.0, and is
102 likely to continue evolving to reflect changes done in Qt. When
103 inputting or outputting complex types, it's very important to
104 make sure that the same version of the stream (version()) is used
105 for reading and writing. If you need both forward and backward
106 compatibility, you can hardcode the version number in the
107 application:
108
109 \snippet code/src_corelib_io_qdatastream.cpp 2
110
111 If you are producing a new binary data format, such as a file
112 format for documents created by your application, you could use a
113 QDataStream to write the data in a portable format. Typically, you
114 would write a brief header containing a magic string and a version
115 number to give yourself room for future expansion. For example:
116
117 \snippet code/src_corelib_io_qdatastream.cpp 3
118
119 Then read it in with:
120
121 \snippet code/src_corelib_io_qdatastream.cpp 4
122
123 You can select which byte order to use when serializing data. The
124 default setting is big-endian (MSB first). Changing it to little-endian
125 breaks the portability (unless the reader also changes to
126 little-endian). We recommend keeping this setting unless you have
127 special requirements.
128
129 \target raw
130 \section1 Reading and Writing Raw Binary Data
131
132 You may wish to read/write your own raw binary data to/from the
133 data stream directly. Data may be read from the stream into a
134 preallocated \c{char *} using readRawData(). Similarly data can be
135 written to the stream using writeRawData(). Note that any
136 encoding/decoding of the data must be done by you.
137
138 A similar pair of functions is readBytes() and writeBytes(). These
139 differ from their \e raw counterparts as follows: readBytes()
140 reads a quint32 which is taken to be the length of the data to be
141 read, then that number of bytes is read into the preallocated
142 \c{char *}; writeBytes() writes a quint32 containing the length of the
143 data, followed by the data. Note that any encoding/decoding of
144 the data (apart from the length quint32) must be done by you.
145
146 \section1 Reading and Writing Qt Collection Classes
147
148 The Qt container classes can also be serialized to a QDataStream.
149 These include QList, QSet, QHash, and QMap.
150 The stream operators are declared as non-members of the classes.
151
152 \target Serializing Qt Classes
153 \section1 Reading and Writing Other Qt Classes
154
155 In addition to the overloaded stream operators documented here,
156 any Qt classes that you might want to serialize to a QDataStream
157 will have appropriate stream operators declared as non-member of
158 the class:
159
160 \snippet code/src_corelib_serialization_qdatastream.cpp 0
161
162 For example, here are the stream operators declared as non-members
163 of the QImage class:
164
165 \snippet code/src_corelib_serialization_qdatastream.cpp 1
166
167 To see if your favorite Qt class has similar stream operators
168 defined, check the \b {Related Non-Members} section of the
169 class's documentation page.
170
171 \section1 Using Read Transactions
172
173 When a data stream operates on an asynchronous device, the chunks of data
174 can arrive at arbitrary points in time. The QDataStream class implements
175 a transaction mechanism that provides the ability to read the data
176 atomically with a series of stream operators. As an example, you can
177 handle incomplete reads from a socket by using a transaction in a slot
178 connected to the readyRead() signal:
179
180 \snippet code/src_corelib_io_qdatastream.cpp 6
181
182 If no full packet is received, this code restores the stream to the
183 initial position, after which you need to wait for more data to arrive.
184
185 \section1 Corruption and Security
186
187 QDataStream is not resilient against corrupted data inputs and should
188 therefore not be used for security-sensitive situations, even when using
189 transactions. Transactions will help determine if a valid input can
190 currently be decoded with the data currently available on an asynchronous
191 device, but will assume that the data that is available is correctly
192 formed.
193
194 Additionally, many QDataStream demarshalling operators will allocate memory
195 based on information found in the stream. Those operators perform no
196 verification on whether the requested amount of memory is reasonable or if
197 it is compatible with the amount of data available in the stream (example:
198 demarshalling a QByteArray or QString may see the request for allocation of
199 several gigabytes of data).
200
201 QDataStream should not be used on content whose provenance cannot be
202 trusted. Applications should be designed to attempt to decode only streams
203 whose provenance is at least as trustworthy as that of the application
204 itself or its plugins.
205
206 \sa QTextStream, QVariant
207*/
208
209/*!
210 \enum QDataStream::ByteOrder
211
212 The byte order used for reading/writing the data.
213
214 \value BigEndian Most significant byte first (the default)
215 \value LittleEndian Least significant byte first
216*/
217
218/*!
219 \enum QDataStream::FloatingPointPrecision
220
221 The precision of floating point numbers used for reading/writing the data. This will only have
222 an effect if the version of the data stream is Qt_4_6 or higher.
223
224 \warning The floating point precision must be set to the same value on the object that writes
225 and the object that reads the data stream.
226
227 \value SinglePrecision All floating point numbers in the data stream have 32-bit precision.
228 \value DoublePrecision All floating point numbers in the data stream have 64-bit precision.
229
230 \sa setFloatingPointPrecision(), floatingPointPrecision()
231*/
232
233/*!
234 \enum QDataStream::Status
235
236 This enum describes the current status of the data stream.
237
238 \value Ok The data stream is operating normally.
239 \value ReadPastEnd The data stream has read past the end of the
240 data in the underlying device.
241 \value ReadCorruptData The data stream has read corrupt data.
242 \value WriteFailed The data stream cannot write to the underlying device.
243 \value [since 6.7] SizeLimitExceeded The data stream cannot read or write
244 the data because its size is larger than supported
245 by the current platform. This can happen, for
246 example, when trying to read more that 2 GiB of
247 data on a 32-bit platform.
248*/
249
250/*****************************************************************************
251 QDataStream member functions
252 *****************************************************************************/
253
254#define Q_VOID
255
256#undef CHECK_STREAM_PRECOND
257#ifndef QT_NO_DEBUG
258#define CHECK_STREAM_PRECOND(retVal)
259 if (!dev) {
260 qWarning("QDataStream: No device");
261 return retVal;
262 }
263#else
264#define CHECK_STREAM_PRECOND(retVal)
265 if (!dev) {
266 return retVal;
267 }
268#endif
269
270#define CHECK_STREAM_WRITE_PRECOND(retVal)
272 if (q_status != Ok)
273 return retVal;
274
275#define CHECK_STREAM_TRANSACTION_PRECOND(retVal)
276 if (transactionDepth == 0) {
277 qWarning("QDataStream: No transaction in progress");
278 return retVal;
279 }
280
281/*!
282 Constructs a data stream that has no I/O device.
283
284 \sa setDevice()
285*/
286
287QDataStream::QDataStream()
288{
289}
290
291/*!
292 Constructs a data stream that uses the I/O device \a d.
293
294 \sa setDevice(), device()
295*/
296
297QDataStream::QDataStream(QIODevice *d)
298{
299 dev = d; // set device
300}
301
302/*!
303 \fn QDataStream::QDataStream(QByteArray *a, OpenMode mode)
304
305 Constructs a data stream that operates on a byte array, \a a. The
306 \a mode describes how the device is to be used.
307
308 Alternatively, you can use QDataStream(const QByteArray &) if you
309 just want to read from a byte array.
310
311 Since QByteArray is not a QIODevice subclass, internally a QBuffer
312 is created to wrap the byte array.
313*/
314
315QDataStream::QDataStream(QByteArray *a, OpenMode flags)
316{
317 QBuffer *buf = new QBuffer(a);
318#ifndef QT_NO_QOBJECT
319 buf->blockSignals(true);
320#endif
321 buf->open(flags);
322 dev = buf;
323 owndev = true;
324}
325
326/*!
327 Constructs a read-only data stream that operates on byte array \a a.
328 Use QDataStream(QByteArray*, int) if you want to write to a byte
329 array.
330
331 Since QByteArray is not a QIODevice subclass, internally a QBuffer
332 is created to wrap the byte array.
333*/
334QDataStream::QDataStream(const QByteArray &a)
335{
336 QBuffer *buf = new QBuffer;
337#ifndef QT_NO_QOBJECT
338 buf->blockSignals(true);
339#endif
340 buf->setData(a);
341 buf->open(QIODevice::ReadOnly);
342 dev = buf;
343 owndev = true;
344}
345
346/*!
347 Destroys the data stream.
348
349 The destructor will not affect the current I/O device, unless it is
350 an internal I/O device (e.g. a QBuffer) processing a QByteArray
351 passed in the \e constructor, in which case the internal I/O device
352 is destroyed.
353*/
354
355QDataStream::~QDataStream()
356{
357 if (owndev)
358 delete dev;
359}
360
361
362/*!
363 \fn QIODevice *QDataStream::device() const
364
365 Returns the I/O device currently set, or \nullptr if no
366 device is currently set.
367
368 \sa setDevice()
369*/
370
371/*!
372 void QDataStream::setDevice(QIODevice *d)
373
374 Sets the I/O device to \a d, which can be \nullptr
375 to unset to current I/O device.
376
377 \sa device()
378*/
379
380void QDataStream::setDevice(QIODevice *d)
381{
382 if (owndev) {
383 delete dev;
384 owndev = false;
385 }
386 dev = d;
387}
388
389/*!
390 \fn bool QDataStream::atEnd() const
391
392 Returns \c true if the I/O device has reached the end position (end of
393 the stream or file) or if there is no I/O device set; otherwise
394 returns \c false.
395
396 \sa QIODevice::atEnd()
397*/
398
399bool QDataStream::atEnd() const
400{
401 return dev ? dev->atEnd() : true;
402}
403
404/*!
405 \fn QDataStream::FloatingPointPrecision QDataStream::floatingPointPrecision() const
406
407 Returns the floating point precision of the data stream.
408
409 \since 4.6
410
411 \sa FloatingPointPrecision, setFloatingPointPrecision()
412*/
413
414/*!
415 Sets the floating point precision of the data stream to \a precision. If the floating point precision is
416 DoublePrecision and the version of the data stream is Qt_4_6 or higher, all floating point
417 numbers will be written and read with 64-bit precision. If the floating point precision is
418 SinglePrecision and the version is Qt_4_6 or higher, all floating point numbers will be written
419 and read with 32-bit precision.
420
421 For versions prior to Qt_4_6, the precision of floating point numbers in the data stream depends
422 on the stream operator called.
423
424 The default is DoublePrecision.
425
426 Note that this property does not affect the serialization or deserialization of \c qfloat16
427 instances.
428
429 \warning This property must be set to the same value on the object that writes and the object
430 that reads the data stream.
431
432 \since 4.6
433*/
434void QDataStream::setFloatingPointPrecision(QDataStream::FloatingPointPrecision precision)
435{
436 fpPrecision = precision;
437}
438
439/*!
440 \fn QDataStream::status() const
441
442 Returns the status of the data stream.
443
444 \sa Status, setStatus(), resetStatus()
445*/
446
447/*!
448 Resets the status of the data stream.
449
450 \sa Status, status(), setStatus()
451*/
452void QDataStream::resetStatus()
453{
454 q_status = Ok;
455}
456
457/*!
458 Sets the status of the data stream to the \a status given.
459
460 Subsequent calls to setStatus() are ignored until resetStatus()
461 is called.
462
463 \sa Status, status(), resetStatus()
464*/
465void QDataStream::setStatus(Status status)
466{
467 if (q_status == Ok)
468 q_status = status;
469}
470
471/*!
472 \fn int QDataStream::byteOrder() const
473
474 Returns the current byte order setting -- either BigEndian or
475 LittleEndian.
476
477 \sa setByteOrder()
478*/
479
480/*!
481 Sets the serialization byte order to \a bo.
482
483 The \a bo parameter can be QDataStream::BigEndian or
484 QDataStream::LittleEndian.
485
486 The default setting is big-endian. We recommend leaving this
487 setting unless you have special requirements.
488
489 \sa byteOrder()
490*/
491
492void QDataStream::setByteOrder(ByteOrder bo)
493{
494#if QT_VERSION < QT_VERSION_CHECK(7, 0, 0) && !defined(QT_BOOTSTRAPPED)
495 // accessed by inline byteOrder() prior to Qt 6.8
496 byteorder = bo;
497#endif
498 if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
499 noswap = (bo == BigEndian);
500 else
501 noswap = (bo == LittleEndian);
502}
503
504
505/*!
506 \enum QDataStream::Version
507
508 This enum provides symbolic synonyms for the data serialization
509 format version numbers.
510
511 \value Qt_1_0
512 \value Qt_2_0
513 \value Qt_2_1
514 \value Qt_3_0
515 \value Qt_3_1
516 \value Qt_3_3
517 \value Qt_4_0
518 \value Qt_4_1
519 \value Qt_4_2
520 \value Qt_4_3
521 \value Qt_4_4
522 \value Qt_4_5
523 \value Qt_4_6
524 \value Qt_4_7
525 \value Qt_4_8
526 \value Qt_4_9
527 \value Qt_5_0
528 \value Qt_5_1
529 \value Qt_5_2
530 \value Qt_5_3
531 \value Qt_5_4
532 \value Qt_5_5
533 \value Qt_5_6
534 \value Qt_5_7
535 \value Qt_5_8
536 \value Qt_5_9
537 \value Qt_5_10
538 \value Qt_5_11
539 \value Qt_5_12
540 \value Qt_5_13
541 \value Qt_5_14
542 \value Qt_5_15
543 \value Qt_6_0
544 \value Qt_6_1
545 \value Qt_6_2
546 \value Qt_6_3
547 \value Qt_6_4
548 \value Qt_6_5
549 \value Qt_6_6
550 \value Qt_6_7
551 \value Qt_6_8
552 \value Qt_6_9
553 \value Qt_6_10
554 \value Qt_6_11
555 \value Qt_6_12
556 \omitvalue Qt_DefaultCompiledVersion
557
558 \sa setVersion(), version()
559*/
560
561/*!
562 \fn int QDataStream::version() const
563
564 Returns the version number of the data serialization format.
565
566 \sa setVersion(), Version
567*/
568
569/*!
570 \fn void QDataStream::setVersion(int v)
571
572 Sets the version number of the data serialization format to \a v,
573 a value of the \l Version enum.
574
575 You don't \e have to set a version if you are using the current
576 version of Qt, but for your own custom binary formats we
577 recommend that you do; see \l{Versioning} in the Detailed
578 Description.
579
580 To accommodate new functionality, the datastream serialization
581 format of some Qt classes has changed in some versions of Qt. If
582 you want to read data that was created by an earlier version of
583 Qt, or write data that can be read by a program that was compiled
584 with an earlier version of Qt, use this function to modify the
585 serialization format used by QDataStream.
586
587 The \l Version enum provides symbolic constants for the different
588 versions of Qt. For example:
589
590 \snippet code/src_corelib_io_qdatastream.cpp 5
591
592 \sa version(), Version
593*/
594
595/*!
596 \since 5.7
597
598 Starts a new read transaction on the stream.
599
600 Defines a restorable point within the sequence of read operations. For
601 sequential devices, read data will be duplicated internally to allow
602 recovery in case of incomplete reads. For random-access devices,
603 this function saves the current position of the stream. Call
604 commitTransaction(), rollbackTransaction(), or abortTransaction() to
605 finish the current transaction.
606
607 Once a transaction is started, subsequent calls to this function will make
608 the transaction recursive. Inner transactions act as agents of the
609 outermost transaction (i.e., report the status of read operations to the
610 outermost transaction, which can restore the position of the stream).
611
612 \note Restoring to the point of the nested startTransaction() call is not
613 supported.
614
615 When an error occurs during a transaction (including an inner transaction
616 failing), reading from the data stream is suspended (all subsequent read
617 operations return empty/zero values) and subsequent inner transactions are
618 forced to fail. Starting a new outermost transaction recovers from this
619 state. This behavior makes it unnecessary to error-check every read
620 operation separately.
621
622 \sa commitTransaction(), rollbackTransaction(), abortTransaction()
623*/
624
625void QDataStream::startTransaction()
626{
628
629 if (++transactionDepth == 1) {
630 dev->startTransaction();
631 resetStatus();
632 }
633}
634
635/*!
636 \since 5.7
637
638 Completes a read transaction. Returns \c true if no read errors have
639 occurred during the transaction; otherwise returns \c false.
640
641 If called on an inner transaction, committing will be postponed until
642 the outermost commitTransaction(), rollbackTransaction(), or
643 abortTransaction() call occurs.
644
645 Otherwise, if the stream status indicates reading past the end of the
646 data, this function restores the stream data to the point of the
647 startTransaction() call. When this situation occurs, you need to wait for
648 more data to arrive, after which you start a new transaction. If the data
649 stream has read corrupt data or any of the inner transactions was aborted,
650 this function aborts the transaction.
651
652 \sa startTransaction(), rollbackTransaction(), abortTransaction()
653*/
654
655bool QDataStream::commitTransaction()
656{
658 if (--transactionDepth == 0) {
660
661 if (q_status == ReadPastEnd) {
662 dev->rollbackTransaction();
663 return false;
664 }
665 dev->commitTransaction();
666 }
667 return q_status == Ok;
668}
669
670/*!
671 \since 5.7
672
673 Reverts a read transaction.
674
675 This function is commonly used to rollback the transaction when an
676 incomplete read was detected prior to committing the transaction.
677
678 If called on an inner transaction, reverting is delegated to the outermost
679 transaction, and subsequently started inner transactions are forced to
680 fail.
681
682 For the outermost transaction, restores the stream data to the point of
683 the startTransaction() call. If the data stream has read corrupt data or
684 any of the inner transactions was aborted, this function aborts the
685 transaction.
686
687 If the preceding stream operations were successful, sets the status of the
688 data stream to \value ReadPastEnd.
689
690 \sa startTransaction(), commitTransaction(), abortTransaction()
691*/
692
693void QDataStream::rollbackTransaction()
694{
695 setStatus(ReadPastEnd);
696
698 if (--transactionDepth != 0)
699 return;
700
702 if (q_status == ReadPastEnd)
703 dev->rollbackTransaction();
704 else
705 dev->commitTransaction();
706}
707
708/*!
709 \since 5.7
710
711 Aborts a read transaction.
712
713 This function is commonly used to discard the transaction after
714 higher-level protocol errors or loss of stream synchronization.
715
716 If called on an inner transaction, aborting is delegated to the outermost
717 transaction, and subsequently started inner transactions are forced to
718 fail.
719
720 For the outermost transaction, discards the restoration point and any
721 internally duplicated data of the stream. Will not affect the current
722 read position of the stream.
723
724 Sets the status of the data stream to \value ReadCorruptData.
725
726 \sa startTransaction(), commitTransaction(), rollbackTransaction()
727*/
728
729void QDataStream::abortTransaction()
730{
731 q_status = ReadCorruptData;
732
734 if (--transactionDepth != 0)
735 return;
736
738 dev->commitTransaction();
739}
740
741/*!
742 \internal
743*/
744bool QDataStream::isDeviceTransactionStarted() const
745{
746 return dev && dev->isTransactionStarted();
747}
748
749/*****************************************************************************
750 QDataStream read functions
751 *****************************************************************************/
752
753/*!
754 \internal
755*/
756
757qint64 QDataStream::readBlock(char *data, qint64 len)
758{
759 // Disable reads on failure in transacted stream
760 if (q_status != Ok && dev->isTransactionStarted())
761 return -1;
762
763 const qint64 readResult = dev->read(data, len);
764 if (readResult != len)
765 setStatus(ReadPastEnd);
766 return readResult;
767}
768
769/*!
770 \fn QDataStream &QDataStream::operator>>(std::nullptr_t &ptr)
771 \since 5.9
772 \overload
773
774 Simulates reading a \c{std::nullptr_t} from the stream into \a ptr and
775 returns a reference to the stream. This function does not actually read
776 anything from the stream, as \c{std::nullptr_t} values are stored as 0
777 bytes.
778*/
779
780/*!
781 \fn QDataStream &QDataStream::operator>>(quint8 &i)
782 \overload
783
784 Reads an unsigned byte from the stream into \a i, and returns a
785 reference to the stream.
786*/
787
788/*!
789 Reads a signed byte from the stream into \a i, and returns a
790 reference to the stream.
791*/
792
793QDataStream &QDataStream::operator>>(qint8 &i)
794{
795 i = 0;
797 char c;
798 if (readBlock(&c, 1) == 1)
799 i = qint8(c);
800 return *this;
801}
802
803
804/*!
805 \fn QDataStream &QDataStream::operator>>(quint16 &i)
806 \overload
807
808 Reads an unsigned 16-bit integer from the stream into \a i, and
809 returns a reference to the stream.
810*/
811
812/*!
813 \overload
814
815 Reads a signed 16-bit integer from the stream into \a i, and
816 returns a reference to the stream.
817*/
818
819QDataStream &QDataStream::operator>>(qint16 &i)
820{
821 i = 0;
823 if (readBlock(reinterpret_cast<char *>(&i), 2) != 2) {
824 i = 0;
825 } else {
826 if (!noswap) {
827 i = qbswap(i);
828 }
829 }
830 return *this;
831}
832
833
834/*!
835 \fn QDataStream &QDataStream::operator>>(quint32 &i)
836 \overload
837
838 Reads an unsigned 32-bit integer from the stream into \a i, and
839 returns a reference to the stream.
840*/
841
842/*!
843 \overload
844
845 Reads a signed 32-bit integer from the stream into \a i, and
846 returns a reference to the stream.
847*/
848
849QDataStream &QDataStream::operator>>(qint32 &i)
850{
851 i = 0;
853 if (readBlock(reinterpret_cast<char *>(&i), 4) != 4) {
854 i = 0;
855 } else {
856 if (!noswap) {
857 i = qbswap(i);
858 }
859 }
860 return *this;
861}
862
863/*!
864 \fn QDataStream &QDataStream::operator>>(quint64 &i)
865 \overload
866
867 Reads an unsigned 64-bit integer from the stream, into \a i, and
868 returns a reference to the stream.
869*/
870
871/*!
872 \overload
873
874 Reads a signed 64-bit integer from the stream into \a i, and
875 returns a reference to the stream.
876*/
877
878QDataStream &QDataStream::operator>>(qint64 &i)
879{
880 i = qint64(0);
882 if (version() < 6) {
883 quint32 i1, i2;
884 *this >> i2 >> i1;
885 i = ((quint64)i1 << 32) + i2;
886 } else {
887 if (readBlock(reinterpret_cast<char *>(&i), 8) != 8) {
888 i = qint64(0);
889 } else {
890 if (!noswap) {
891 i = qbswap(i);
892 }
893 }
894 }
895 return *this;
896}
897
898/*!
899 Reads a boolean value from the stream into \a i. Returns a
900 reference to the stream.
901*/
902QDataStream &QDataStream::operator>>(bool &i)
903{
904 qint8 v;
905 *this >> v;
906 i = !!v;
907 return *this;
908}
909
910/*!
911 \overload
912
913 Reads a floating point number from the stream into \a f,
914 using the standard IEEE 754 format. Returns a reference to the
915 stream.
916
917 \sa setFloatingPointPrecision()
918*/
919
920QDataStream &QDataStream::operator>>(float &f)
921{
922 if (version() >= QDataStream::Qt_4_6
923 && floatingPointPrecision() == QDataStream::DoublePrecision) {
924 double d;
925 *this >> d;
926 f = d;
927 return *this;
928 }
929
930 f = 0.0f;
932 if (readBlock(reinterpret_cast<char *>(&f), 4) != 4) {
933 f = 0.0f;
934 } else {
935 if (!noswap) {
936 union {
937 float val1;
938 quint32 val2;
939 } x;
940 x.val2 = qbswap(*reinterpret_cast<quint32 *>(&f));
941 f = x.val1;
942 }
943 }
944 return *this;
945}
946
947/*!
948 \overload
949
950 Reads a floating point number from the stream into \a f,
951 using the standard IEEE 754 format. Returns a reference to the
952 stream.
953
954 \sa setFloatingPointPrecision()
955*/
956
957QDataStream &QDataStream::operator>>(double &f)
958{
959 if (version() >= QDataStream::Qt_4_6
960 && floatingPointPrecision() == QDataStream::SinglePrecision) {
961 float d;
962 *this >> d;
963 f = d;
964 return *this;
965 }
966
967 f = 0.0;
969 if (readBlock(reinterpret_cast<char *>(&f), 8) != 8) {
970 f = 0.0;
971 } else {
972 if (!noswap) {
973 union {
974 double val1;
975 quint64 val2;
976 } x;
977 x.val2 = qbswap(*reinterpret_cast<quint64 *>(&f));
978 f = x.val1;
979 }
980 }
981 return *this;
982}
983
984
985/*!
986 \overload
987
988 Reads string \a s from the stream and returns a reference to the stream.
989
990 The string is deserialized using \c{readBytes()} where the serialization
991 format is a \c quint32 length specifier first, followed by that many bytes
992 of data. The resulting string is always '\\0'-terminated.
993
994 Space for the string is allocated using \c{new []} -- the caller must
995 destroy it with \c{delete []}.
996
997 \sa readBytes(), readRawData()
998*/
999
1000QDataStream &QDataStream::operator>>(char *&s)
1001{
1002 qint64 len = 0;
1003 return readBytes(s, len);
1004}
1005
1006/*!
1007 \overload
1008 \since 6.0
1009
1010 Reads a 16bit wide char from the stream into \a c and
1011 returns a reference to the stream.
1012*/
1013QDataStream &QDataStream::operator>>(char16_t &c)
1014{
1015 quint16 u;
1016 *this >> u;
1017 c = char16_t(u);
1018 return *this;
1019}
1020
1021/*!
1022 \overload
1023 \since 6.0
1024
1025 Reads a 32bit wide character from the stream into \a c and
1026 returns a reference to the stream.
1027*/
1028QDataStream &QDataStream::operator>>(char32_t &c)
1029{
1030 quint32 u;
1031 *this >> u;
1032 c = char32_t(u);
1033 return *this;
1034}
1035
1036/*!
1037 \relates QChar
1038
1039 Reads a char from the stream \a in into char \a chr.
1040
1041 \sa {Serializing Qt Data Types}
1042*/
1043QDataStream &operator>>(QDataStream &in, QChar &chr)
1044{
1045 quint16 u;
1046 in >> u;
1047 chr.unicode() = char16_t(u);
1048 return in;
1049}
1050
1051#if QT_DEPRECATED_SINCE(6, 11)
1052
1053/*!
1054 \deprecated [6.11] Use an overload that takes qint64 length instead.
1055*/
1056QDataStream &QDataStream::readBytes(char *&s, uint &l)
1057{
1058 qint64 length = 0;
1059 (void)readBytes(s, length);
1060 if (length != qint64(uint(length))) {
1061 setStatus(SizeLimitExceeded); // Cannot store length in l
1062 delete[] s;
1063 l = 0;
1064 return *this;
1065 }
1066 l = uint(length);
1067 return *this;
1068}
1069
1070#endif // QT_DEPRECATED_SINCE(6, 11)
1071
1072/*!
1073 \since 6.7
1074 Reads the buffer \a s from the stream and returns a reference to
1075 the stream.
1076
1077 The buffer \a s is allocated using \c{new []}. Destroy it with the
1078 \c{delete []} operator.
1079
1080 The \a l parameter is set to the length of the buffer. If the
1081 string read is empty, \a l is set to 0 and \a s is set to \nullptr.
1082
1083 The serialization format is a length specifier first, then \a l
1084 bytes of data. The length specifier is one quint32 if the version
1085 is less than 6.7 or if the number of elements is less than 0xfffffffe
1086 (2^32 -2), otherwise there is an extend value 0xfffffffe followed by
1087 one quint64 with the actual value. In addition for containers that
1088 support isNull(), it is encoded as a single quint32 with all bits
1089 set and no data.
1090
1091 \sa readRawData(), writeBytes()
1092*/
1093
1094QDataStream &QDataStream::readBytes(char *&s, qint64 &l)
1095{
1096 s = nullptr;
1097 l = 0;
1099
1100 qint64 length = readQSizeType(*this);
1101 if (length == 0)
1102 return *this;
1103
1104 qsizetype len = qsizetype(length);
1105 if (length != len || length < 0) {
1106 setStatus(SizeLimitExceeded); // Cannot store len
1107 return *this;
1108 }
1109
1110 qsizetype step = (dev->bytesAvailable() >= len) ? len : 1024 * 1024;
1111 qsizetype allocated = 0;
1112 std::unique_ptr<char[]> curBuf = nullptr;
1113
1114 constexpr qsizetype StepIncreaseThreshold = std::numeric_limits<qsizetype>::max() / 2;
1115 do {
1116 qsizetype blockSize = qMin(step, len - allocated);
1117 const qsizetype n = allocated + blockSize + 1;
1118 if (const auto prevBuf = std::exchange(curBuf, q20::make_unique_for_overwrite<char[]>(n)))
1119 memcpy(curBuf.get(), prevBuf.get(), allocated);
1120 if (readBlock(curBuf.get() + allocated, blockSize) != blockSize)
1121 return *this;
1122 allocated += blockSize;
1123 if (step <= StepIncreaseThreshold)
1124 step *= 2;
1125 } while (allocated < len);
1126
1127 s = curBuf.release();
1128 s[len] = '\0';
1129 l = len;
1130 return *this;
1131}
1132
1133/*!
1134 Reads at most \a len bytes from the stream into \a s and returns the number of
1135 bytes read. If an error occurs, this function returns -1.
1136
1137 The buffer \a s must be preallocated. The data is \e not decoded.
1138
1139 \sa readBytes(), QIODevice::read(), writeRawData()
1140*/
1141
1142qint64 QDataStream::readRawData(char *s, qint64 len)
1143{
1145 return readBlock(s, len);
1146}
1147
1148/*! \fn template <class T1, class T2> QDataStream &operator>>(QDataStream &in, std::pair<T1, T2> &pair)
1149 \since 6.0
1150 \relates QDataStream
1151
1152 Reads a pair from stream \a in into \a pair.
1153
1154 This function requires the T1 and T2 types to implement \c operator>>().
1155
1156 \sa {Serializing Qt Data Types}
1157*/
1158
1159/*****************************************************************************
1160 QDataStream write functions
1161 *****************************************************************************/
1162
1163/*!
1164 \fn QDataStream &QDataStream::operator<<(std::nullptr_t ptr)
1165 \since 5.9
1166 \overload
1167
1168 Simulates writing a \c{std::nullptr_t}, \a ptr, to the stream and returns a
1169 reference to the stream. This function does not actually write anything to
1170 the stream, as \c{std::nullptr_t} values are stored as 0 bytes.
1171*/
1172
1173/*!
1174 \fn QDataStream &QDataStream::operator<<(quint8 i)
1175 \overload
1176
1177 Writes an unsigned byte, \a i, to the stream and returns a
1178 reference to the stream.
1179*/
1180
1181/*!
1182 Writes a signed byte, \a i, to the stream and returns a reference
1183 to the stream.
1184*/
1185
1186QDataStream &QDataStream::operator<<(qint8 i)
1187{
1189 if (!dev->putChar(i))
1190 q_status = WriteFailed;
1191 return *this;
1192}
1193
1194
1195/*!
1196 \fn QDataStream &QDataStream::operator<<(quint16 i)
1197 \overload
1198
1199 Writes an unsigned 16-bit integer, \a i, to the stream and returns
1200 a reference to the stream.
1201*/
1202
1203/*!
1204 \overload
1205
1206 Writes a signed 16-bit integer, \a i, to the stream and returns a
1207 reference to the stream.
1208*/
1209
1210QDataStream &QDataStream::operator<<(qint16 i)
1211{
1213 if (!noswap) {
1214 i = qbswap(i);
1215 }
1216 if (dev->write((char *)&i, sizeof(qint16)) != sizeof(qint16))
1217 q_status = WriteFailed;
1218 return *this;
1219}
1220
1221/*!
1222 \overload
1223
1224 Writes a signed 32-bit integer, \a i, to the stream and returns a
1225 reference to the stream.
1226*/
1227
1228QDataStream &QDataStream::operator<<(qint32 i)
1229{
1231 if (!noswap) {
1232 i = qbswap(i);
1233 }
1234 if (dev->write((char *)&i, sizeof(qint32)) != sizeof(qint32))
1235 q_status = WriteFailed;
1236 return *this;
1237}
1238
1239/*!
1240 \fn QDataStream &QDataStream::operator<<(quint64 i)
1241 \overload
1242
1243 Writes an unsigned 64-bit integer, \a i, to the stream and returns a
1244 reference to the stream.
1245*/
1246
1247/*!
1248 \overload
1249
1250 Writes a signed 64-bit integer, \a i, to the stream and returns a
1251 reference to the stream.
1252*/
1253
1254QDataStream &QDataStream::operator<<(qint64 i)
1255{
1257 if (version() < 6) {
1258 quint32 i1 = i & 0xffffffff;
1259 quint32 i2 = i >> 32;
1260 *this << i2 << i1;
1261 } else {
1262 if (!noswap) {
1263 i = qbswap(i);
1264 }
1265 if (dev->write((char *)&i, sizeof(qint64)) != sizeof(qint64))
1266 q_status = WriteFailed;
1267 }
1268 return *this;
1269}
1270
1271/*!
1272 \fn QDataStream &QDataStream::operator<<(quint32 i)
1273 \overload
1274
1275 Writes an unsigned integer, \a i, to the stream as a 32-bit
1276 unsigned integer (quint32). Returns a reference to the stream.
1277*/
1278
1279/*!
1280 \fn QDataStream &QDataStream::operator<<(bool i)
1281 \overload
1282
1283 Writes a boolean value, \a i, to the stream. Returns a reference
1284 to the stream.
1285*/
1286
1287/*!
1288 \overload
1289
1290 Writes a floating point number, \a f, to the stream using
1291 the standard IEEE 754 format. Returns a reference to the stream.
1292
1293 \sa setFloatingPointPrecision()
1294*/
1295
1296QDataStream &QDataStream::operator<<(float f)
1297{
1298 if (version() >= QDataStream::Qt_4_6
1299 && floatingPointPrecision() == QDataStream::DoublePrecision) {
1300 *this << double(f);
1301 return *this;
1302 }
1303
1305 float g = f; // fixes float-on-stack problem
1306 if (!noswap) {
1307 union {
1308 float val1;
1309 quint32 val2;
1310 } x;
1311 x.val1 = g;
1312 x.val2 = qbswap(x.val2);
1313
1314 if (dev->write((char *)&x.val2, sizeof(float)) != sizeof(float))
1315 q_status = WriteFailed;
1316 return *this;
1317 }
1318
1319 if (dev->write((char *)&g, sizeof(float)) != sizeof(float))
1320 q_status = WriteFailed;
1321 return *this;
1322}
1323
1324
1325/*!
1326 \overload
1327
1328 Writes a floating point number, \a f, to the stream using
1329 the standard IEEE 754 format. Returns a reference to the stream.
1330
1331 \sa setFloatingPointPrecision()
1332*/
1333
1334QDataStream &QDataStream::operator<<(double f)
1335{
1336 if (version() >= QDataStream::Qt_4_6
1337 && floatingPointPrecision() == QDataStream::SinglePrecision) {
1338 *this << float(f);
1339 return *this;
1340 }
1341
1343 if (noswap) {
1344 if (dev->write((char *)&f, sizeof(double)) != sizeof(double))
1345 q_status = WriteFailed;
1346 } else {
1347 union {
1348 double val1;
1349 quint64 val2;
1350 } x;
1351 x.val1 = f;
1352 x.val2 = qbswap(x.val2);
1353 if (dev->write((char *)&x.val2, sizeof(double)) != sizeof(double))
1354 q_status = WriteFailed;
1355 }
1356 return *this;
1357}
1358
1359
1360/*!
1361 \overload
1362
1363 Writes the '\\0'-terminated string \a s to the stream and returns a
1364 reference to the stream.
1365
1366 The string is serialized using \c{writeBytes()}.
1367
1368 \sa writeBytes(), writeRawData()
1369*/
1370
1371QDataStream &QDataStream::operator<<(const char *s)
1372{
1373 // Include null terminator, unless s itself is null
1374 const qint64 len = s ? qint64(qstrlen(s)) + 1 : 0;
1375 writeBytes(s, len);
1376 return *this;
1377}
1378
1379/*!
1380 \overload
1381 \since 6.0
1382
1383 Writes a character, \a c, to the stream. Returns a reference to
1384 the stream
1385*/
1386QDataStream &QDataStream::operator<<(char16_t c)
1387{
1388 return *this << qint16(c);
1389}
1390
1391/*!
1392 \overload
1393 \since 6.0
1394
1395 Writes a character, \a c, to the stream. Returns a reference to
1396 the stream
1397*/
1398QDataStream &QDataStream::operator<<(char32_t c)
1399{
1400 return *this << qint32(c);
1401}
1402
1403/*!
1404 \relates QChar
1405
1406 Writes the char \a chr to the stream \a out.
1407
1408 \sa {Serializing Qt Data Types}
1409*/
1410QDataStream &operator<<(QDataStream &out, QChar chr)
1411{
1412 out << quint16(chr.unicode());
1413 return out;
1414}
1415
1416/*!
1417 \fn QDataStream::operator bool() const
1418 \since 6.10
1419
1420 Returns whether this stream has no errors (\l status() returns \l{Ok}).
1421*/
1422
1423/*!
1424 Writes the length specifier \a len and the buffer \a s to the
1425 stream and returns a reference to the stream.
1426
1427 The \a len is serialized as a quint32 and an optional quint64,
1428 followed by \a len bytes from \a s. Note that the data is
1429 \e not encoded.
1430
1431 \sa writeRawData(), readBytes()
1432*/
1433
1434QDataStream &QDataStream::writeBytes(const char *s, qint64 len)
1435{
1436 if (len < 0) {
1437 q_status = WriteFailed;
1438 return *this;
1439 }
1441 // Write length then, if any, content
1442 if (writeQSizeType(*this, len) && len > 0)
1443 writeRawData(s, len);
1444 return *this;
1445}
1446
1447/*!
1448 Writes \a len bytes from \a s to the stream. Returns the
1449 number of bytes actually written, or -1 on error.
1450 The data is \e not encoded.
1451
1452 \sa writeBytes(), QIODevice::write(), readRawData()
1453*/
1454
1455qint64 QDataStream::writeRawData(const char *s, qint64 len)
1456{
1458 qint64 ret = dev->write(s, len);
1459 if (ret != len)
1460 q_status = WriteFailed;
1461 return ret;
1462}
1463
1464/*!
1465 \since 4.1
1466
1467 Skips \a len bytes from the device. Returns the number of bytes
1468 actually skipped, or -1 on error.
1469
1470 This is equivalent to calling readRawData() on a buffer of length
1471 \a len and ignoring the buffer.
1472
1473 \sa QIODevice::seek()
1474*/
1475qint64 QDataStream::skipRawData(qint64 len)
1476{
1478 if (q_status != Ok && dev->isTransactionStarted())
1479 return -1;
1480
1481 const qint64 skipResult = dev->skip(len);
1482 if (skipResult != len)
1483 setStatus(ReadPastEnd);
1484 return skipResult;
1485}
1486
1487/*!
1488 \fn template <class T1, class T2> QDataStream &operator<<(QDataStream &out, const std::pair<T1, T2> &pair)
1489 \since 6.0
1490 \relates QDataStream
1491
1492 Writes the pair \a pair to stream \a out.
1493
1494 This function requires the T1 and T2 types to implement \c operator<<().
1495
1496 \sa {Serializing Qt Data Types}
1497*/
1498
1499QT_END_NAMESPACE
1500
1501#endif // QT_NO_DATASTREAM
Combined button and popup list for selecting options.
#define CHECK_STREAM_WRITE_PRECOND(retVal)
#define CHECK_STREAM_PRECOND(retVal)
#define CHECK_STREAM_TRANSACTION_PRECOND(retVal)
QDataStream & operator>>(QDataStream &s, QKeyCombination &combination)
#define Q_VOID
Definition qiodevice.cpp:46