1
/****************************************************************************
3
** Copyright (C) 1992-2005 Trolltech AS. All rights reserved.
5
** This file is part of the core module of the Qt Toolkit.
7
** This file may be distributed under the terms of the Q Public License
8
** as defined by Trolltech AS of Norway and appearing in the file
9
** LICENSE.QPL included in the packaging of this file.
11
** This file may be distributed and/or modified under the terms of the
12
** GNU General Public License version 2 as published by the Free Software
13
** Foundation and appearing in the file LICENSE.GPL included in the
14
** packaging of this file.
16
** See http://www.trolltech.com/pricing.html or email sales@trolltech.com for
17
** information about Qt Commercial License Agreements.
18
** See http://www.trolltech.com/qpl/ for QPL licensing information.
19
** See http://www.trolltech.com/gpl/ for GPL licensing information.
21
** Contact info@trolltech.com if any conditions of this licensing are
24
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
25
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
27
****************************************************************************/
29
#include "qdatastream.h"
31
#ifndef QT_NO_DATASTREAM
41
\brief The QDataStream class provides serialization of binary data
47
A data stream is a binary stream of encoded information which is
48
100% independent of the host computer's operating system, CPU or
49
byte order. For example, a data stream that is written by a PC
50
under Windows can be read by a Sun SPARC running Solaris.
52
You can also use a data stream to read/write \l{raw}{raw
53
unencoded binary data}. If you want a "parsing" input stream, see
56
The QDataStream class implements the serialization of C++'s basic
57
data types, like \c char, \c short, \c int, \c{char *}, etc.
58
Serialization of more complex data is accomplished by breaking up
59
the data into primitive units.
61
A data stream cooperates closely with a QIODevice. A QIODevice
62
represents an input/output medium one can read data from and write
63
data to. The QFile class is an example of an I/O device.
65
Example (write binary data to a stream):
68
QFile file("file.dat");
69
file.open(QIODevice::WriteOnly);
70
QDataStream out(&file); // we will serialize the data into the file
71
out << "the answer is"; // serialize a string
72
out << (qint32)42; // serialize an integer
75
Example (read binary data from a stream):
78
QFile file("file.dat");
79
file.open(QIODevice::ReadOnly);
80
QDataStream in(&file); // read the data serialized from the file
83
in >> str >> a; // extract "the answer is" and 42
86
Each item written to the stream is written in a predefined binary
87
format that varies depending on the item's type. Supported Qt
88
types include QBrush, QColor, QDateTime, QFont, QPixmap, QString,
89
QVariant and many others. For the complete list of all Qt types
90
supporting data streaming see the \l{Format of the QDataStream
93
For integers it is best to always cast to a Qt integer type for
94
writing, and to read back into the same Qt integer type. This
95
ensures that you get integers of the size you want and insulates
96
you from compiler and platform differences.
98
To take one example, a \c{char *} string is written as a 32-bit
99
integer equal to the length of the string including the '\\0' byte,
100
followed by all the characters of the string including the
101
'\\0' byte. When reading a \c{char *} string, 4 bytes are read to
102
create the 32-bit length value, then that many characters for the
103
\c {char *} string including the '\\0' terminator are read.
105
The initial I/O device is usually set in the constructor, but can be
106
changed with setDevice(). If you've reached the end of the data
107
(or if there is no I/O device set) atEnd() will return true.
111
QDataStream's binary format has evolved since Qt 1.0, and is
112
likely to continue evolving to reflect changes done in Qt. When
113
inputting or outputting complex types, it's very important to
114
make sure that the same version of the stream (version()) is used
115
for reading and writing. If you need both forward and backward
116
compatibility, you can hardcode the version number in the
120
stream.setVersion(QDataStream::Qt_4_0);
123
If you are producing a new binary data format, such as a file
124
format for documents created by your application, you could use a
125
QDataStream to write the data in a portable format. Typically, you
126
would write a brief header containing a magic string and a version
127
number to give yourself room for future expansion. For example:
130
QFile file("file.xxx");
131
file.open(QIODevice::WriteOnly);
132
QDataStream out(&file);
134
// Write a header with a "magic number" and a version
135
out << (quint32)0xA0B0C0D0;
138
out.setVersion(QDataStream::Qt_4_0);
141
out << lots_of_interesting_data;
144
Then read it in with:
147
QFile file("file.xxx");
148
file.open(QIODevice::ReadOnly);
149
QDataStream in(&file);
151
// Read and check the header
154
if (magic != 0xA0B0C0D0)
155
return XXX_BAD_FILE_FORMAT;
161
return XXX_BAD_FILE_TOO_OLD;
163
return XXX_BAD_FILE_TOO_NEW;
166
in.setVersion(QDataStream::Qt_3_2);
168
in.setVersion(QDataStream::Qt_4_0);
171
in >> lots_of_interesting_data;
173
in >> data_new_in_XXX_version_1_2;
174
in >> other_interesting_data;
177
You can select which byte order to use when serializing data. The
178
default setting is big endian (MSB first). Changing it to little
179
endian breaks the portability (unless the reader also changes to
180
little endian). We recommend keeping this setting unless you have
181
special requirements.
184
\section1 Reading and writing raw binary data
186
You may wish to read/write your own raw binary data to/from the
187
data stream directly. Data may be read from the stream into a
188
preallocated \c{char *} using readRawData(). Similarly data can be
189
written to the stream using writeRawData(). Note that any
190
encoding/decoding of the data must be done by you.
192
A similar pair of functions is readBytes() and writeBytes(). These
193
differ from their \e raw counterparts as follows: readBytes()
194
reads a quint32 which is taken to be the length of the data to be
195
read, then that number of bytes is read into the preallocated
196
\c{char *}; writeBytes() writes a quint32 containing the length of the
197
data, followed by the data. Note that any encoding/decoding of
198
the data (apart from the length quint32) must be done by you.
200
\sa QTextStream QVariant
204
\enum QDataStream::ByteOrder
206
The byte order used for reading/writing the data.
208
\value BigEndian Most significant byte first (the default)
209
\value LittleEndian Less significant byte first
213
\enum QDataStream::Status
215
This enum describes the current status of the data stream.
217
\value Ok The data stream is operating normally.
218
\value ReadPastEnd The data stream has read past the end of the
219
data in the underlying device.
220
\value ReadCorruptData The data stream has read corrupt data.
223
/*****************************************************************************
224
QDataStream member functions
225
*****************************************************************************/
228
#undef CHECK_STREAM_PRECOND
229
#define CHECK_STREAM_PRECOND(retVal) \
231
qWarning("QDataStream: No device"); \
235
#define CHECK_STREAM_PRECOND(retVal)
239
DefaultStreamVersion = 7
242
// ### 4.0: when streaming invalid QVariants, just the type should
243
// be written, no "data" after it
246
Constructs a data stream that has no I/O device.
251
QDataStream::QDataStream()
255
byteorder = BigEndian;
256
ver = DefaultStreamVersion;
257
noswap = QSysInfo::ByteOrder == QSysInfo::BigEndian;
262
Constructs a data stream that uses the I/O device \a d.
264
\warning If you use QSocket or QSocketDevice as the I/O device \a d
265
for reading data, you must make sure that enough data is available
266
on the socket for the operation to successfully proceed;
267
QDataStream does not have any means to handle or recover from
270
\sa setDevice(), device()
273
QDataStream::QDataStream(QIODevice *d)
275
dev = d; // set device
277
byteorder = BigEndian; // default byte order
278
ver = DefaultStreamVersion;
279
noswap = QSysInfo::ByteOrder == QSysInfo::BigEndian;
285
\fn QDataStream::QDataStream(QByteArray *array, int mode)
288
Constructs a data stream that operates on the given \a array. The
289
\a mode specifies how the byte array is to be used, and is
290
usually either \c QIODevice::ReadOnly or \c QIODevice::WriteOnly.
292
QDataStream::QDataStream(QByteArray *a, int mode)
294
QBuffer *buf = new QBuffer(a);
295
buf->open(QIODevice::OpenMode(mode));
298
byteorder = BigEndian;
299
ver = DefaultStreamVersion;
300
noswap = QSysInfo::ByteOrder == QSysInfo::BigEndian;
306
\fn QDataStream::QDataStream(QByteArray *a, QIODevice::OpenMode mode)
308
Constructs a data stream that operates on a byte array, \a a. The
309
\a mode describes how the device is to be used.
311
Alternatively, you can use QDataStream(const QByteArray &) if you
312
just want to read from a byte array.
314
Since QByteArray is not a QIODevice subclass, internally a QBuffer
315
is created to wrap the byte array.
318
QDataStream::QDataStream(QByteArray *a, QIODevice::OpenMode flags)
320
QBuffer *buf = new QBuffer(a);
324
byteorder = BigEndian;
325
ver = DefaultStreamVersion;
326
noswap = QSysInfo::ByteOrder == QSysInfo::BigEndian;
331
Constructs a read-only data stream that operates on byte array \a a.
332
Use QDataStream(QByteArray*, int) if you want to write to a byte
335
Since QByteArray is not a QIODevice subclass, internally a QBuffer
336
is created to wrap the byte array.
338
QDataStream::QDataStream(const QByteArray &a)
340
QBuffer *buf = new QBuffer;
342
buf->open(QIODevice::ReadOnly);
345
byteorder = BigEndian;
346
ver = DefaultStreamVersion;
347
noswap = QSysInfo::ByteOrder == QSysInfo::BigEndian;
352
Destroys the data stream.
354
The destructor will not affect the current I/O device, unless it is
355
an internal I/O device (e.g. a QBuffer) processing a QByteArray
356
passed in the \e constructor, in which case the internal I/O device
360
QDataStream::~QDataStream()
368
\fn QIODevice *QDataStream::device() const
370
Returns the I/O device currently set.
372
\sa setDevice(), unsetDevice()
376
void QDataStream::setDevice(QIODevice *d)
378
Sets the I/O device to \a d.
380
\sa device(), unsetDevice()
383
void QDataStream::setDevice(QIODevice *d)
393
Unsets the I/O device. This is the same as calling setDevice(0).
395
\sa device(), setDevice()
398
void QDataStream::unsetDevice()
405
\fn bool QDataStream::atEnd() const
407
Returns true if the I/O device has reached the end position (end of
408
the stream or file) or if there is no I/O device set; otherwise
411
\sa QIODevice::atEnd()
414
bool QDataStream::atEnd() const
416
return dev ? dev->atEnd() : true;
420
Returns the status of the data stream.
422
\sa Status setStatus() resetStatus()
425
QDataStream::Status QDataStream::status() const
431
Resets the status of the data stream.
433
\sa Status status() setStatus()
435
void QDataStream::resetStatus()
441
Sets the status of the data stream to the \a status given.
443
\sa Status status() resetStatus()
445
void QDataStream::setStatus(Status status)
451
/*!\fn bool QDataStream::eof() const
457
\fn int QDataStream::byteOrder() const
459
Returns the current byte order setting -- either \c BigEndian or
466
Sets the serialization byte order to \a bo.
468
The \a bo parameter can be \c QDataStream::BigEndian or \c
469
QDataStream::LittleEndian.
471
The default setting is big endian. We recommend leaving this
472
setting unless you have special requirements.
477
void QDataStream::setByteOrder(ByteOrder bo)
480
if (QSysInfo::ByteOrder == QSysInfo::BigEndian)
481
noswap = (byteorder == BigEndian);
483
noswap = (byteorder == LittleEndian);
488
\fn bool QDataStream::isPrintableData() const
490
In Qt 4, this function always returns false.
492
\sa setPrintableData()
496
\fn void QDataStream::setPrintableData(bool enable)
498
In Qt 3, this function enabled output in a human-readable
499
format if \a enable was false.
501
In Qt 4, QDataStream no longer provides a human-readable output.
502
This function does nothing.
506
\enum QDataStream::Version
508
This enum provides symbolic synonyms for the data serialization
509
format version numbers.
511
\value Qt_1_0 Version 1 (Qt 1.x)
512
\value Qt_2_0 Version 2 (Qt 2.0)
513
\value Qt_2_1 Version 3 (Qt 2.1, 2.2, 2.3)
514
\value Qt_3_0 Version 4 (Qt 3.0)
515
\value Qt_3_1 Version 5 (Qt 3.1, 3.2)
516
\value Qt_3_3 Version 6 (Qt 3.3)
517
\value Qt_4_0 Version 7 (Qt 4.0)
519
\sa setVersion(), version()
523
\fn int QDataStream::version() const
525
Returns the version number of the data serialization format.
527
\sa setVersion(), Version
531
\fn void QDataStream::setVersion(int v)
533
Sets the version number of the data serialization format to \a v.
535
You don't \e have to set a version if you are using the current
536
version of Qt, but for your own custom binary formats we
537
recommend that you do; see \l{Versioning} in the Detailed
540
In order to accommodate new functionality, the datastream
541
serialization format of some Qt classes has changed in some
542
versions of Qt. If you want to read data that was created by an
543
earlier version of Qt, or write data that can be read by a
544
program that was compiled with an earlier version of Qt, use this
545
function to modify the serialization format used by QDataStream.
548
\header \i Qt Version \i QDataStream Version
551
\row \i Qt 3.1, 3.2 \i 5
553
\row \i Qt 2.1, 2.2, 2.3 \i 3
558
The \l Version enum provides symbolic constants for the different
559
versions of Qt. For example:
562
QDataStream out(file);
563
out.setVersion(QDataStream::Qt_4_0);
566
\sa version(), Version
569
/*****************************************************************************
570
QDataStream read functions
571
*****************************************************************************/
574
\fn QDataStream &QDataStream::operator>>(quint8 &i)
577
Reads an unsigned byte from the stream into \a i, and returns a
578
reference to the stream.
582
Reads a signed byte from the stream into \a i, and returns a
583
reference to the stream.
586
QDataStream &QDataStream::operator>>(qint8 &i)
589
CHECK_STREAM_PRECOND(*this)
591
if (!dev->getChar(&c))
592
setStatus(ReadPastEnd);
600
\fn QDataStream &QDataStream::operator>>(quint16 &i)
603
Reads an unsigned 16-bit integer from the stream into \a i, and
604
returns a reference to the stream.
610
Reads a signed 16-bit integer from the stream into \a i, and
611
returns a reference to the stream.
614
QDataStream &QDataStream::operator>>(qint16 &i)
617
CHECK_STREAM_PRECOND(*this)
619
if (dev->read((char *)&i, 2) != 2) {
621
setStatus(ReadPastEnd);
624
register uchar *p = (uchar *)(&i);
626
if (dev->read(b, 2) == 2) {
630
setStatus(ReadPastEnd);
638
\fn QDataStream &QDataStream::operator>>(quint32 &i)
641
Reads an unsigned 32-bit integer from the stream into \a i, and
642
returns a reference to the stream.
648
Reads a signed 32-bit integer from the stream into \a i, and
649
returns a reference to the stream.
652
QDataStream &QDataStream::operator>>(qint32 &i)
655
CHECK_STREAM_PRECOND(*this)
657
if (dev->read((char *)&i, 4) != 4) {
659
setStatus(ReadPastEnd);
661
} else { // swap bytes
662
uchar *p = (uchar *)(&i);
664
if (dev->read(b, 4) == 4) {
670
setStatus(ReadPastEnd);
677
\fn QDataStream &QDataStream::operator>>(quint64 &i)
680
Reads an unsigned 64-bit integer from the stream, into \a i, and
681
returns a reference to the stream.
687
Reads a signed 64-bit integer from the stream into \a i, and
688
returns a reference to the stream.
691
QDataStream &QDataStream::operator>>(qint64 &i)
694
CHECK_STREAM_PRECOND(*this)
698
i = ((quint64)i1 << 32) + i2;
699
} else if (noswap) { // no conversion needed
700
if (dev->read((char *)&i, 8) != 8) {
702
setStatus(ReadPastEnd);
704
} else { // swap bytes
705
uchar *p = (uchar *)(&i);
707
if (dev->read(b, 8) == 8) {
717
setStatus(ReadPastEnd);
724
Reads a boolean value from the stream into \a i. Returns a
725
reference to the stream.
727
QDataStream &QDataStream::operator>>(bool &i)
739
Reads a 32-bit floating point number from the stream into \a f,
740
using the standard IEEE 754 format. Returns a reference to the
744
QDataStream &QDataStream::operator>>(float &f)
747
CHECK_STREAM_PRECOND(*this)
749
if (dev->read((char *)&f, 4) != 4) {
751
setStatus(ReadPastEnd);
753
} else { // swap bytes
754
uchar *p = (uchar *)(&f);
756
if (dev->read(b, 4) == 4) {
762
setStatus(ReadPastEnd);
772
Reads a 64-bit floating point number from the stream into \a f,
773
using the standard IEEE 754 format. Returns a reference to the
777
QDataStream &QDataStream::operator>>(double &f)
780
CHECK_STREAM_PRECOND(*this)
782
if (dev->read((char *)&f, 8) != 8) {
784
setStatus(ReadPastEnd);
786
} else { // swap bytes
787
register uchar *p = (uchar *)(&f);
789
if (dev->read(b, 8) == 8) {
799
setStatus(ReadPastEnd);
809
Reads the '\0'-terminated string \a s from the stream and returns
810
a reference to the stream.
812
Space for the string is allocated using \c new -- the caller must
813
destroy it with \c{delete[]}.
816
QDataStream &QDataStream::operator>>(char *&s)
819
return readBytes(s, len);
824
Reads the buffer \a s from the stream and returns a reference to
827
The buffer \a s is allocated using \c new. Destroy it with the \c
830
The \a l parameter is set to the length of the buffer. If the
831
string read is empty, \a l is set to 0 and \a s is set to
834
The serialization format is a quint32 length specifier first,
835
then \a l bytes of data.
837
\sa readRawData(), writeBytes()
840
QDataStream &QDataStream::readBytes(char *&s, uint &l)
844
CHECK_STREAM_PRECOND(*this)
851
const quint32 Step = 1024 * 1024;
852
quint32 allocated = 0;
857
int blockSize = qMin(Step, len - allocated);
859
curBuf = new char[allocated + blockSize + 1];
861
memcpy(curBuf, prevBuf, allocated);
864
if (dev->read(curBuf + allocated, blockSize) != blockSize) {
866
setStatus(ReadPastEnd);
869
allocated += blockSize;
870
} while (allocated < len);
879
Reads \a len bytes from the stream into \a s and returns a
880
reference to the stream.
882
The buffer \a s must be preallocated. The data is \e not encoded.
884
\sa readBytes(), QIODevice::read(), writeRawData()
887
int QDataStream::readRawData(char *s, int len)
889
CHECK_STREAM_PRECOND(-1)
890
return dev->read(s, len);
894
/*****************************************************************************
895
QDataStream write functions
896
*****************************************************************************/
900
\fn QDataStream &QDataStream::operator<<(quint8 i)
903
Writes an unsigned byte, \a i, to the stream and returns a
904
reference to the stream.
908
Writes a signed byte, \a i, to the stream and returns a reference
912
QDataStream &QDataStream::operator<<(qint8 i)
914
CHECK_STREAM_PRECOND(*this)
921
\fn QDataStream &QDataStream::operator<<(quint16 i)
924
Writes an unsigned 16-bit integer, \a i, to the stream and returns
925
a reference to the stream.
931
Writes a signed 16-bit integer, \a i, to the stream and returns a
932
reference to the stream.
935
QDataStream &QDataStream::operator<<(qint16 i)
937
CHECK_STREAM_PRECOND(*this)
939
dev->write((char *)&i, sizeof(qint16));
940
} else { // swap bytes
941
register uchar *p = (uchar *)(&i);
953
Writes a signed 32-bit integer, \a i, to the stream and returns a
954
reference to the stream.
957
QDataStream &QDataStream::operator<<(qint32 i)
959
CHECK_STREAM_PRECOND(*this)
961
dev->write((char *)&i, sizeof(qint32));
962
} else { // swap bytes
963
register uchar *p = (uchar *)(&i);
975
\fn QDataStream &QDataStream::operator<<(quint64 i)
978
Writes an unsigned 64-bit integer, \a i, to the stream and returns a
979
reference to the stream.
985
Writes a signed 64-bit integer, \a i, to the stream and returns a
986
reference to the stream.
989
QDataStream &QDataStream::operator<<(qint64 i)
991
CHECK_STREAM_PRECOND(*this)
995
i = ((quint64)i1 << 32) + i2;
996
} else if (noswap) { // no conversion needed
997
dev->write((char *)&i, sizeof(qint64));
998
} else { // swap bytes
999
register uchar *p = (uchar *)(&i);
1015
\fn QDataStream &QDataStream::operator<<(quint32 i)
1018
Writes an unsigned integer, \a i, to the stream as a 32-bit
1019
unsigned integer (quint32). Returns a reference to the stream.
1023
Writes a boolean value, \a i, to the stream. Returns a reference
1027
QDataStream &QDataStream::operator<<(bool i)
1029
CHECK_STREAM_PRECOND(*this)
1030
dev->putChar(qint8(i));
1037
Writes a 32-bit floating point number, \a f, to the stream using
1038
the standard IEEE 754 format. Returns a reference to the stream.
1041
QDataStream &QDataStream::operator<<(float f)
1043
CHECK_STREAM_PRECOND(*this)
1044
float g = f; // fixes float-on-stack problem
1045
if (noswap) { // no conversion needed
1046
dev->write((char *)&g, sizeof(float));
1047
} else { // swap bytes
1048
register uchar *p = (uchar *)(&g);
1063
Writes a 64-bit floating point number, \a f, to the stream using
1064
the standard IEEE 754 format. Returns a reference to the stream.
1067
QDataStream &QDataStream::operator<<(double f)
1069
CHECK_STREAM_PRECOND(*this)
1071
dev->write((char *)&f, sizeof(double));
1073
register uchar *p = (uchar *)(&f);
1092
Writes the '\0'-terminated string \a s to the stream and returns a
1093
reference to the stream.
1095
The string is serialized using writeBytes().
1098
QDataStream &QDataStream::operator<<(const char *s)
1101
*this << (quint32)0;
1104
uint len = qstrlen(s) + 1; // also write null terminator
1105
*this << (quint32)len; // write length specifier
1106
writeRawData(s, len);
1112
Writes the length specifier \a len and the buffer \a s to the
1113
stream and returns a reference to the stream.
1115
The \a len is serialized as a quint32, followed by \a len bytes
1116
from \a s. Note that the data is \e not encoded.
1118
\sa writeRawData(), readBytes()
1121
QDataStream &QDataStream::writeBytes(const char *s, uint len)
1123
CHECK_STREAM_PRECOND(*this)
1124
*this << (quint32)len; // write length specifier
1126
writeRawData(s, len);
1132
Writes \a len bytes from \a s to the stream and returns a
1133
reference to the stream. The data is \e not encoded.
1135
\sa writeBytes(), QIODevice::write(), readRawData()
1138
int QDataStream::writeRawData(const char *s, int len)
1140
CHECK_STREAM_PRECOND(-1)
1141
return dev->write(s, len);
1146
\fn QDataStream &QDataStream::readRawBytes(char *str, uint len)
1148
Use readRawData() instead.
1152
\fn QDataStream &QDataStream::writeRawBytes(const char *str, uint len)
1154
Use writeRawData() instead.
1158
#endif // QT_NO_DATASTREAM