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