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