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