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 Version 1 (Qt 1.x)
512 \value Qt_2_0 Version 2 (Qt 2.0)
513 \value Qt_2_1 Version 3 (Qt 2.1, 2.2, 2.3)
514 \value Qt_3_0 Version 4 (Qt 3.0)
515 \value Qt_3_1 Version 5 (Qt 3.1, 3.2)
516 \value Qt_3_3 Version 6 (Qt 3.3)
517 \value Qt_4_0 Version 7 (Qt 4.0, Qt 4.1)
518 \value Qt_4_1 Version 7 (Qt 4.0, Qt 4.1)
519 \value Qt_4_2 Version 8 (Qt 4.2)
520 \value Qt_4_3 Version 9 (Qt 4.3)
521 \value Qt_4_4 Version 10 (Qt 4.4)
522 \value Qt_4_5 Version 11 (Qt 4.5)
523 \value Qt_4_6 Version 12 (Qt 4.6, Qt 4.7, Qt 4.8)
524 \value Qt_4_7 Same as Qt_4_6.
525 \value Qt_4_8 Same as Qt_4_6.
526 \value Qt_4_9 Same as Qt_4_6.
527 \value Qt_5_0 Version 13 (Qt 5.0)
528 \value Qt_5_1 Version 14 (Qt 5.1)
529 \value Qt_5_2 Version 15 (Qt 5.2)
530 \value Qt_5_3 Same as Qt_5_2
531 \value Qt_5_4 Version 16 (Qt 5.4)
532 \value Qt_5_5 Same as Qt_5_4
533 \value Qt_5_6 Version 17 (Qt 5.6)
534 \value Qt_5_7 Same as Qt_5_6
535 \value Qt_5_8 Same as Qt_5_6
536 \value Qt_5_9 Same as Qt_5_6
537 \value Qt_5_10 Same as Qt_5_6
538 \value Qt_5_11 Same as Qt_5_6
539 \value Qt_5_12 Version 18 (Qt 5.12)
540 \value Qt_5_13 Version 19 (Qt 5.13)
541 \value Qt_5_14 Same as Qt_5_13
542 \value Qt_5_15 Same as Qt_5_13
543 \value Qt_6_0 Version 20 (Qt 6.0)
544 \value Qt_6_1 Same as Qt_6_0
545 \value Qt_6_2 Same as Qt_6_0
546 \value Qt_6_3 Same as Qt_6_0
547 \value Qt_6_4 Same as Qt_6_0
548 \value Qt_6_5 Same as Qt_6_0
549 \value Qt_6_6 Version 21 (Qt 6.6)
550 \value Qt_6_7 Version 22 (Qt 6.7)
551 \value Qt_6_8 Same as Qt_6_7
552 \value Qt_6_9 Same as Qt_6_7
553 \value Qt_6_10 Same as Qt_6_7
554 \value Qt_6_11 Same as Qt_6_10
555 \omitvalue Qt_DefaultCompiledVersion
556
557 \sa setVersion(), version()
558*/
559
560/*!
561 \fn int QDataStream::version() const
562
563 Returns the version number of the data serialization format.
564
565 \sa setVersion(), Version
566*/
567
568/*!
569 \fn void QDataStream::setVersion(int v)
570
571 Sets the version number of the data serialization format to \a v,
572 a value of the \l Version enum.
573
574 You don't \e have to set a version if you are using the current
575 version of Qt, but for your own custom binary formats we
576 recommend that you do; see \l{Versioning} in the Detailed
577 Description.
578
579 To accommodate new functionality, the datastream serialization
580 format of some Qt classes has changed in some versions of Qt. If
581 you want to read data that was created by an earlier version of
582 Qt, or write data that can be read by a program that was compiled
583 with an earlier version of Qt, use this function to modify the
584 serialization format used by QDataStream.
585
586 The \l Version enum provides symbolic constants for the different
587 versions of Qt. For example:
588
589 \snippet code/src_corelib_io_qdatastream.cpp 5
590
591 \sa version(), Version
592*/
593
594/*!
595 \since 5.7
596
597 Starts a new read transaction on the stream.
598
599 Defines a restorable point within the sequence of read operations. For
600 sequential devices, read data will be duplicated internally to allow
601 recovery in case of incomplete reads. For random-access devices,
602 this function saves the current position of the stream. Call
603 commitTransaction(), rollbackTransaction(), or abortTransaction() to
604 finish the current transaction.
605
606 Once a transaction is started, subsequent calls to this function will make
607 the transaction recursive. Inner transactions act as agents of the
608 outermost transaction (i.e., report the status of read operations to the
609 outermost transaction, which can restore the position of the stream).
610
611 \note Restoring to the point of the nested startTransaction() call is not
612 supported.
613
614 When an error occurs during a transaction (including an inner transaction
615 failing), reading from the data stream is suspended (all subsequent read
616 operations return empty/zero values) and subsequent inner transactions are
617 forced to fail. Starting a new outermost transaction recovers from this
618 state. This behavior makes it unnecessary to error-check every read
619 operation separately.
620
621 \sa commitTransaction(), rollbackTransaction(), abortTransaction()
622*/
623
624void QDataStream::startTransaction()
625{
627
628 if (++transactionDepth == 1) {
629 dev->startTransaction();
630 resetStatus();
631 }
632}
633
634/*!
635 \since 5.7
636
637 Completes a read transaction. Returns \c true if no read errors have
638 occurred during the transaction; otherwise returns \c false.
639
640 If called on an inner transaction, committing will be postponed until
641 the outermost commitTransaction(), rollbackTransaction(), or
642 abortTransaction() call occurs.
643
644 Otherwise, if the stream status indicates reading past the end of the
645 data, this function restores the stream data to the point of the
646 startTransaction() call. When this situation occurs, you need to wait for
647 more data to arrive, after which you start a new transaction. If the data
648 stream has read corrupt data or any of the inner transactions was aborted,
649 this function aborts the transaction.
650
651 \sa startTransaction(), rollbackTransaction(), abortTransaction()
652*/
653
654bool QDataStream::commitTransaction()
655{
657 if (--transactionDepth == 0) {
659
660 if (q_status == ReadPastEnd) {
661 dev->rollbackTransaction();
662 return false;
663 }
664 dev->commitTransaction();
665 }
666 return q_status == Ok;
667}
668
669/*!
670 \since 5.7
671
672 Reverts a read transaction.
673
674 This function is commonly used to rollback the transaction when an
675 incomplete read was detected prior to committing the transaction.
676
677 If called on an inner transaction, reverting is delegated to the outermost
678 transaction, and subsequently started inner transactions are forced to
679 fail.
680
681 For the outermost transaction, restores the stream data to the point of
682 the startTransaction() call. If the data stream has read corrupt data or
683 any of the inner transactions was aborted, this function aborts the
684 transaction.
685
686 If the preceding stream operations were successful, sets the status of the
687 data stream to \value ReadPastEnd.
688
689 \sa startTransaction(), commitTransaction(), abortTransaction()
690*/
691
692void QDataStream::rollbackTransaction()
693{
694 setStatus(ReadPastEnd);
695
697 if (--transactionDepth != 0)
698 return;
699
701 if (q_status == ReadPastEnd)
702 dev->rollbackTransaction();
703 else
704 dev->commitTransaction();
705}
706
707/*!
708 \since 5.7
709
710 Aborts a read transaction.
711
712 This function is commonly used to discard the transaction after
713 higher-level protocol errors or loss of stream synchronization.
714
715 If called on an inner transaction, aborting is delegated to the outermost
716 transaction, and subsequently started inner transactions are forced to
717 fail.
718
719 For the outermost transaction, discards the restoration point and any
720 internally duplicated data of the stream. Will not affect the current
721 read position of the stream.
722
723 Sets the status of the data stream to \value ReadCorruptData.
724
725 \sa startTransaction(), commitTransaction(), rollbackTransaction()
726*/
727
728void QDataStream::abortTransaction()
729{
730 q_status = ReadCorruptData;
731
733 if (--transactionDepth != 0)
734 return;
735
737 dev->commitTransaction();
738}
739
740/*!
741 \internal
742*/
743bool QDataStream::isDeviceTransactionStarted() const
744{
745 return dev && dev->isTransactionStarted();
746}
747
748/*****************************************************************************
749 QDataStream read functions
750 *****************************************************************************/
751
752/*!
753 \internal
754*/
755
756qint64 QDataStream::readBlock(char *data, qint64 len)
757{
758 // Disable reads on failure in transacted stream
759 if (q_status != Ok && dev->isTransactionStarted())
760 return -1;
761
762 const qint64 readResult = dev->read(data, len);
763 if (readResult != len)
764 setStatus(ReadPastEnd);
765 return readResult;
766}
767
768/*!
769 \fn QDataStream &QDataStream::operator>>(std::nullptr_t &ptr)
770 \since 5.9
771 \overload
772
773 Simulates reading a \c{std::nullptr_t} from the stream into \a ptr and
774 returns a reference to the stream. This function does not actually read
775 anything from the stream, as \c{std::nullptr_t} values are stored as 0
776 bytes.
777*/
778
779/*!
780 \fn QDataStream &QDataStream::operator>>(quint8 &i)
781 \overload
782
783 Reads an unsigned byte from the stream into \a i, and returns a
784 reference to the stream.
785*/
786
787/*!
788 Reads a signed byte from the stream into \a i, and returns a
789 reference to the stream.
790*/
791
792QDataStream &QDataStream::operator>>(qint8 &i)
793{
794 i = 0;
796 char c;
797 if (readBlock(&c, 1) == 1)
798 i = qint8(c);
799 return *this;
800}
801
802
803/*!
804 \fn QDataStream &QDataStream::operator>>(quint16 &i)
805 \overload
806
807 Reads an unsigned 16-bit integer from the stream into \a i, and
808 returns a reference to the stream.
809*/
810
811/*!
812 \overload
813
814 Reads a signed 16-bit integer from the stream into \a i, and
815 returns a reference to the stream.
816*/
817
818QDataStream &QDataStream::operator>>(qint16 &i)
819{
820 i = 0;
822 if (readBlock(reinterpret_cast<char *>(&i), 2) != 2) {
823 i = 0;
824 } else {
825 if (!noswap) {
826 i = qbswap(i);
827 }
828 }
829 return *this;
830}
831
832
833/*!
834 \fn QDataStream &QDataStream::operator>>(quint32 &i)
835 \overload
836
837 Reads an unsigned 32-bit integer from the stream into \a i, and
838 returns a reference to the stream.
839*/
840
841/*!
842 \overload
843
844 Reads a signed 32-bit integer from the stream into \a i, and
845 returns a reference to the stream.
846*/
847
848QDataStream &QDataStream::operator>>(qint32 &i)
849{
850 i = 0;
852 if (readBlock(reinterpret_cast<char *>(&i), 4) != 4) {
853 i = 0;
854 } else {
855 if (!noswap) {
856 i = qbswap(i);
857 }
858 }
859 return *this;
860}
861
862/*!
863 \fn QDataStream &QDataStream::operator>>(quint64 &i)
864 \overload
865
866 Reads an unsigned 64-bit integer from the stream, into \a i, and
867 returns a reference to the stream.
868*/
869
870/*!
871 \overload
872
873 Reads a signed 64-bit integer from the stream into \a i, and
874 returns a reference to the stream.
875*/
876
877QDataStream &QDataStream::operator>>(qint64 &i)
878{
879 i = qint64(0);
881 if (version() < 6) {
882 quint32 i1, i2;
883 *this >> i2 >> i1;
884 i = ((quint64)i1 << 32) + i2;
885 } else {
886 if (readBlock(reinterpret_cast<char *>(&i), 8) != 8) {
887 i = qint64(0);
888 } else {
889 if (!noswap) {
890 i = qbswap(i);
891 }
892 }
893 }
894 return *this;
895}
896
897/*!
898 Reads a boolean value from the stream into \a i. Returns a
899 reference to the stream.
900*/
901QDataStream &QDataStream::operator>>(bool &i)
902{
903 qint8 v;
904 *this >> v;
905 i = !!v;
906 return *this;
907}
908
909/*!
910 \overload
911
912 Reads a floating point number from the stream into \a f,
913 using the standard IEEE 754 format. Returns a reference to the
914 stream.
915
916 \sa setFloatingPointPrecision()
917*/
918
919QDataStream &QDataStream::operator>>(float &f)
920{
921 if (version() >= QDataStream::Qt_4_6
922 && floatingPointPrecision() == QDataStream::DoublePrecision) {
923 double d;
924 *this >> d;
925 f = d;
926 return *this;
927 }
928
929 f = 0.0f;
931 if (readBlock(reinterpret_cast<char *>(&f), 4) != 4) {
932 f = 0.0f;
933 } else {
934 if (!noswap) {
935 union {
936 float val1;
937 quint32 val2;
938 } x;
939 x.val2 = qbswap(*reinterpret_cast<quint32 *>(&f));
940 f = x.val1;
941 }
942 }
943 return *this;
944}
945
946/*!
947 \overload
948
949 Reads a floating point number from the stream into \a f,
950 using the standard IEEE 754 format. Returns a reference to the
951 stream.
952
953 \sa setFloatingPointPrecision()
954*/
955
956QDataStream &QDataStream::operator>>(double &f)
957{
958 if (version() >= QDataStream::Qt_4_6
959 && floatingPointPrecision() == QDataStream::SinglePrecision) {
960 float d;
961 *this >> d;
962 f = d;
963 return *this;
964 }
965
966 f = 0.0;
968 if (readBlock(reinterpret_cast<char *>(&f), 8) != 8) {
969 f = 0.0;
970 } else {
971 if (!noswap) {
972 union {
973 double val1;
974 quint64 val2;
975 } x;
976 x.val2 = qbswap(*reinterpret_cast<quint64 *>(&f));
977 f = x.val1;
978 }
979 }
980 return *this;
981}
982
983
984/*!
985 \overload
986
987 Reads string \a s from the stream and returns a reference to the stream.
988
989 The string is deserialized using \c{readBytes()} where the serialization
990 format is a \c quint32 length specifier first, followed by that many bytes
991 of data. The resulting string is always '\\0'-terminated.
992
993 Space for the string is allocated using \c{new []} -- the caller must
994 destroy it with \c{delete []}.
995
996 \sa readBytes(), readRawData()
997*/
998
999QDataStream &QDataStream::operator>>(char *&s)
1000{
1001 qint64 len = 0;
1002 return readBytes(s, len);
1003}
1004
1005/*!
1006 \overload
1007 \since 6.0
1008
1009 Reads a 16bit wide char from the stream into \a c and
1010 returns a reference to the stream.
1011*/
1012QDataStream &QDataStream::operator>>(char16_t &c)
1013{
1014 quint16 u;
1015 *this >> u;
1016 c = char16_t(u);
1017 return *this;
1018}
1019
1020/*!
1021 \overload
1022 \since 6.0
1023
1024 Reads a 32bit wide character from the stream into \a c and
1025 returns a reference to the stream.
1026*/
1027QDataStream &QDataStream::operator>>(char32_t &c)
1028{
1029 quint32 u;
1030 *this >> u;
1031 c = char32_t(u);
1032 return *this;
1033}
1034
1035/*!
1036 \relates QChar
1037
1038 Reads a char from the stream \a in into char \a chr.
1039
1040 \sa {Serializing Qt Data Types}
1041*/
1042QDataStream &operator>>(QDataStream &in, QChar &chr)
1043{
1044 quint16 u;
1045 in >> u;
1046 chr.unicode() = char16_t(u);
1047 return in;
1048}
1049
1050#if QT_DEPRECATED_SINCE(6, 11)
1051
1052/*!
1053 \deprecated [6.11] Use an overload that takes qint64 length instead.
1054*/
1055QDataStream &QDataStream::readBytes(char *&s, uint &l)
1056{
1057 qint64 length = 0;
1058 (void)readBytes(s, length);
1059 if (length != qint64(uint(length))) {
1060 setStatus(SizeLimitExceeded); // Cannot store length in l
1061 delete[] s;
1062 l = 0;
1063 return *this;
1064 }
1065 l = uint(length);
1066 return *this;
1067}
1068
1069#endif // QT_DEPRECATED_SINCE(6, 11)
1070
1071/*!
1072 \since 6.7
1073 Reads the buffer \a s from the stream and returns a reference to
1074 the stream.
1075
1076 The buffer \a s is allocated using \c{new []}. Destroy it with the
1077 \c{delete []} operator.
1078
1079 The \a l parameter is set to the length of the buffer. If the
1080 string read is empty, \a l is set to 0 and \a s is set to \nullptr.
1081
1082 The serialization format is a length specifier first, then \a l
1083 bytes of data. The length specifier is one quint32 if the version
1084 is less than 6.7 or if the number of elements is less than 0xfffffffe
1085 (2^32 -2), otherwise there is an extend value 0xfffffffe followed by
1086 one quint64 with the actual value. In addition for containers that
1087 support isNull(), it is encoded as a single quint32 with all bits
1088 set and no data.
1089
1090 \sa readRawData(), writeBytes()
1091*/
1092
1093QDataStream &QDataStream::readBytes(char *&s, qint64 &l)
1094{
1095 s = nullptr;
1096 l = 0;
1098
1099 qint64 length = readQSizeType(*this);
1100 if (length == 0)
1101 return *this;
1102
1103 qsizetype len = qsizetype(length);
1104 if (length != len || length < 0) {
1105 setStatus(SizeLimitExceeded); // Cannot store len
1106 return *this;
1107 }
1108
1109 qsizetype step = (dev->bytesAvailable() >= len) ? len : 1024 * 1024;
1110 qsizetype allocated = 0;
1111 std::unique_ptr<char[]> curBuf = nullptr;
1112
1113 constexpr qsizetype StepIncreaseThreshold = std::numeric_limits<qsizetype>::max() / 2;
1114 do {
1115 qsizetype blockSize = qMin(step, len - allocated);
1116 const qsizetype n = allocated + blockSize + 1;
1117 if (const auto prevBuf = std::exchange(curBuf, q20::make_unique_for_overwrite<char[]>(n)))
1118 memcpy(curBuf.get(), prevBuf.get(), allocated);
1119 if (readBlock(curBuf.get() + allocated, blockSize) != blockSize)
1120 return *this;
1121 allocated += blockSize;
1122 if (step <= StepIncreaseThreshold)
1123 step *= 2;
1124 } while (allocated < len);
1125
1126 s = curBuf.release();
1127 s[len] = '\0';
1128 l = len;
1129 return *this;
1130}
1131
1132/*!
1133 Reads at most \a len bytes from the stream into \a s and returns the number of
1134 bytes read. If an error occurs, this function returns -1.
1135
1136 The buffer \a s must be preallocated. The data is \e not decoded.
1137
1138 \sa readBytes(), QIODevice::read(), writeRawData()
1139*/
1140
1141qint64 QDataStream::readRawData(char *s, qint64 len)
1142{
1144 return readBlock(s, len);
1145}
1146
1147/*! \fn template <class T1, class T2> QDataStream &operator>>(QDataStream &in, std::pair<T1, T2> &pair)
1148 \since 6.0
1149 \relates QDataStream
1150
1151 Reads a pair from stream \a in into \a pair.
1152
1153 This function requires the T1 and T2 types to implement \c operator>>().
1154
1155 \sa {Serializing Qt Data Types}
1156*/
1157
1158/*****************************************************************************
1159 QDataStream write functions
1160 *****************************************************************************/
1161
1162/*!
1163 \fn QDataStream &QDataStream::operator<<(std::nullptr_t ptr)
1164 \since 5.9
1165 \overload
1166
1167 Simulates writing a \c{std::nullptr_t}, \a ptr, to the stream and returns a
1168 reference to the stream. This function does not actually write anything to
1169 the stream, as \c{std::nullptr_t} values are stored as 0 bytes.
1170*/
1171
1172/*!
1173 \fn QDataStream &QDataStream::operator<<(quint8 i)
1174 \overload
1175
1176 Writes an unsigned byte, \a i, to the stream and returns a
1177 reference to the stream.
1178*/
1179
1180/*!
1181 Writes a signed byte, \a i, to the stream and returns a reference
1182 to the stream.
1183*/
1184
1185QDataStream &QDataStream::operator<<(qint8 i)
1186{
1188 if (!dev->putChar(i))
1189 q_status = WriteFailed;
1190 return *this;
1191}
1192
1193
1194/*!
1195 \fn QDataStream &QDataStream::operator<<(quint16 i)
1196 \overload
1197
1198 Writes an unsigned 16-bit integer, \a i, to the stream and returns
1199 a reference to the stream.
1200*/
1201
1202/*!
1203 \overload
1204
1205 Writes a signed 16-bit integer, \a i, to the stream and returns a
1206 reference to the stream.
1207*/
1208
1209QDataStream &QDataStream::operator<<(qint16 i)
1210{
1212 if (!noswap) {
1213 i = qbswap(i);
1214 }
1215 if (dev->write((char *)&i, sizeof(qint16)) != sizeof(qint16))
1216 q_status = WriteFailed;
1217 return *this;
1218}
1219
1220/*!
1221 \overload
1222
1223 Writes a signed 32-bit integer, \a i, to the stream and returns a
1224 reference to the stream.
1225*/
1226
1227QDataStream &QDataStream::operator<<(qint32 i)
1228{
1230 if (!noswap) {
1231 i = qbswap(i);
1232 }
1233 if (dev->write((char *)&i, sizeof(qint32)) != sizeof(qint32))
1234 q_status = WriteFailed;
1235 return *this;
1236}
1237
1238/*!
1239 \fn QDataStream &QDataStream::operator<<(quint64 i)
1240 \overload
1241
1242 Writes an unsigned 64-bit integer, \a i, to the stream and returns a
1243 reference to the stream.
1244*/
1245
1246/*!
1247 \overload
1248
1249 Writes a signed 64-bit integer, \a i, to the stream and returns a
1250 reference to the stream.
1251*/
1252
1253QDataStream &QDataStream::operator<<(qint64 i)
1254{
1256 if (version() < 6) {
1257 quint32 i1 = i & 0xffffffff;
1258 quint32 i2 = i >> 32;
1259 *this << i2 << i1;
1260 } else {
1261 if (!noswap) {
1262 i = qbswap(i);
1263 }
1264 if (dev->write((char *)&i, sizeof(qint64)) != sizeof(qint64))
1265 q_status = WriteFailed;
1266 }
1267 return *this;
1268}
1269
1270/*!
1271 \fn QDataStream &QDataStream::operator<<(quint32 i)
1272 \overload
1273
1274 Writes an unsigned integer, \a i, to the stream as a 32-bit
1275 unsigned integer (quint32). Returns a reference to the stream.
1276*/
1277
1278/*!
1279 \fn QDataStream &QDataStream::operator<<(bool i)
1280 \overload
1281
1282 Writes a boolean value, \a i, to the stream. Returns a reference
1283 to the stream.
1284*/
1285
1286/*!
1287 \overload
1288
1289 Writes a floating point number, \a f, to the stream using
1290 the standard IEEE 754 format. Returns a reference to the stream.
1291
1292 \sa setFloatingPointPrecision()
1293*/
1294
1295QDataStream &QDataStream::operator<<(float f)
1296{
1297 if (version() >= QDataStream::Qt_4_6
1298 && floatingPointPrecision() == QDataStream::DoublePrecision) {
1299 *this << double(f);
1300 return *this;
1301 }
1302
1304 float g = f; // fixes float-on-stack problem
1305 if (!noswap) {
1306 union {
1307 float val1;
1308 quint32 val2;
1309 } x;
1310 x.val1 = g;
1311 x.val2 = qbswap(x.val2);
1312
1313 if (dev->write((char *)&x.val2, sizeof(float)) != sizeof(float))
1314 q_status = WriteFailed;
1315 return *this;
1316 }
1317
1318 if (dev->write((char *)&g, sizeof(float)) != sizeof(float))
1319 q_status = WriteFailed;
1320 return *this;
1321}
1322
1323
1324/*!
1325 \overload
1326
1327 Writes a floating point number, \a f, to the stream using
1328 the standard IEEE 754 format. Returns a reference to the stream.
1329
1330 \sa setFloatingPointPrecision()
1331*/
1332
1333QDataStream &QDataStream::operator<<(double f)
1334{
1335 if (version() >= QDataStream::Qt_4_6
1336 && floatingPointPrecision() == QDataStream::SinglePrecision) {
1337 *this << float(f);
1338 return *this;
1339 }
1340
1342 if (noswap) {
1343 if (dev->write((char *)&f, sizeof(double)) != sizeof(double))
1344 q_status = WriteFailed;
1345 } else {
1346 union {
1347 double val1;
1348 quint64 val2;
1349 } x;
1350 x.val1 = f;
1351 x.val2 = qbswap(x.val2);
1352 if (dev->write((char *)&x.val2, sizeof(double)) != sizeof(double))
1353 q_status = WriteFailed;
1354 }
1355 return *this;
1356}
1357
1358
1359/*!
1360 \overload
1361
1362 Writes the '\\0'-terminated string \a s to the stream and returns a
1363 reference to the stream.
1364
1365 The string is serialized using \c{writeBytes()}.
1366
1367 \sa writeBytes(), writeRawData()
1368*/
1369
1370QDataStream &QDataStream::operator<<(const char *s)
1371{
1372 // Include null terminator, unless s itself is null
1373 const qint64 len = s ? qint64(qstrlen(s)) + 1 : 0;
1374 writeBytes(s, len);
1375 return *this;
1376}
1377
1378/*!
1379 \overload
1380 \since 6.0
1381
1382 Writes a character, \a c, to the stream. Returns a reference to
1383 the stream
1384*/
1385QDataStream &QDataStream::operator<<(char16_t c)
1386{
1387 return *this << qint16(c);
1388}
1389
1390/*!
1391 \overload
1392 \since 6.0
1393
1394 Writes a character, \a c, to the stream. Returns a reference to
1395 the stream
1396*/
1397QDataStream &QDataStream::operator<<(char32_t c)
1398{
1399 return *this << qint32(c);
1400}
1401
1402/*!
1403 \relates QChar
1404
1405 Writes the char \a chr to the stream \a out.
1406
1407 \sa {Serializing Qt Data Types}
1408*/
1409QDataStream &operator<<(QDataStream &out, QChar chr)
1410{
1411 out << quint16(chr.unicode());
1412 return out;
1413}
1414
1415/*!
1416 \fn QDataStream::operator bool() const
1417 \since 6.10
1418
1419 Returns whether this stream has no errors (\l status() returns \l{Ok}).
1420*/
1421
1422/*!
1423 Writes the length specifier \a len and the buffer \a s to the
1424 stream and returns a reference to the stream.
1425
1426 The \a len is serialized as a quint32 and an optional quint64,
1427 followed by \a len bytes from \a s. Note that the data is
1428 \e not encoded.
1429
1430 \sa writeRawData(), readBytes()
1431*/
1432
1433QDataStream &QDataStream::writeBytes(const char *s, qint64 len)
1434{
1435 if (len < 0) {
1436 q_status = WriteFailed;
1437 return *this;
1438 }
1440 // Write length then, if any, content
1441 if (writeQSizeType(*this, len) && len > 0)
1442 writeRawData(s, len);
1443 return *this;
1444}
1445
1446/*!
1447 Writes \a len bytes from \a s to the stream. Returns the
1448 number of bytes actually written, or -1 on error.
1449 The data is \e not encoded.
1450
1451 \sa writeBytes(), QIODevice::write(), readRawData()
1452*/
1453
1454qint64 QDataStream::writeRawData(const char *s, qint64 len)
1455{
1457 qint64 ret = dev->write(s, len);
1458 if (ret != len)
1459 q_status = WriteFailed;
1460 return ret;
1461}
1462
1463/*!
1464 \since 4.1
1465
1466 Skips \a len bytes from the device. Returns the number of bytes
1467 actually skipped, or -1 on error.
1468
1469 This is equivalent to calling readRawData() on a buffer of length
1470 \a len and ignoring the buffer.
1471
1472 \sa QIODevice::seek()
1473*/
1474qint64 QDataStream::skipRawData(qint64 len)
1475{
1477 if (q_status != Ok && dev->isTransactionStarted())
1478 return -1;
1479
1480 const qint64 skipResult = dev->skip(len);
1481 if (skipResult != len)
1482 setStatus(ReadPastEnd);
1483 return skipResult;
1484}
1485
1486/*!
1487 \fn template <class T1, class T2> QDataStream &operator<<(QDataStream &out, const std::pair<T1, T2> &pair)
1488 \since 6.0
1489 \relates QDataStream
1490
1491 Writes the pair \a pair to stream \a out.
1492
1493 This function requires the T1 and T2 types to implement \c operator<<().
1494
1495 \sa {Serializing Qt Data Types}
1496*/
1497
1498QT_END_NAMESPACE
1499
1500#endif // QT_NO_DATASTREAM
#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