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