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