7f378662262bf615af0c0d6190d0f270a725bd5b
[profile/ivi/qtbase.git] / src / corelib / io / qtextstream.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 //#define QTEXTSTREAM_DEBUG
43 static const int QTEXTSTREAM_BUFFERSIZE = 16384;
44
45 /*!
46     \class QTextStream
47
48     \brief The QTextStream class provides a convenient interface for
49     reading and writing text.
50
51     \ingroup io
52     \ingroup string-processing
53     \reentrant
54
55     QTextStream can operate on a QIODevice, a QByteArray or a
56     QString. Using QTextStream's streaming operators, you can
57     conveniently read and write words, lines and numbers. For
58     generating text, QTextStream supports formatting options for field
59     padding and alignment, and formatting of numbers. Example:
60
61     \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 0
62
63     It's also common to use QTextStream to read console input and write
64     console output. QTextStream is locale aware, and will automatically decode
65     standard input using the correct codec. Example:
66
67     \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 1
68
69     Note that you cannot use QTextStream::atEnd(), which returns true when you
70     have reached the end of the data stream, with stdin. The reason for this is
71     that as long as stdin doesn't give any input to the QTextStream, \c atEnd()
72     will return true even if the stdin is open and waiting for more characters.
73
74     Besides using QTextStream's constructors, you can also set the
75     device or string QTextStream operates on by calling setDevice() or
76     setString(). You can seek to a position by calling seek(), and
77     atEnd() will return true when there is no data left to be read. If
78     you call flush(), QTextStream will empty all data from its write
79     buffer into the device and call flush() on the device.
80
81     Internally, QTextStream uses a Unicode based buffer, and
82     QTextCodec is used by QTextStream to automatically support
83     different character sets. By default, QTextCodec::codecForLocale()
84     is used for reading and writing, but you can also set the codec by
85     calling setCodec(). Automatic Unicode detection is also
86     supported. When this feature is enabled (the default behavior),
87     QTextStream will detect the UTF-16 or the UTF-32 BOM (Byte Order Mark) and
88     switch to the appropriate UTF codec when reading. QTextStream
89     does not write a BOM by default, but you can enable this by calling
90     setGenerateByteOrderMark(true). When QTextStream operates on a QString
91     directly, the codec is disabled.
92
93     There are three general ways to use QTextStream when reading text
94     files:
95
96     \list
97
98     \o Chunk by chunk, by calling readLine() or readAll().
99
100     \o Word by word. QTextStream supports streaming into QStrings,
101     QByteArrays and char* buffers. Words are delimited by space, and
102     leading white space is automatically skipped.
103
104     \o Character by character, by streaming into QChar or char types.
105     This method is often used for convenient input handling when
106     parsing files, independent of character encoding and end-of-line
107     semantics. To skip white space, call skipWhiteSpace().
108
109     \endlist
110
111     Since the text stream uses a buffer, you should not read from
112     the stream using the implementation of a superclass. For instance,
113     if you have a QFile and read from it directly using
114     QFile::readLine() instead of using the stream, the text stream's
115     internal position will be out of sync with the file's position.
116
117     By default, when reading numbers from a stream of text,
118     QTextStream will automatically detect the number's base
119     representation. For example, if the number starts with "0x", it is
120     assumed to be in hexadecimal form. If it starts with the digits
121     1-9, it is assumed to be in decimal form, and so on. You can set
122     the integer base, thereby disabling the automatic detection, by
123     calling setIntegerBase(). Example:
124
125     \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 2
126
127     QTextStream supports many formatting options for generating text.
128     You can set the field width and pad character by calling
129     setFieldWidth() and setPadChar(). Use setFieldAlignment() to set
130     the alignment within each field. For real numbers, call
131     setRealNumberNotation() and setRealNumberPrecision() to set the
132     notation (SmartNotation, ScientificNotation, FixedNotation) and precision in
133     digits of the generated number. Some extra number formatting
134     options are also available through setNumberFlags().
135
136     \keyword QTextStream manipulators
137
138     Like \c <iostream> in the standard C++ library, QTextStream also
139     defines several global manipulator functions:
140
141     \table
142     \header \o Manipulator        \o Description
143     \row    \o \c bin             \o Same as setIntegerBase(2).
144     \row    \o \c oct             \o Same as setIntegerBase(8).
145     \row    \o \c dec             \o Same as setIntegerBase(10).
146     \row    \o \c hex             \o Same as setIntegerBase(16).
147     \row    \o \c showbase        \o Same as setNumberFlags(numberFlags() | ShowBase).
148     \row    \o \c forcesign       \o Same as setNumberFlags(numberFlags() | ForceSign).
149     \row    \o \c forcepoint      \o Same as setNumberFlags(numberFlags() | ForcePoint).
150     \row    \o \c noshowbase      \o Same as setNumberFlags(numberFlags() & ~ShowBase).
151     \row    \o \c noforcesign     \o Same as setNumberFlags(numberFlags() & ~ForceSign).
152     \row    \o \c noforcepoint    \o Same as setNumberFlags(numberFlags() & ~ForcePoint).
153     \row    \o \c uppercasebase   \o Same as setNumberFlags(numberFlags() | UppercaseBase).
154     \row    \o \c uppercasedigits \o Same as setNumberFlags(numberFlags() | UppercaseDigits).
155     \row    \o \c lowercasebase   \o Same as setNumberFlags(numberFlags() & ~UppercaseBase).
156     \row    \o \c lowercasedigits \o Same as setNumberFlags(numberFlags() & ~UppercaseDigits).
157     \row    \o \c fixed           \o Same as setRealNumberNotation(FixedNotation).
158     \row    \o \c scientific      \o Same as setRealNumberNotation(ScientificNotation).
159     \row    \o \c left            \o Same as setFieldAlignment(AlignLeft).
160     \row    \o \c right           \o Same as setFieldAlignment(AlignRight).
161     \row    \o \c center          \o Same as setFieldAlignment(AlignCenter).
162     \row    \o \c endl            \o Same as operator<<('\n') and flush().
163     \row    \o \c flush           \o Same as flush().
164     \row    \o \c reset           \o Same as reset().
165     \row    \o \c ws              \o Same as skipWhiteSpace().
166     \row    \o \c bom             \o Same as setGenerateByteOrderMark(true).
167     \endtable
168
169     In addition, Qt provides three global manipulators that take a
170     parameter: qSetFieldWidth(), qSetPadChar(), and
171     qSetRealNumberPrecision().
172
173     \sa QDataStream, QIODevice, QFile, QBuffer, QTcpSocket, {Codecs Example}
174 */
175
176 /*! \enum QTextStream::RealNumberNotation
177
178     This enum specifies which notations to use for expressing \c
179     float and \c double as strings.
180
181     \value ScientificNotation Scientific notation (\c{printf()}'s \c %e flag).
182     \value FixedNotation Fixed-point notation (\c{printf()}'s \c %f flag).
183     \value SmartNotation Scientific or fixed-point notation, depending on which makes most sense (\c{printf()}'s \c %g flag).
184
185     \sa setRealNumberNotation()
186 */
187
188 /*! \enum QTextStream::FieldAlignment
189
190     This enum specifies how to align text in fields when the field is
191     wider than the text that occupies it.
192
193     \value AlignLeft  Pad on the right side of fields.
194     \value AlignRight  Pad on the left side of fields.
195     \value AlignCenter  Pad on both sides of field.
196     \value AlignAccountingStyle  Same as AlignRight, except that the
197                                  sign of a number is flush left.
198
199     \sa setFieldAlignment()
200 */
201
202 /*! \enum QTextStream::NumberFlag
203
204     This enum specifies various flags that can be set to affect the
205     output of integers, \c{float}s, and \c{double}s.
206
207     \value ShowBase  Show the base as a prefix if the base
208                      is 16 ("0x"), 8 ("0"), or 2 ("0b").
209     \value ForcePoint  Always put the decimal separator in numbers, even if
210                        there are no decimals.
211     \value ForceSign  Always put the sign in numbers, even for positive numbers.
212     \value UppercaseBase  Use uppercase versions of base prefixes ("0X", "0B").
213     \value UppercaseDigits  Use uppercase letters for expressing
214                             digits 10 to 35 instead of lowercase.
215
216     \sa setNumberFlags()
217 */
218
219 /*! \enum QTextStream::Status
220
221     This enum describes the current status of the text stream.
222
223     \value Ok               The text stream is operating normally.
224     \value ReadPastEnd      The text stream has read past the end of the
225                             data in the underlying device.
226     \value ReadCorruptData  The text stream has read corrupt data.
227     \value WriteFailed      The text stream cannot write to the underlying device.
228
229     \sa status()
230 */
231
232 #include "qtextstream.h"
233 #include "qbuffer.h"
234 #include "qfile.h"
235 #include "qnumeric.h"
236 #ifndef QT_NO_TEXTCODEC
237 #include "qtextcodec.h"
238 #endif
239 #ifndef Q_OS_WINCE
240 #include <locale.h>
241 #endif
242 #include "private/qlocale_p.h"
243
244 #include <stdlib.h>
245 #include <limits.h>
246 #include <new>
247
248 #if defined QTEXTSTREAM_DEBUG
249 #include <ctype.h>
250
251 QT_BEGIN_NAMESPACE
252
253 // Returns a human readable representation of the first \a len
254 // characters in \a data.
255 static QByteArray qt_prettyDebug(const char *data, int len, int maxSize)
256 {
257     if (!data) return "(null)";
258     QByteArray out;
259     for (int i = 0; i < len; ++i) {
260         char c = data[i];
261         if (isprint(int(uchar(c)))) {
262             out += c;
263         } else switch (c) {
264         case '\n': out += "\\n"; break;
265         case '\r': out += "\\r"; break;
266         case '\t': out += "\\t"; break;
267         default:
268             QString tmp;
269             tmp.sprintf("\\x%x", (unsigned int)(unsigned char)c);
270             out += tmp.toLatin1();
271         }
272     }
273
274     if (len < maxSize)
275         out += "...";
276
277     return out;
278 }
279 QT_END_NAMESPACE
280
281 #endif
282
283 // A precondition macro
284 #define Q_VOID
285 #define CHECK_VALID_STREAM(x) do { \
286     if (!d->string && !d->device) { \
287         qWarning("QTextStream: No device"); \
288         return x; \
289     } } while (0)
290
291 // Base implementations of operator>> for ints and reals
292 #define IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(type) do { \
293     Q_D(QTextStream); \
294     CHECK_VALID_STREAM(*this); \
295     qulonglong tmp; \
296     switch (d->getNumber(&tmp)) { \
297     case QTextStreamPrivate::npsOk: \
298         i = (type)tmp; \
299         break; \
300     case QTextStreamPrivate::npsMissingDigit: \
301     case QTextStreamPrivate::npsInvalidPrefix: \
302         i = (type)0; \
303         setStatus(atEnd() ? QTextStream::ReadPastEnd : QTextStream::ReadCorruptData); \
304         break; \
305     } \
306     return *this; } while (0)
307
308 #define IMPLEMENT_STREAM_RIGHT_REAL_OPERATOR(type) do { \
309     Q_D(QTextStream); \
310     CHECK_VALID_STREAM(*this); \
311     double tmp; \
312     if (d->getReal(&tmp)) { \
313         f = (type)tmp; \
314     } else { \
315         f = (type)0; \
316         setStatus(atEnd() ? QTextStream::ReadPastEnd : QTextStream::ReadCorruptData); \
317     } \
318     return *this; } while (0)
319
320 QT_BEGIN_NAMESPACE
321
322 #ifndef QT_NO_QOBJECT
323 class QDeviceClosedNotifier : public QObject
324 {
325     Q_OBJECT
326 public:
327     inline QDeviceClosedNotifier()
328     { }
329
330     inline void setupDevice(QTextStream *stream, QIODevice *device)
331     {
332         disconnect();
333         if (device)
334             connect(device, SIGNAL(aboutToClose()), this, SLOT(flushStream()));
335         this->stream = stream;
336     }
337
338 public Q_SLOTS:
339     inline void flushStream() { stream->flush(); }
340
341 private:
342     QTextStream *stream;
343 };
344 #endif
345
346 //-------------------------------------------------------------------
347 class QTextStreamPrivate
348 {
349     Q_DECLARE_PUBLIC(QTextStream)
350 public:
351     QTextStreamPrivate(QTextStream *q_ptr);
352     ~QTextStreamPrivate();
353     void reset();
354
355     // device
356     QIODevice *device;
357 #ifndef QT_NO_QOBJECT
358     QDeviceClosedNotifier deviceClosedNotifier;
359 #endif
360     bool deleteDevice;
361
362     // string
363     QString *string;
364     int stringOffset;
365     QIODevice::OpenMode stringOpenMode;
366
367 #ifndef QT_NO_TEXTCODEC
368     // codec
369     QTextCodec *codec;
370     QTextCodec::ConverterState readConverterState;
371     QTextCodec::ConverterState writeConverterState;
372     QTextCodec::ConverterState *readConverterSavedState;
373     bool autoDetectUnicode;
374 #endif
375
376     // i/o
377     enum TokenDelimiter {
378         Space,
379         NotSpace,
380         EndOfLine
381     };
382
383     QString read(int maxlen);
384     bool scan(const QChar **ptr, int *tokenLength,
385               int maxlen, TokenDelimiter delimiter);
386     inline const QChar *readPtr() const;
387     inline void consumeLastToken();
388     inline void consume(int nchars);
389     void saveConverterState(qint64 newPos);
390     void restoreToSavedConverterState();
391     int lastTokenSize;
392
393     // Return value type for getNumber()
394     enum NumberParsingStatus {
395         npsOk,
396         npsMissingDigit,
397         npsInvalidPrefix
398     };
399
400     inline bool getChar(QChar *ch);
401     inline void ungetChar(const QChar &ch);
402     NumberParsingStatus getNumber(qulonglong *l);
403     bool getReal(double *f);
404
405     inline void write(const QString &data);
406     inline void putString(const QString &ch, bool number = false);
407     void putNumber(qulonglong number, bool negative);
408
409     // buffers
410     bool fillReadBuffer(qint64 maxBytes = -1);
411     void resetReadBuffer();
412     void flushWriteBuffer();
413     QString writeBuffer;
414     QString readBuffer;
415     int readBufferOffset;
416     int readConverterSavedStateOffset; //the offset between readBufferStartDevicePos and that start of the buffer
417     qint64 readBufferStartDevicePos;
418
419     // streaming parameters
420     int realNumberPrecision;
421     int integerBase;
422     int fieldWidth;
423     QChar padChar;
424     QTextStream::FieldAlignment fieldAlignment;
425     QTextStream::RealNumberNotation realNumberNotation;
426     QTextStream::NumberFlags numberFlags;
427
428     // status
429     QTextStream::Status status;
430
431     QLocale locale;
432
433     QTextStream *q_ptr;
434 };
435
436 /*! \internal
437 */
438 QTextStreamPrivate::QTextStreamPrivate(QTextStream *q_ptr)
439     :
440 #ifndef QT_NO_TEXTCODEC
441     readConverterSavedState(0),
442 #endif
443     readConverterSavedStateOffset(0),
444     locale(QLocale::c())
445 {
446     this->q_ptr = q_ptr;
447     reset();
448 }
449
450 /*! \internal
451 */
452 QTextStreamPrivate::~QTextStreamPrivate()
453 {
454     if (deleteDevice) {
455 #ifndef QT_NO_QOBJECT
456         device->blockSignals(true);
457 #endif
458         delete device;
459     }
460 #ifndef QT_NO_TEXTCODEC
461     delete readConverterSavedState;
462 #endif
463 }
464
465 #ifndef QT_NO_TEXTCODEC
466 static void resetCodecConverterStateHelper(QTextCodec::ConverterState *state)
467 {
468     state->~ConverterState();
469     new (state) QTextCodec::ConverterState;
470 }
471
472 static void copyConverterStateHelper(QTextCodec::ConverterState *dest,
473     const QTextCodec::ConverterState *src)
474 {
475     // ### QTextCodec::ConverterState's copy constructors and assignments are
476     // private. This function copies the structure manually.
477     Q_ASSERT(!src->d);
478     dest->flags = src->flags;
479     dest->invalidChars = src->invalidChars;
480     dest->state_data[0] = src->state_data[0];
481     dest->state_data[1] = src->state_data[1];
482     dest->state_data[2] = src->state_data[2];
483 }
484 #endif
485
486 /*! \internal
487 */
488 void QTextStreamPrivate::reset()
489 {
490     realNumberPrecision = 6;
491     integerBase = 0;
492     fieldWidth = 0;
493     padChar = QLatin1Char(' ');
494     fieldAlignment = QTextStream::AlignRight;
495     realNumberNotation = QTextStream::SmartNotation;
496     numberFlags = 0;
497
498     device = 0;
499     deleteDevice = false;
500     string = 0;
501     stringOffset = 0;
502     stringOpenMode = QIODevice::NotOpen;
503
504     readBufferOffset = 0;
505     readBufferStartDevicePos = 0;
506     lastTokenSize = 0;
507
508 #ifndef QT_NO_TEXTCODEC
509     codec = QTextCodec::codecForLocale();
510     resetCodecConverterStateHelper(&readConverterState);
511     resetCodecConverterStateHelper(&writeConverterState);
512     delete readConverterSavedState;
513     readConverterSavedState = 0;
514     writeConverterState.flags |= QTextCodec::IgnoreHeader;
515     autoDetectUnicode = true;
516 #endif
517 }
518
519 /*! \internal
520 */
521 bool QTextStreamPrivate::fillReadBuffer(qint64 maxBytes)
522 {
523     // no buffer next to the QString itself; this function should only
524     // be called internally, for devices.
525     Q_ASSERT(!string);
526     Q_ASSERT(device);
527
528     // handle text translation and bypass the Text flag in the device.
529     bool textModeEnabled = device->isTextModeEnabled();
530     if (textModeEnabled)
531         device->setTextModeEnabled(false);
532
533     // read raw data into a temporary buffer
534     char buf[QTEXTSTREAM_BUFFERSIZE];
535     qint64 bytesRead = 0;
536 #if defined(Q_OS_WIN)
537     // On Windows, there is no non-blocking stdin - so we fall back to reading
538     // lines instead. If there is no QOBJECT, we read lines for all sequential
539     // devices; otherwise, we read lines only for stdin.
540     QFile *file = 0;
541     Q_UNUSED(file);
542     if (device->isSequential()
543 #if !defined(QT_NO_QOBJECT)
544         && (file = qobject_cast<QFile *>(device)) && file->handle() == 0
545 #endif
546         ) {
547         if (maxBytes != -1)
548             bytesRead = device->readLine(buf, qMin<qint64>(sizeof(buf), maxBytes));
549         else
550             bytesRead = device->readLine(buf, sizeof(buf));
551     } else
552 #endif
553     {
554         if (maxBytes != -1)
555             bytesRead = device->read(buf, qMin<qint64>(sizeof(buf), maxBytes));
556         else
557             bytesRead = device->read(buf, sizeof(buf));
558     }
559
560 #ifndef QT_NO_TEXTCODEC
561     // codec auto detection, explicitly defaults to locale encoding if the
562     // codec has been set to 0.
563     if (!codec || autoDetectUnicode) {
564         autoDetectUnicode = false;
565
566         codec = QTextCodec::codecForUtfText(QByteArray::fromRawData(buf, bytesRead), codec);
567         if (!codec) {
568             codec = QTextCodec::codecForLocale();
569             writeConverterState.flags |= QTextCodec::IgnoreHeader;
570         }
571     }
572 #if defined (QTEXTSTREAM_DEBUG)
573     qDebug("QTextStreamPrivate::fillReadBuffer(), using %s codec",
574            codec->name().constData());
575 #endif
576 #endif
577
578 #if defined (QTEXTSTREAM_DEBUG)
579     qDebug("QTextStreamPrivate::fillReadBuffer(), device->read(\"%s\", %d) == %d",
580            qt_prettyDebug(buf, qMin(32,int(bytesRead)) , int(bytesRead)).constData(), sizeof(buf), int(bytesRead));
581 #endif
582
583     if (bytesRead <= 0)
584         return false;
585
586     int oldReadBufferSize = readBuffer.size();
587 #ifndef QT_NO_TEXTCODEC
588     // convert to unicode
589     readBuffer += codec->toUnicode(buf, bytesRead, &readConverterState);
590 #else
591     readBuffer += QString::fromLatin1(QByteArray(buf, bytesRead).constData());
592 #endif
593
594     // reset the Text flag.
595     if (textModeEnabled)
596         device->setTextModeEnabled(true);
597
598     // remove all '\r\n' in the string.
599     if (readBuffer.size() > oldReadBufferSize && textModeEnabled) {
600         QChar CR = QLatin1Char('\r');
601         QChar *writePtr = readBuffer.data() + oldReadBufferSize;
602         QChar *readPtr = readBuffer.data() + oldReadBufferSize;
603         QChar *endPtr = readBuffer.data() + readBuffer.size();
604
605         int n = oldReadBufferSize;
606         if (readPtr < endPtr) {
607             // Cut-off to avoid unnecessary self-copying.
608             while (*readPtr++ != CR) {
609                 ++n;
610                 if (++writePtr == endPtr)
611                     break;
612             }
613         }
614         while (readPtr < endPtr) {
615             QChar ch = *readPtr++;
616             if (ch != CR) {
617                 *writePtr++ = ch;
618             } else {
619                 if (n < readBufferOffset)
620                     --readBufferOffset;
621                 --bytesRead;
622             }
623             ++n;
624         }
625         readBuffer.resize(writePtr - readBuffer.data());
626     }
627
628 #if defined (QTEXTSTREAM_DEBUG)
629     qDebug("QTextStreamPrivate::fillReadBuffer() read %d bytes from device. readBuffer = [%s]", int(bytesRead),
630            qt_prettyDebug(readBuffer.toLatin1(), readBuffer.size(), readBuffer.size()).data());
631 #endif
632     return true;
633 }
634
635 /*! \internal
636 */
637 void QTextStreamPrivate::resetReadBuffer()
638 {
639     readBuffer.clear();
640     readBufferOffset = 0;
641     readBufferStartDevicePos = (device ? device->pos() : 0);
642 }
643
644 /*! \internal
645 */
646 void QTextStreamPrivate::flushWriteBuffer()
647 {
648     // no buffer next to the QString itself; this function should only
649     // be called internally, for devices.
650     if (string || !device)
651         return;
652
653     // Stream went bye-bye already. Appending further data may succeed again,
654     // but would create a corrupted stream anyway.
655     if (status != QTextStream::Ok)
656         return;
657
658     if (writeBuffer.isEmpty())
659         return;
660
661 #if defined (Q_OS_WIN)
662     // handle text translation and bypass the Text flag in the device.
663     bool textModeEnabled = device->isTextModeEnabled();
664     if (textModeEnabled) {
665         device->setTextModeEnabled(false);
666         writeBuffer.replace(QLatin1Char('\n'), QLatin1String("\r\n"));
667     }
668 #endif
669
670 #ifndef QT_NO_TEXTCODEC
671     if (!codec)
672         codec = QTextCodec::codecForLocale();
673 #if defined (QTEXTSTREAM_DEBUG)
674     qDebug("QTextStreamPrivate::flushWriteBuffer(), using %s codec (%s generating BOM)",
675            codec->name().constData(), writeConverterState.flags & QTextCodec::IgnoreHeader ? "not" : "");
676 #endif
677
678     // convert from unicode to raw data
679     QByteArray data = codec->fromUnicode(writeBuffer.data(), writeBuffer.size(), &writeConverterState);
680 #else
681     QByteArray data = writeBuffer.toLocal8Bit();
682 #endif
683     writeBuffer.clear();
684
685     // write raw data to the device
686     qint64 bytesWritten = device->write(data);
687 #if defined (QTEXTSTREAM_DEBUG)
688     qDebug("QTextStreamPrivate::flushWriteBuffer(), device->write(\"%s\") == %d",
689            qt_prettyDebug(data.constData(), qMin(data.size(),32), data.size()).constData(), int(bytesWritten));
690 #endif
691     if (bytesWritten <= 0) {
692         status = QTextStream::WriteFailed;
693         return;
694     }
695
696 #if defined (Q_OS_WIN)
697     // replace the text flag
698     if (textModeEnabled)
699         device->setTextModeEnabled(true);
700 #endif
701
702     // flush the file
703 #ifndef QT_NO_QOBJECT
704     QFile *file = qobject_cast<QFile *>(device);
705     bool flushed = !file || file->flush();
706 #else
707     bool flushed = true;
708 #endif
709
710 #if defined (QTEXTSTREAM_DEBUG)
711     qDebug("QTextStreamPrivate::flushWriteBuffer() wrote %d bytes",
712            int(bytesWritten));
713 #endif
714     if (!flushed || bytesWritten != qint64(data.size()))
715         status = QTextStream::WriteFailed;
716 }
717
718 QString QTextStreamPrivate::read(int maxlen)
719 {
720     QString ret;
721     if (string) {
722         lastTokenSize = qMin(maxlen, string->size() - stringOffset);
723         ret = string->mid(stringOffset, lastTokenSize);
724     } else {
725         while (readBuffer.size() - readBufferOffset < maxlen && fillReadBuffer()) ;
726         lastTokenSize = qMin(maxlen, readBuffer.size() - readBufferOffset);
727         ret = readBuffer.mid(readBufferOffset, lastTokenSize);
728     }
729     consumeLastToken();
730
731 #if defined (QTEXTSTREAM_DEBUG)
732     qDebug("QTextStreamPrivate::read() maxlen = %d, token length = %d", maxlen, ret.length());
733 #endif
734     return ret;
735 }
736
737 /*! \internal
738
739     Scans no more than \a maxlen QChars in the current buffer for the
740     first \a delimiter. Stores a pointer to the start offset of the
741     token in \a ptr, and the length in QChars in \a length.
742 */
743 bool QTextStreamPrivate::scan(const QChar **ptr, int *length, int maxlen, TokenDelimiter delimiter)
744 {
745     int totalSize = 0;
746     int delimSize = 0;
747     bool consumeDelimiter = false;
748     bool foundToken = false;
749     int startOffset = device ? readBufferOffset : stringOffset;
750     QChar lastChar;
751
752     bool canStillReadFromDevice = true;
753     do {
754         int endOffset;
755         const QChar *chPtr;
756         if (device) {
757             chPtr = readBuffer.constData();
758             endOffset = readBuffer.size();
759         } else {
760             chPtr = string->constData();
761             endOffset = string->size();
762         }
763         chPtr += startOffset;
764
765         for (; !foundToken && startOffset < endOffset && (!maxlen || totalSize < maxlen); ++startOffset) {
766             const QChar ch = *chPtr++;
767             ++totalSize;
768
769             switch (delimiter) {
770             case Space:
771                 if (ch.isSpace()) {
772                     foundToken = true;
773                     delimSize = 1;
774                 }
775                 break;
776             case NotSpace:
777                 if (!ch.isSpace()) {
778                     foundToken = true;
779                     delimSize = 1;
780                 }
781                 break;
782             case EndOfLine:
783                 if (ch == QLatin1Char('\n')) {
784                     foundToken = true;
785                     delimSize = (lastChar == QLatin1Char('\r')) ? 2 : 1;
786                     consumeDelimiter = true;
787                 }
788                 lastChar = ch;
789                 break;
790             }
791         }
792     } while (!foundToken
793              && (!maxlen || totalSize < maxlen)
794              && (device && (canStillReadFromDevice = fillReadBuffer())));
795
796     // if the token was not found, but we reached the end of input,
797     // then we accept what we got. if we are not at the end of input,
798     // we return false.
799     if (!foundToken && (!maxlen || totalSize < maxlen)
800         && (totalSize == 0
801             || (string && stringOffset + totalSize < string->size())
802             || (device && !device->atEnd() && canStillReadFromDevice))) {
803 #if defined (QTEXTSTREAM_DEBUG)
804         qDebug("QTextStreamPrivate::scan() did not find the token.");
805 #endif
806         return false;
807     }
808
809     // if we find a '\r' at the end of the data when reading lines,
810     // don't make it part of the line.
811     if (delimiter == EndOfLine && totalSize > 0 && !foundToken) {
812         if (((string && stringOffset + totalSize == string->size()) || (device && device->atEnd()))
813             && lastChar == QLatin1Char('\r')) {
814             consumeDelimiter = true;
815             ++delimSize;
816         }
817     }
818
819     // set the read offset and length of the token
820     if (length)
821         *length = totalSize - delimSize;
822     if (ptr)
823         *ptr = readPtr();
824
825     // update last token size. the callee will call consumeLastToken() when
826     // done.
827     lastTokenSize = totalSize;
828     if (!consumeDelimiter)
829         lastTokenSize -= delimSize;
830
831 #if defined (QTEXTSTREAM_DEBUG)
832     qDebug("QTextStreamPrivate::scan(%p, %p, %d, %x) token length = %d, delimiter = %d",
833            ptr, length, maxlen, (int)delimiter, totalSize - delimSize, delimSize);
834 #endif
835     return true;
836 }
837
838 /*! \internal
839 */
840 inline const QChar *QTextStreamPrivate::readPtr() const
841 {
842     Q_ASSERT(readBufferOffset <= readBuffer.size());
843     if (string)
844         return string->constData() + stringOffset;
845     return readBuffer.constData() + readBufferOffset;
846 }
847
848 /*! \internal
849 */
850 inline void QTextStreamPrivate::consumeLastToken()
851 {
852     if (lastTokenSize)
853         consume(lastTokenSize);
854     lastTokenSize = 0;
855 }
856
857 /*! \internal
858 */
859 inline void QTextStreamPrivate::consume(int size)
860 {
861 #if defined (QTEXTSTREAM_DEBUG)
862     qDebug("QTextStreamPrivate::consume(%d)", size);
863 #endif
864     if (string) {
865         stringOffset += size;
866         if (stringOffset > string->size())
867             stringOffset = string->size();
868     } else {
869         readBufferOffset += size;
870         if (readBufferOffset >= readBuffer.size()) {
871             readBufferOffset = 0;
872             readBuffer.clear();
873             saveConverterState(device->pos());
874         } else if (readBufferOffset > QTEXTSTREAM_BUFFERSIZE) {
875             readBuffer = readBuffer.remove(0,readBufferOffset);
876             readConverterSavedStateOffset += readBufferOffset;
877             readBufferOffset = 0;
878         }
879     }
880 }
881
882 /*! \internal
883 */
884 inline void QTextStreamPrivate::saveConverterState(qint64 newPos)
885 {
886 #ifndef QT_NO_TEXTCODEC
887     if (readConverterState.d) {
888         // converter cannot be copied, so don't save anything
889         // don't update readBufferStartDevicePos either
890         return;
891     }
892
893     if (!readConverterSavedState)
894         readConverterSavedState = new QTextCodec::ConverterState;
895     copyConverterStateHelper(readConverterSavedState, &readConverterState);
896 #endif
897
898     readBufferStartDevicePos = newPos;
899     readConverterSavedStateOffset = 0;
900 }
901
902 /*! \internal
903 */
904 inline void QTextStreamPrivate::restoreToSavedConverterState()
905 {
906 #ifndef QT_NO_TEXTCODEC
907     if (readConverterSavedState) {
908         // we have a saved state
909         // that means the converter can be copied
910         copyConverterStateHelper(&readConverterState, readConverterSavedState);
911     } else {
912         // the only state we could save was the initial
913         // so reset to that
914         resetCodecConverterStateHelper(&readConverterState);
915     }
916 #endif
917 }
918
919 /*! \internal
920 */
921 inline void QTextStreamPrivate::write(const QString &data)
922 {
923     if (string) {
924         // ### What about seek()??
925         string->append(data);
926     } else {
927         writeBuffer += data;
928         if (writeBuffer.size() > QTEXTSTREAM_BUFFERSIZE)
929             flushWriteBuffer();
930     }
931 }
932
933 /*! \internal
934 */
935 inline bool QTextStreamPrivate::getChar(QChar *ch)
936 {
937     if ((string && stringOffset == string->size())
938         || (device && readBuffer.isEmpty() && !fillReadBuffer())) {
939         if (ch)
940             *ch = 0;
941         return false;
942     }
943     if (ch)
944         *ch = *readPtr();
945     consume(1);
946     return true;
947 }
948
949 /*! \internal
950 */
951 inline void QTextStreamPrivate::ungetChar(const QChar &ch)
952 {
953     if (string) {
954         if (stringOffset == 0)
955             string->prepend(ch);
956         else
957             (*string)[--stringOffset] = ch;
958         return;
959     }
960
961     if (readBufferOffset == 0) {
962         readBuffer.prepend(ch);
963         return;
964     }
965
966     readBuffer[--readBufferOffset] = ch;
967 }
968
969 /*! \internal
970 */
971 inline void QTextStreamPrivate::putString(const QString &s, bool number)
972 {
973     QString tmp = s;
974
975     // handle padding
976     int padSize = fieldWidth - s.size();
977     if (padSize > 0) {
978         QString pad(padSize, padChar);
979         if (fieldAlignment == QTextStream::AlignLeft) {
980             tmp.append(QString(padSize, padChar));
981         } else if (fieldAlignment == QTextStream::AlignRight
982                    || fieldAlignment == QTextStream::AlignAccountingStyle) {
983             tmp.prepend(QString(padSize, padChar));
984             if (fieldAlignment == QTextStream::AlignAccountingStyle && number) {
985                 const QChar sign = s.size() > 0 ? s.at(0) : QChar();
986                 if (sign == locale.negativeSign() || sign == locale.positiveSign()) {
987                     QChar *data = tmp.data();
988                     data[padSize] = tmp.at(0);
989                     data[0] = sign;
990                 }
991            }
992         } else if (fieldAlignment == QTextStream::AlignCenter) {
993             tmp.prepend(QString(padSize/2, padChar));
994             tmp.append(QString(padSize - padSize/2, padChar));
995         }
996     }
997
998 #if defined (QTEXTSTREAM_DEBUG)
999     QByteArray a = s.toUtf8();
1000     QByteArray b = tmp.toUtf8();
1001     qDebug("QTextStreamPrivate::putString(\"%s\") calls write(\"%s\")",
1002            qt_prettyDebug(a.constData(), a.size(), qMax(16, a.size())).constData(),
1003            qt_prettyDebug(b.constData(), b.size(), qMax(16, b.size())).constData());
1004 #endif
1005     write(tmp);
1006 }
1007
1008 /*!
1009     Constructs a QTextStream. Before you can use it for reading or
1010     writing, you must assign a device or a string.
1011
1012     \sa setDevice(), setString()
1013 */
1014 QTextStream::QTextStream()
1015     : d_ptr(new QTextStreamPrivate(this))
1016 {
1017 #if defined (QTEXTSTREAM_DEBUG)
1018     qDebug("QTextStream::QTextStream()");
1019 #endif
1020     Q_D(QTextStream);
1021     d->status = Ok;
1022 }
1023
1024 /*!
1025     Constructs a QTextStream that operates on \a device.
1026 */
1027 QTextStream::QTextStream(QIODevice *device)
1028     : d_ptr(new QTextStreamPrivate(this))
1029 {
1030 #if defined (QTEXTSTREAM_DEBUG)
1031     qDebug("QTextStream::QTextStream(QIODevice *device == *%p)",
1032            device);
1033 #endif
1034     Q_D(QTextStream);
1035     d->device = device;
1036 #ifndef QT_NO_QOBJECT
1037     d->deviceClosedNotifier.setupDevice(this, d->device);
1038 #endif
1039     d->status = Ok;
1040 }
1041
1042 /*!
1043     Constructs a QTextStream that operates on \a string, using \a
1044     openMode to define the open mode.
1045 */
1046 QTextStream::QTextStream(QString *string, QIODevice::OpenMode openMode)
1047     : d_ptr(new QTextStreamPrivate(this))
1048 {
1049 #if defined (QTEXTSTREAM_DEBUG)
1050     qDebug("QTextStream::QTextStream(QString *string == *%p, openMode = %d)",
1051            string, int(openMode));
1052 #endif
1053     Q_D(QTextStream);
1054     d->string = string;
1055     d->stringOpenMode = openMode;
1056     d->status = Ok;
1057 }
1058
1059 /*!
1060     Constructs a QTextStream that operates on \a array, using \a
1061     openMode to define the open mode. Internally, the array is wrapped
1062     by a QBuffer.
1063 */
1064 QTextStream::QTextStream(QByteArray *array, QIODevice::OpenMode openMode)
1065     : d_ptr(new QTextStreamPrivate(this))
1066 {
1067 #if defined (QTEXTSTREAM_DEBUG)
1068     qDebug("QTextStream::QTextStream(QByteArray *array == *%p, openMode = %d)",
1069            array, int(openMode));
1070 #endif
1071     Q_D(QTextStream);
1072     d->device = new QBuffer(array);
1073     d->device->open(openMode);
1074     d->deleteDevice = true;
1075 #ifndef QT_NO_QOBJECT
1076     d->deviceClosedNotifier.setupDevice(this, d->device);
1077 #endif
1078     d->status = Ok;
1079 }
1080
1081 /*!
1082     Constructs a QTextStream that operates on \a array, using \a
1083     openMode to define the open mode. The array is accessed as
1084     read-only, regardless of the values in \a openMode.
1085
1086     This constructor is convenient for working on constant
1087     strings. Example:
1088
1089     \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 3
1090 */
1091 QTextStream::QTextStream(const QByteArray &array, QIODevice::OpenMode openMode)
1092     : d_ptr(new QTextStreamPrivate(this))
1093 {
1094 #if defined (QTEXTSTREAM_DEBUG)
1095     qDebug("QTextStream::QTextStream(const QByteArray &array == *(%p), openMode = %d)",
1096            &array, int(openMode));
1097 #endif
1098     QBuffer *buffer = new QBuffer;
1099     buffer->setData(array);
1100     buffer->open(openMode);
1101
1102     Q_D(QTextStream);
1103     d->device = buffer;
1104     d->deleteDevice = true;
1105 #ifndef QT_NO_QOBJECT
1106     d->deviceClosedNotifier.setupDevice(this, d->device);
1107 #endif
1108     d->status = Ok;
1109 }
1110
1111 /*!
1112     Constructs a QTextStream that operates on \a fileHandle, using \a
1113     openMode to define the open mode. Internally, a QFile is created
1114     to handle the FILE pointer.
1115
1116     This constructor is useful for working directly with the common
1117     FILE based input and output streams: stdin, stdout and stderr. Example:
1118
1119     \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 4
1120 */
1121
1122 QTextStream::QTextStream(FILE *fileHandle, QIODevice::OpenMode openMode)
1123     : d_ptr(new QTextStreamPrivate(this))
1124 {
1125 #if defined (QTEXTSTREAM_DEBUG)
1126     qDebug("QTextStream::QTextStream(FILE *fileHandle = %p, openMode = %d)",
1127            fileHandle, int(openMode));
1128 #endif
1129     QFile *file = new QFile;
1130     file->open(fileHandle, openMode);
1131
1132     Q_D(QTextStream);
1133     d->device = file;
1134     d->deleteDevice = true;
1135 #ifndef QT_NO_QOBJECT
1136     d->deviceClosedNotifier.setupDevice(this, d->device);
1137 #endif
1138     d->status = Ok;
1139 }
1140
1141 /*!
1142     Destroys the QTextStream.
1143
1144     If the stream operates on a device, flush() will be called
1145     implicitly. Otherwise, the device is unaffected.
1146 */
1147 QTextStream::~QTextStream()
1148 {
1149     Q_D(QTextStream);
1150 #if defined (QTEXTSTREAM_DEBUG)
1151     qDebug("QTextStream::~QTextStream()");
1152 #endif
1153     if (!d->writeBuffer.isEmpty())
1154         d->flushWriteBuffer();
1155 }
1156
1157 /*!
1158     Resets QTextStream's formatting options, bringing it back to its
1159     original constructed state. The device, string and any buffered
1160     data is left untouched.
1161 */
1162 void QTextStream::reset()
1163 {
1164     Q_D(QTextStream);
1165
1166     d->realNumberPrecision = 6;
1167     d->integerBase = 0;
1168     d->fieldWidth = 0;
1169     d->padChar = QLatin1Char(' ');
1170     d->fieldAlignment = QTextStream::AlignRight;
1171     d->realNumberNotation = QTextStream::SmartNotation;
1172     d->numberFlags = 0;
1173 }
1174
1175 /*!
1176     Flushes any buffered data waiting to be written to the device.
1177
1178     If QTextStream operates on a string, this function does nothing.
1179 */
1180 void QTextStream::flush()
1181 {
1182     Q_D(QTextStream);
1183     d->flushWriteBuffer();
1184 }
1185
1186 /*!
1187     Seeks to the position \a pos in the device. Returns true on
1188     success; otherwise returns false.
1189 */
1190 bool QTextStream::seek(qint64 pos)
1191 {
1192     Q_D(QTextStream);
1193     d->lastTokenSize = 0;
1194
1195     if (d->device) {
1196         // Empty the write buffer
1197         d->flushWriteBuffer();
1198         if (!d->device->seek(pos))
1199             return false;
1200         d->resetReadBuffer();
1201
1202 #ifndef QT_NO_TEXTCODEC
1203         // Reset the codec converter states.
1204         resetCodecConverterStateHelper(&d->readConverterState);
1205         resetCodecConverterStateHelper(&d->writeConverterState);
1206         delete d->readConverterSavedState;
1207         d->readConverterSavedState = 0;
1208         d->writeConverterState.flags |= QTextCodec::IgnoreHeader;
1209 #endif
1210         return true;
1211     }
1212
1213     // string
1214     if (d->string && pos <= d->string->size()) {
1215         d->stringOffset = int(pos);
1216         return true;
1217     }
1218     return false;
1219 }
1220
1221 /*!
1222     \since 4.2
1223
1224     Returns the device position corresponding to the current position of the
1225     stream, or -1 if an error occurs (e.g., if there is no device or string,
1226     or if there's a device error).
1227
1228     Because QTextStream is buffered, this function may have to
1229     seek the device to reconstruct a valid device position. This
1230     operation can be expensive, so you may want to avoid calling this
1231     function in a tight loop.
1232
1233     \sa seek()
1234 */
1235 qint64 QTextStream::pos() const
1236 {
1237     Q_D(const QTextStream);
1238     if (d->device) {
1239         // Cutoff
1240         if (d->readBuffer.isEmpty())
1241             return d->device->pos();
1242         if (d->device->isSequential())
1243             return 0;
1244
1245         // Seek the device
1246         if (!d->device->seek(d->readBufferStartDevicePos))
1247             return qint64(-1);
1248
1249         // Reset the read buffer
1250         QTextStreamPrivate *thatd = const_cast<QTextStreamPrivate *>(d);
1251         thatd->readBuffer.clear();
1252
1253 #ifndef QT_NO_TEXTCODEC
1254         thatd->restoreToSavedConverterState();
1255         if (d->readBufferStartDevicePos == 0)
1256             thatd->autoDetectUnicode = true;
1257 #endif
1258
1259         // Rewind the device to get to the current position Ensure that
1260         // readBufferOffset is unaffected by fillReadBuffer()
1261         int oldReadBufferOffset = d->readBufferOffset + d->readConverterSavedStateOffset;
1262         while (d->readBuffer.size() < oldReadBufferOffset) {
1263             if (!thatd->fillReadBuffer(1))
1264                 return qint64(-1);
1265         }
1266         thatd->readBufferOffset = oldReadBufferOffset;
1267         thatd->readConverterSavedStateOffset = 0;
1268
1269         // Return the device position.
1270         return d->device->pos();
1271     }
1272
1273     if (d->string)
1274         return d->stringOffset;
1275
1276     qWarning("QTextStream::pos: no device");
1277     return qint64(-1);
1278 }
1279
1280 /*!
1281     Reads and discards whitespace from the stream until either a
1282     non-space character is detected, or until atEnd() returns
1283     true. This function is useful when reading a stream character by
1284     character.
1285
1286     Whitespace characters are all characters for which
1287     QChar::isSpace() returns true.
1288
1289     \sa operator>>()
1290 */
1291 void QTextStream::skipWhiteSpace()
1292 {
1293     Q_D(QTextStream);
1294     CHECK_VALID_STREAM(Q_VOID);
1295     d->scan(0, 0, 0, QTextStreamPrivate::NotSpace);
1296     d->consumeLastToken();
1297 }
1298
1299 /*!
1300     Sets the current device to \a device. If a device has already been
1301     assigned, QTextStream will call flush() before the old device is
1302     replaced.
1303
1304     \note This function resets locale to the default locale ('C')
1305     and codec to the default codec, QTextCodec::codecForLocale().
1306
1307     \sa device(), setString()
1308 */
1309 void QTextStream::setDevice(QIODevice *device)
1310 {
1311     Q_D(QTextStream);
1312     flush();
1313     if (d->deleteDevice) {
1314 #ifndef QT_NO_QOBJECT
1315         d->deviceClosedNotifier.disconnect();
1316 #endif
1317         delete d->device;
1318         d->deleteDevice = false;
1319     }
1320
1321     d->reset();
1322     d->status = Ok;
1323     d->device = device;
1324     d->resetReadBuffer();
1325 #ifndef QT_NO_QOBJECT
1326     d->deviceClosedNotifier.setupDevice(this, d->device);
1327 #endif
1328 }
1329
1330 /*!
1331     Returns the current device associated with the QTextStream,
1332     or 0 if no device has been assigned.
1333
1334     \sa setDevice(), string()
1335 */
1336 QIODevice *QTextStream::device() const
1337 {
1338     Q_D(const QTextStream);
1339     return d->device;
1340 }
1341
1342 /*!
1343     Sets the current string to \a string, using the given \a
1344     openMode. If a device has already been assigned, QTextStream will
1345     call flush() before replacing it.
1346
1347     \sa string(), setDevice()
1348 */
1349 void QTextStream::setString(QString *string, QIODevice::OpenMode openMode)
1350 {
1351     Q_D(QTextStream);
1352     flush();
1353     if (d->deleteDevice) {
1354 #ifndef QT_NO_QOBJECT
1355         d->deviceClosedNotifier.disconnect();
1356         d->device->blockSignals(true);
1357 #endif
1358         delete d->device;
1359         d->deleteDevice = false;
1360     }
1361
1362     d->reset();
1363     d->status = Ok;
1364     d->string = string;
1365     d->stringOpenMode = openMode;
1366 }
1367
1368 /*!
1369     Returns the current string assigned to the QTextStream, or 0 if no
1370     string has been assigned.
1371
1372     \sa setString(), device()
1373 */
1374 QString *QTextStream::string() const
1375 {
1376     Q_D(const QTextStream);
1377     return d->string;
1378 }
1379
1380 /*!
1381     Sets the field alignment to \a mode. When used together with
1382     setFieldWidth(), this function allows you to generate formatted
1383     output with text aligned to the left, to the right or center
1384     aligned.
1385
1386     \sa fieldAlignment(), setFieldWidth()
1387 */
1388 void QTextStream::setFieldAlignment(FieldAlignment mode)
1389 {
1390     Q_D(QTextStream);
1391     d->fieldAlignment = mode;
1392 }
1393
1394 /*!
1395     Returns the current field alignment.
1396
1397     \sa setFieldAlignment(), fieldWidth()
1398 */
1399 QTextStream::FieldAlignment QTextStream::fieldAlignment() const
1400 {
1401     Q_D(const QTextStream);
1402     return d->fieldAlignment;
1403 }
1404
1405 /*!
1406     Sets the pad character to \a ch. The default value is the ASCII
1407     space character (' '), or QChar(0x20). This character is used to
1408     fill in the space in fields when generating text.
1409
1410     Example:
1411
1412     \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 5
1413
1414     The string \c s contains:
1415
1416     \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 6
1417
1418     \sa padChar(), setFieldWidth()
1419 */
1420 void QTextStream::setPadChar(QChar ch)
1421 {
1422     Q_D(QTextStream);
1423     d->padChar = ch;
1424 }
1425
1426 /*!
1427     Returns the current pad character.
1428
1429     \sa setPadChar(), setFieldWidth()
1430 */
1431 QChar QTextStream::padChar() const
1432 {
1433     Q_D(const QTextStream);
1434     return d->padChar;
1435 }
1436
1437 /*!
1438     Sets the current field width to \a width. If \a width is 0 (the
1439     default), the field width is equal to the length of the generated
1440     text.
1441
1442     \note The field width applies to every element appended to this
1443     stream after this function has been called (e.g., it also pads
1444     endl). This behavior is different from similar classes in the STL,
1445     where the field width only applies to the next element.
1446
1447     \sa fieldWidth(), setPadChar()
1448 */
1449 void QTextStream::setFieldWidth(int width)
1450 {
1451     Q_D(QTextStream);
1452     d->fieldWidth = width;
1453 }
1454
1455 /*!
1456     Returns the current field width.
1457
1458     \sa setFieldWidth()
1459 */
1460 int QTextStream::fieldWidth() const
1461 {
1462     Q_D(const QTextStream);
1463     return d->fieldWidth;
1464 }
1465
1466 /*!
1467     Sets the current number flags to \a flags. \a flags is a set of
1468     flags from the NumberFlag enum, and describes options for
1469     formatting generated code (e.g., whether or not to always write
1470     the base or sign of a number).
1471
1472     \sa numberFlags(), setIntegerBase(), setRealNumberNotation()
1473 */
1474 void QTextStream::setNumberFlags(NumberFlags flags)
1475 {
1476     Q_D(QTextStream);
1477     d->numberFlags = flags;
1478 }
1479
1480 /*!
1481     Returns the current number flags.
1482
1483     \sa setNumberFlags(), integerBase(), realNumberNotation()
1484 */
1485 QTextStream::NumberFlags QTextStream::numberFlags() const
1486 {
1487     Q_D(const QTextStream);
1488     return d->numberFlags;
1489 }
1490
1491 /*!
1492     Sets the base of integers to \a base, both for reading and for
1493     generating numbers. \a base can be either 2 (binary), 8 (octal),
1494     10 (decimal) or 16 (hexadecimal). If \a base is 0, QTextStream
1495     will attempt to detect the base by inspecting the data on the
1496     stream. When generating numbers, QTextStream assumes base is 10
1497     unless the base has been set explicitly.
1498
1499     \sa integerBase(), QString::number(), setNumberFlags()
1500 */
1501 void QTextStream::setIntegerBase(int base)
1502 {
1503     Q_D(QTextStream);
1504     d->integerBase = base;
1505 }
1506
1507 /*!
1508     Returns the current base of integers. 0 means that the base is
1509     detected when reading, or 10 (decimal) when generating numbers.
1510
1511     \sa setIntegerBase(), QString::number(), numberFlags()
1512 */
1513 int QTextStream::integerBase() const
1514 {
1515     Q_D(const QTextStream);
1516     return d->integerBase;
1517 }
1518
1519 /*!
1520     Sets the real number notation to \a notation (SmartNotation,
1521     FixedNotation, ScientificNotation). When reading and generating
1522     numbers, QTextStream uses this value to detect the formatting of
1523     real numbers.
1524
1525     \sa realNumberNotation(), setRealNumberPrecision(), setNumberFlags(), setIntegerBase()
1526 */
1527 void QTextStream::setRealNumberNotation(RealNumberNotation notation)
1528 {
1529     Q_D(QTextStream);
1530     d->realNumberNotation = notation;
1531 }
1532
1533 /*!
1534     Returns the current real number notation.
1535
1536     \sa setRealNumberNotation(), realNumberPrecision(), numberFlags(), integerBase()
1537 */
1538 QTextStream::RealNumberNotation QTextStream::realNumberNotation() const
1539 {
1540     Q_D(const QTextStream);
1541     return d->realNumberNotation;
1542 }
1543
1544 /*!
1545     Sets the precision of real numbers to \a precision. This value
1546     describes the number of fraction digits QTextStream should
1547     write when generating real numbers.
1548
1549     The precision cannot be a negative value. The default value is 6.
1550
1551     \sa realNumberPrecision(), setRealNumberNotation()
1552 */
1553 void QTextStream::setRealNumberPrecision(int precision)
1554 {
1555     Q_D(QTextStream);
1556     if (precision < 0) {
1557         qWarning("QTextStream::setRealNumberPrecision: Invalid precision (%d)", precision);
1558         d->realNumberPrecision = 6;
1559         return;
1560     }
1561     d->realNumberPrecision = precision;
1562 }
1563
1564 /*!
1565     Returns the current real number precision, or the number of fraction
1566     digits QTextStream will write when generating real numbers.
1567
1568     \sa setRealNumberNotation(), realNumberNotation(), numberFlags(), integerBase()
1569 */
1570 int QTextStream::realNumberPrecision() const
1571 {
1572     Q_D(const QTextStream);
1573     return d->realNumberPrecision;
1574 }
1575
1576 /*!
1577     Returns the status of the text stream.
1578
1579     \sa QTextStream::Status, setStatus(), resetStatus()
1580 */
1581
1582 QTextStream::Status QTextStream::status() const
1583 {
1584     Q_D(const QTextStream);
1585     return d->status;
1586 }
1587
1588 /*!
1589     \since 4.1
1590
1591     Resets the status of the text stream.
1592
1593     \sa QTextStream::Status, status(), setStatus()
1594 */
1595 void QTextStream::resetStatus()
1596 {
1597     Q_D(QTextStream);
1598     d->status = Ok;
1599 }
1600
1601 /*!
1602     \since 4.1
1603
1604     Sets the status of the text stream to the \a status given.
1605
1606     Subsequent calls to setStatus() are ignored until resetStatus()
1607     is called.
1608
1609     \sa Status status() resetStatus()
1610 */
1611 void QTextStream::setStatus(Status status)
1612 {
1613     Q_D(QTextStream);
1614     if (d->status == Ok)
1615         d->status = status;
1616 }
1617
1618 /*!
1619     Returns true if there is no more data to be read from the
1620     QTextStream; otherwise returns false. This is similar to, but not
1621     the same as calling QIODevice::atEnd(), as QTextStream also takes
1622     into account its internal Unicode buffer.
1623 */
1624 bool QTextStream::atEnd() const
1625 {
1626     Q_D(const QTextStream);
1627     CHECK_VALID_STREAM(true);
1628
1629     if (d->string)
1630         return d->string->size() == d->stringOffset;
1631     return d->readBuffer.isEmpty() && d->device->atEnd();
1632 }
1633
1634 /*!
1635     Reads the entire content of the stream, and returns it as a
1636     QString. Avoid this function when working on large files, as it
1637     will consume a significant amount of memory.
1638
1639     Calling readLine() is better if you do not know how much data is
1640     available.
1641
1642     \sa readLine()
1643 */
1644 QString QTextStream::readAll()
1645 {
1646     Q_D(QTextStream);
1647     CHECK_VALID_STREAM(QString());
1648
1649     return d->read(INT_MAX);
1650 }
1651
1652 /*!
1653     Reads one line of text from the stream, and returns it as a
1654     QString. The maximum allowed line length is set to \a maxlen. If
1655     the stream contains lines longer than this, then the lines will be
1656     split after \a maxlen characters and returned in parts.
1657
1658     If \a maxlen is 0, the lines can be of any length. A common value
1659     for \a maxlen is 75.
1660
1661     The returned line has no trailing end-of-line characters ("\\n"
1662     or "\\r\\n"), so calling QString::trimmed() is unnecessary.
1663
1664     If the stream has read to the end of the file, readLine() will return a
1665     null QString. For strings, or for devices that support it, you can
1666     explicitly test for the end of the stream using atEnd().
1667
1668     \sa readAll(), QIODevice::readLine()
1669 */
1670 QString QTextStream::readLine(qint64 maxlen)
1671 {
1672     Q_D(QTextStream);
1673     CHECK_VALID_STREAM(QString());
1674
1675     const QChar *readPtr;
1676     int length;
1677     if (!d->scan(&readPtr, &length, int(maxlen), QTextStreamPrivate::EndOfLine))
1678         return QString();
1679
1680     QString tmp = QString(readPtr, length);
1681     d->consumeLastToken();
1682     return tmp;
1683 }
1684
1685 /*!
1686     \since 4.1
1687
1688     Reads at most \a maxlen characters from the stream, and returns the data
1689     read as a QString.
1690
1691     \sa readAll(), readLine(), QIODevice::read()
1692 */
1693 QString QTextStream::read(qint64 maxlen)
1694 {
1695     Q_D(QTextStream);
1696     CHECK_VALID_STREAM(QString());
1697
1698     if (maxlen <= 0)
1699         return QString::fromLatin1("");     // empty, not null
1700
1701     return d->read(int(maxlen));
1702 }
1703
1704 /*! \internal
1705 */
1706 QTextStreamPrivate::NumberParsingStatus QTextStreamPrivate::getNumber(qulonglong *ret)
1707 {
1708     scan(0, 0, 0, NotSpace);
1709     consumeLastToken();
1710
1711     // detect int encoding
1712     int base = integerBase;
1713     if (base == 0) {
1714         QChar ch;
1715         if (!getChar(&ch))
1716             return npsInvalidPrefix;
1717         if (ch == QLatin1Char('0')) {
1718             QChar ch2;
1719             if (!getChar(&ch2)) {
1720                 // Result is the number 0
1721                 *ret = 0;
1722                 return npsOk;
1723             }
1724             ch2 = ch2.toLower();
1725
1726             if (ch2 == QLatin1Char('x')) {
1727                 base = 16;
1728             } else if (ch2 == QLatin1Char('b')) {
1729                 base = 2;
1730             } else if (ch2.isDigit() && ch2.digitValue() >= 0 && ch2.digitValue() <= 7) {
1731                 base = 8;
1732             } else {
1733                 base = 10;
1734             }
1735             ungetChar(ch2);
1736         } else if (ch == locale.negativeSign() || ch == locale.positiveSign() || ch.isDigit()) {
1737             base = 10;
1738         } else {
1739             ungetChar(ch);
1740             return npsInvalidPrefix;
1741         }
1742         ungetChar(ch);
1743         // State of the stream is now the same as on entry
1744         // (cursor is at prefix),
1745         // and local variable 'base' has been set appropriately.
1746     }
1747
1748     qulonglong val=0;
1749     switch (base) {
1750     case 2: {
1751         QChar pf1, pf2, dig;
1752         // Parse prefix '0b'
1753         if (!getChar(&pf1) || pf1 != QLatin1Char('0'))
1754             return npsInvalidPrefix;
1755         if (!getChar(&pf2) || pf2.toLower() != QLatin1Char('b'))
1756             return npsInvalidPrefix;
1757         // Parse digits
1758         int ndigits = 0;
1759         while (getChar(&dig)) {
1760             int n = dig.toLower().unicode();
1761             if (n == '0' || n == '1') {
1762                 val <<= 1;
1763                 val += n - '0';
1764             } else {
1765                 ungetChar(dig);
1766                 break;
1767             }
1768             ndigits++;
1769         }
1770         if (ndigits == 0) {
1771             // Unwind the prefix and abort
1772             ungetChar(pf2);
1773             ungetChar(pf1);
1774             return npsMissingDigit;
1775         }
1776         break;
1777     }
1778     case 8: {
1779         QChar pf, dig;
1780         // Parse prefix '0'
1781         if (!getChar(&pf) || pf != QLatin1Char('0'))
1782             return npsInvalidPrefix;
1783         // Parse digits
1784         int ndigits = 0;
1785         while (getChar(&dig)) {
1786             int n = dig.toLower().unicode();
1787             if (n >= '0' && n <= '7') {
1788                 val *= 8;
1789                 val += n - '0';
1790             } else {
1791                 ungetChar(dig);
1792                 break;
1793             }
1794             ndigits++;
1795         }
1796         if (ndigits == 0) {
1797             // Unwind the prefix and abort
1798             ungetChar(pf);
1799             return npsMissingDigit;
1800         }
1801         break;
1802     }
1803     case 10: {
1804         // Parse sign (or first digit)
1805         QChar sign;
1806         int ndigits = 0;
1807         if (!getChar(&sign))
1808             return npsMissingDigit;
1809         if (sign != locale.negativeSign() && sign != locale.positiveSign()) {
1810             if (!sign.isDigit()) {
1811                 ungetChar(sign);
1812                 return npsMissingDigit;
1813             }
1814             val += sign.digitValue();
1815             ndigits++;
1816         }
1817         // Parse digits
1818         QChar ch;
1819         while (getChar(&ch)) {
1820             if (ch.isDigit()) {
1821                 val *= 10;
1822                 val += ch.digitValue();
1823             } else if (locale != QLocale::c() && ch == locale.groupSeparator()) {
1824                 continue;
1825             } else {
1826                 ungetChar(ch);
1827                 break;
1828             }
1829             ndigits++;
1830         }
1831         if (ndigits == 0)
1832             return npsMissingDigit;
1833         if (sign == locale.negativeSign()) {
1834             qlonglong ival = qlonglong(val);
1835             if (ival > 0)
1836                 ival = -ival;
1837             val = qulonglong(ival);
1838         }
1839         break;
1840     }
1841     case 16: {
1842         QChar pf1, pf2, dig;
1843         // Parse prefix ' 0x'
1844         if (!getChar(&pf1) || pf1 != QLatin1Char('0'))
1845             return npsInvalidPrefix;
1846         if (!getChar(&pf2) || pf2.toLower() != QLatin1Char('x'))
1847             return npsInvalidPrefix;
1848         // Parse digits
1849         int ndigits = 0;
1850         while (getChar(&dig)) {
1851             int n = dig.toLower().unicode();
1852             if (n >= '0' && n <= '9') {
1853                 val <<= 4;
1854                 val += n - '0';
1855             } else if (n >= 'a' && n <= 'f') {
1856                 val <<= 4;
1857                 val += 10 + (n - 'a');
1858             } else {
1859                 ungetChar(dig);
1860                 break;
1861             }
1862             ndigits++;
1863         }
1864         if (ndigits == 0) {
1865             return npsMissingDigit;
1866         }
1867         break;
1868     }
1869     default:
1870         // Unsupported integerBase
1871         return npsInvalidPrefix;
1872     }
1873
1874     if (ret)
1875         *ret = val;
1876     return npsOk;
1877 }
1878
1879 /*! \internal
1880     (hihi)
1881 */
1882 bool QTextStreamPrivate::getReal(double *f)
1883 {
1884     // We use a table-driven FSM to parse floating point numbers
1885     // strtod() cannot be used directly since we may be reading from a
1886     // QIODevice.
1887     enum ParserState {
1888         Init = 0,
1889         Sign = 1,
1890         Mantissa = 2,
1891         Dot = 3,
1892         Abscissa = 4,
1893         ExpMark = 5,
1894         ExpSign = 6,
1895         Exponent = 7,
1896         Nan1 = 8,
1897         Nan2 = 9,
1898         Inf1 = 10,
1899         Inf2 = 11,
1900         NanInf = 12,
1901         Done = 13
1902     };
1903     enum InputToken {
1904         None = 0,
1905         InputSign = 1,
1906         InputDigit = 2,
1907         InputDot = 3,
1908         InputExp = 4,
1909         InputI = 5,
1910         InputN = 6,
1911         InputF = 7,
1912         InputA = 8,
1913         InputT = 9
1914     };
1915
1916     static const uchar table[13][10] = {
1917         // None InputSign InputDigit InputDot InputExp InputI    InputN    InputF    InputA    InputT
1918         { 0,    Sign,     Mantissa,  Dot,     0,       Inf1,     Nan1,     0,        0,        0      }, // 0  Init
1919         { 0,    0,        Mantissa,  Dot,     0,       Inf1,     Nan1,     0,        0,        0      }, // 1  Sign
1920         { Done, Done,     Mantissa,  Dot,     ExpMark, 0,        0,        0,        0,        0      }, // 2  Mantissa
1921         { 0,    0,        Abscissa,  0,       0,       0,        0,        0,        0,        0      }, // 3  Dot
1922         { Done, Done,     Abscissa,  Done,    ExpMark, 0,        0,        0,        0,        0      }, // 4  Abscissa
1923         { 0,    ExpSign,  Exponent,  0,       0,       0,        0,        0,        0,        0      }, // 5  ExpMark
1924         { 0,    0,        Exponent,  0,       0,       0,        0,        0,        0,        0      }, // 6  ExpSign
1925         { Done, Done,     Exponent,  Done,    Done,    0,        0,        0,        0,        0      }, // 7  Exponent
1926         { 0,    0,        0,         0,       0,       0,        0,        0,        Nan2,     0      }, // 8  Nan1
1927         { 0,    0,        0,         0,       0,       0,        NanInf,   0,        0,        0      }, // 9  Nan2
1928         { 0,    0,        0,         0,       0,       0,        Inf2,     0,        0,        0      }, // 10 Inf1
1929         { 0,    0,        0,         0,       0,       0,        0,        NanInf,   0,        0      }, // 11 Inf2
1930         { Done, 0,        0,         0,       0,       0,        0,        0,        0,        0      }, // 11 NanInf
1931     };
1932
1933     ParserState state = Init;
1934     InputToken input = None;
1935
1936     scan(0, 0, 0, NotSpace);
1937     consumeLastToken();
1938
1939     const int BufferSize = 128;
1940     char buf[BufferSize];
1941     int i = 0;
1942
1943     QChar c;
1944     while (getChar(&c)) {
1945         switch (c.unicode()) {
1946         case '0': case '1': case '2': case '3': case '4':
1947         case '5': case '6': case '7': case '8': case '9':
1948             input = InputDigit;
1949             break;
1950         case 'i': case 'I':
1951             input = InputI;
1952             break;
1953         case 'n': case 'N':
1954             input = InputN;
1955             break;
1956         case 'f': case 'F':
1957             input = InputF;
1958             break;
1959         case 'a': case 'A':
1960             input = InputA;
1961             break;
1962         case 't': case 'T':
1963             input = InputT;
1964             break;
1965         default: {
1966             QChar lc = c.toLower();
1967             if (lc == locale.decimalPoint().toLower())
1968                 input = InputDot;
1969             else if (lc == locale.exponential().toLower())
1970                 input = InputExp;
1971             else if (lc == locale.negativeSign().toLower()
1972                      || lc == locale.positiveSign().toLower())
1973                 input = InputSign;
1974             else if (locale != QLocale::c() // backward-compatibility
1975                      && lc == locale.groupSeparator().toLower())
1976                 input = InputDigit; // well, it isn't a digit, but no one cares.
1977             else
1978                 input = None;
1979         }
1980             break;
1981         }
1982
1983         state = ParserState(table[state][input]);
1984
1985         if  (state == Init || state == Done || i > (BufferSize - 5)) {
1986             ungetChar(c);
1987             if (i > (BufferSize - 5)) { // ignore rest of digits
1988                 while (getChar(&c)) {
1989                     if (!c.isDigit()) {
1990                         ungetChar(c);
1991                         break;
1992                     }
1993                 }
1994             }
1995             break;
1996         }
1997
1998         buf[i++] = c.toLatin1();
1999     }
2000
2001     if (i == 0)
2002         return false;
2003     if (!f)
2004         return true;
2005     buf[i] = '\0';
2006
2007     // backward-compatibility. Old implementation supported +nan/-nan
2008     // for some reason. QLocale only checks for lower-case
2009     // nan/+inf/-inf, so here we also check for uppercase and mixed
2010     // case versions.
2011     if (!qstricmp(buf, "nan") || !qstricmp(buf, "+nan") || !qstricmp(buf, "-nan")) {
2012         *f = qSNaN();
2013         return true;
2014     } else if (!qstricmp(buf, "+inf") || !qstricmp(buf, "inf")) {
2015         *f = qInf();
2016         return true;
2017     } else if (!qstricmp(buf, "-inf")) {
2018         *f = -qInf();
2019         return true;
2020     }
2021     bool ok;
2022     *f = locale.toDouble(QString::fromLatin1(buf), &ok);
2023     return ok;
2024 }
2025
2026 /*!
2027     Reads a character from the stream and stores it in \a c. Returns a
2028     reference to the QTextStream, so several operators can be
2029     nested. Example:
2030
2031     \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 7
2032
2033     Whitespace is \e not skipped.
2034 */
2035
2036 QTextStream &QTextStream::operator>>(QChar &c)
2037 {
2038     Q_D(QTextStream);
2039     CHECK_VALID_STREAM(*this);
2040     d->scan(0, 0, 0, QTextStreamPrivate::NotSpace);
2041     if (!d->getChar(&c))
2042         setStatus(ReadPastEnd);
2043     return *this;
2044 }
2045
2046 /*!
2047     \overload
2048
2049     Reads a character from the stream and stores it in \a c. The
2050     character from the stream is converted to ISO-5589-1 before it is
2051     stored.
2052
2053     \sa QChar::toLatin1()
2054 */
2055 QTextStream &QTextStream::operator>>(char &c)
2056 {
2057     QChar ch;
2058     *this >> ch;
2059     c = ch.toLatin1();
2060     return *this;
2061 }
2062
2063 /*!
2064     Reads an integer from the stream and stores it in \a i, then
2065     returns a reference to the QTextStream. The number is cast to
2066     the correct type before it is stored. If no number was detected on
2067     the stream, \a i is set to 0.
2068
2069     By default, QTextStream will attempt to detect the base of the
2070     number using the following rules:
2071
2072     \table
2073     \header \o Prefix                \o Base
2074     \row    \o "0b" or "0B"          \o 2 (binary)
2075     \row    \o "0" followed by "0-7" \o 8 (octal)
2076     \row    \o "0" otherwise         \o 10 (decimal)
2077     \row    \o "0x" or "0X"          \o 16 (hexadecimal)
2078     \row    \o "1" to "9"            \o 10 (decimal)
2079     \endtable
2080
2081     By calling setIntegerBase(), you can specify the integer base
2082     explicitly. This will disable the auto-detection, and speed up
2083     QTextStream slightly.
2084
2085     Leading whitespace is skipped.
2086 */
2087 QTextStream &QTextStream::operator>>(signed short &i)
2088 {
2089     IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(signed short);
2090 }
2091
2092 /*!
2093     \overload
2094
2095     Stores the integer in the unsigned short \a i.
2096 */
2097 QTextStream &QTextStream::operator>>(unsigned short &i)
2098 {
2099     IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(unsigned short);
2100 }
2101
2102 /*!
2103     \overload
2104
2105     Stores the integer in the signed int \a i.
2106 */
2107 QTextStream &QTextStream::operator>>(signed int &i)
2108 {
2109     IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(signed int);
2110 }
2111
2112 /*!
2113     \overload
2114
2115     Stores the integer in the unsigned int \a i.
2116 */
2117 QTextStream &QTextStream::operator>>(unsigned int &i)
2118 {
2119     IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(unsigned int);
2120 }
2121
2122 /*!
2123     \overload
2124
2125     Stores the integer in the signed long \a i.
2126 */
2127 QTextStream &QTextStream::operator>>(signed long &i)
2128 {
2129     IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(signed long);
2130 }
2131
2132 /*!
2133     \overload
2134
2135     Stores the integer in the unsigned long \a i.
2136 */
2137 QTextStream &QTextStream::operator>>(unsigned long &i)
2138 {
2139     IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(unsigned long);
2140 }
2141
2142 /*!
2143     \overload
2144
2145     Stores the integer in the qlonglong \a i.
2146 */
2147 QTextStream &QTextStream::operator>>(qlonglong &i)
2148 {
2149     IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(qlonglong);
2150 }
2151
2152 /*!
2153     \overload
2154
2155     Stores the integer in the qulonglong \a i.
2156 */
2157 QTextStream &QTextStream::operator>>(qulonglong &i)
2158 {
2159     IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(qulonglong);
2160 }
2161
2162 /*!
2163     Reads a real number from the stream and stores it in \a f, then
2164     returns a reference to the QTextStream. The number is cast to
2165     the correct type. If no real number is detect on the stream, \a f
2166     is set to 0.0.
2167
2168     As a special exception, QTextStream allows the strings "nan" and "inf" to
2169     represent NAN and INF floats or doubles.
2170
2171     Leading whitespace is skipped.
2172 */
2173 QTextStream &QTextStream::operator>>(float &f)
2174 {
2175     IMPLEMENT_STREAM_RIGHT_REAL_OPERATOR(float);
2176 }
2177
2178 /*!
2179     \overload
2180
2181     Stores the real number in the double \a f.
2182 */
2183 QTextStream &QTextStream::operator>>(double &f)
2184 {
2185     IMPLEMENT_STREAM_RIGHT_REAL_OPERATOR(double);
2186 }
2187
2188 /*!
2189     Reads a word from the stream and stores it in \a str, then returns
2190     a reference to the stream. Words are separated by whitespace
2191     (i.e., all characters for which QChar::isSpace() returns true).
2192
2193     Leading whitespace is skipped.
2194 */
2195 QTextStream &QTextStream::operator>>(QString &str)
2196 {
2197     Q_D(QTextStream);
2198     CHECK_VALID_STREAM(*this);
2199
2200     str.clear();
2201     d->scan(0, 0, 0, QTextStreamPrivate::NotSpace);
2202     d->consumeLastToken();
2203
2204     const QChar *ptr;
2205     int length;
2206     if (!d->scan(&ptr, &length, 0, QTextStreamPrivate::Space)) {
2207         setStatus(ReadPastEnd);
2208         return *this;
2209     }
2210
2211     str = QString(ptr, length);
2212     d->consumeLastToken();
2213     return *this;
2214 }
2215
2216 /*!
2217     \overload
2218
2219     Converts the word to ISO-8859-1, then stores it in \a array.
2220
2221     \sa QString::toLatin1()
2222 */
2223 QTextStream &QTextStream::operator>>(QByteArray &array)
2224 {
2225     Q_D(QTextStream);
2226     CHECK_VALID_STREAM(*this);
2227
2228     array.clear();
2229     d->scan(0, 0, 0, QTextStreamPrivate::NotSpace);
2230     d->consumeLastToken();
2231
2232     const QChar *ptr;
2233     int length;
2234     if (!d->scan(&ptr, &length, 0, QTextStreamPrivate::Space)) {
2235         setStatus(ReadPastEnd);
2236         return *this;
2237     }
2238
2239     for (int i = 0; i < length; ++i)
2240         array += ptr[i].toLatin1();
2241
2242     d->consumeLastToken();
2243     return *this;
2244 }
2245
2246 /*!
2247     \overload
2248
2249     Stores the word in \a c, terminated by a '\0' character. If no word is
2250     available, only the '\0' character is stored.
2251
2252     Warning: Although convenient, this operator is dangerous and must
2253     be used with care. QTextStream assumes that \a c points to a
2254     buffer with enough space to hold the word. If the buffer is too
2255     small, your application may crash.
2256
2257     If possible, use the QByteArray operator instead.
2258 */
2259 QTextStream &QTextStream::operator>>(char *c)
2260 {
2261     Q_D(QTextStream);
2262     *c = 0;
2263     CHECK_VALID_STREAM(*this);
2264     d->scan(0, 0, 0, QTextStreamPrivate::NotSpace);
2265     d->consumeLastToken();
2266
2267     const QChar *ptr;
2268     int length;
2269     if (!d->scan(&ptr, &length, 0, QTextStreamPrivate::Space)) {
2270         setStatus(ReadPastEnd);
2271         return *this;
2272     }
2273
2274     for (int i = 0; i < length; ++i)
2275         *c++ = ptr[i].toLatin1();
2276     *c = '\0';
2277     d->consumeLastToken();
2278     return *this;
2279 }
2280
2281 /*! \internal
2282  */
2283 void QTextStreamPrivate::putNumber(qulonglong number, bool negative)
2284 {
2285     QString result;
2286
2287     unsigned flags = 0;
2288     if (numberFlags & QTextStream::ShowBase)
2289         flags |= QLocalePrivate::ShowBase;
2290     if (numberFlags & QTextStream::ForceSign)
2291         flags |= QLocalePrivate::AlwaysShowSign;
2292     if (numberFlags & QTextStream::UppercaseBase)
2293         flags |= QLocalePrivate::UppercaseBase;
2294     if (numberFlags & QTextStream::UppercaseDigits)
2295         flags |= QLocalePrivate::CapitalEorX;
2296
2297     // add thousands group separators. For backward compatibility we
2298     // don't add a group separator for C locale.
2299     if (locale != QLocale::c())
2300         flags |= QLocalePrivate::ThousandsGroup;
2301
2302     const QLocalePrivate *dd = locale.d();
2303     int base = integerBase ? integerBase : 10;
2304     if (negative && base == 10) {
2305         result = dd->longLongToString(-static_cast<qlonglong>(number), -1,
2306                                       base, -1, flags);
2307     } else if (negative) {
2308         // Workaround for backward compatibility for writing negative
2309         // numbers in octal and hex:
2310         // QTextStream(result) << showbase << hex << -1 << oct << -1
2311         // should output: -0x1 -0b1
2312         result = dd->unsLongLongToString(number, -1, base, -1, flags);
2313         result.prepend(locale.negativeSign());
2314     } else {
2315         result = dd->unsLongLongToString(number, -1, base, -1, flags);
2316         // workaround for backward compatibility - in octal form with
2317         // ShowBase flag set zero should be written as '00'
2318         if (number == 0 && base == 8 && numberFlags & QTextStream::ShowBase
2319             && result == QLatin1String("0")) {
2320             result.prepend(QLatin1Char('0'));
2321         }
2322     }
2323     putString(result, true);
2324 }
2325
2326 /*!
2327     Writes the character \a c to the stream, then returns a reference
2328     to the QTextStream.
2329
2330     \sa setFieldWidth()
2331 */
2332 QTextStream &QTextStream::operator<<(QChar c)
2333 {
2334     Q_D(QTextStream);
2335     CHECK_VALID_STREAM(*this);
2336     d->putString(QString(c));
2337     return *this;
2338 }
2339
2340 /*!
2341     \overload
2342
2343     Converts \a c from ASCII to a QChar, then writes it to the stream.
2344 */
2345 QTextStream &QTextStream::operator<<(char c)
2346 {
2347     Q_D(QTextStream);
2348     CHECK_VALID_STREAM(*this);
2349     d->putString(QString(QChar::fromAscii(c)));
2350     return *this;
2351 }
2352
2353 /*!
2354     Writes the integer number \a i to the stream, then returns a
2355     reference to the QTextStream. By default, the number is stored in
2356     decimal form, but you can also set the base by calling
2357     setIntegerBase().
2358
2359     \sa setFieldWidth(), setNumberFlags()
2360 */
2361 QTextStream &QTextStream::operator<<(signed short i)
2362 {
2363     Q_D(QTextStream);
2364     CHECK_VALID_STREAM(*this);
2365     d->putNumber((qulonglong)qAbs(qlonglong(i)), i < 0);
2366     return *this;
2367 }
2368
2369 /*!
2370     \overload
2371
2372     Writes the unsigned short \a i to the stream.
2373 */
2374 QTextStream &QTextStream::operator<<(unsigned short i)
2375 {
2376     Q_D(QTextStream);
2377     CHECK_VALID_STREAM(*this);
2378     d->putNumber((qulonglong)i, false);
2379     return *this;
2380 }
2381
2382 /*!
2383     \overload
2384
2385     Writes the signed int \a i to the stream.
2386 */
2387 QTextStream &QTextStream::operator<<(signed int i)
2388 {
2389     Q_D(QTextStream);
2390     CHECK_VALID_STREAM(*this);
2391     d->putNumber((qulonglong)qAbs(qlonglong(i)), i < 0);
2392     return *this;
2393 }
2394
2395 /*!
2396     \overload
2397
2398     Writes the unsigned int \a i to the stream.
2399 */
2400 QTextStream &QTextStream::operator<<(unsigned int i)
2401 {
2402     Q_D(QTextStream);
2403     CHECK_VALID_STREAM(*this);
2404     d->putNumber((qulonglong)i, false);
2405     return *this;
2406 }
2407
2408 /*!
2409     \overload
2410
2411     Writes the signed long \a i to the stream.
2412 */
2413 QTextStream &QTextStream::operator<<(signed long i)
2414 {
2415     Q_D(QTextStream);
2416     CHECK_VALID_STREAM(*this);
2417     d->putNumber((qulonglong)qAbs(qlonglong(i)), i < 0);
2418     return *this;
2419 }
2420
2421 /*!
2422     \overload
2423
2424     Writes the unsigned long \a i to the stream.
2425 */
2426 QTextStream &QTextStream::operator<<(unsigned long i)
2427 {
2428     Q_D(QTextStream);
2429     CHECK_VALID_STREAM(*this);
2430     d->putNumber((qulonglong)i, false);
2431     return *this;
2432 }
2433
2434 /*!
2435     \overload
2436
2437     Writes the qlonglong \a i to the stream.
2438 */
2439 QTextStream &QTextStream::operator<<(qlonglong i)
2440 {
2441     Q_D(QTextStream);
2442     CHECK_VALID_STREAM(*this);
2443     d->putNumber((qulonglong)qAbs(i), i < 0);
2444     return *this;
2445 }
2446
2447 /*!
2448     \overload
2449
2450     Writes the qulonglong \a i to the stream.
2451 */
2452 QTextStream &QTextStream::operator<<(qulonglong i)
2453 {
2454     Q_D(QTextStream);
2455     CHECK_VALID_STREAM(*this);
2456     d->putNumber(i, false);
2457     return *this;
2458 }
2459
2460 /*!
2461     Writes the real number \a f to the stream, then returns a
2462     reference to the QTextStream. By default, QTextStream stores it
2463     using SmartNotation, with up to 6 digits of precision. You can
2464     change the textual representation QTextStream will use for real
2465     numbers by calling setRealNumberNotation(),
2466     setRealNumberPrecision() and setNumberFlags().
2467
2468     \sa setFieldWidth(), setRealNumberNotation(),
2469     setRealNumberPrecision(), setNumberFlags()
2470 */
2471 QTextStream &QTextStream::operator<<(float f)
2472 {
2473     return *this << double(f);
2474 }
2475
2476 /*!
2477     \overload
2478
2479     Writes the double \a f to the stream.
2480 */
2481 QTextStream &QTextStream::operator<<(double f)
2482 {
2483     Q_D(QTextStream);
2484     CHECK_VALID_STREAM(*this);
2485
2486     QLocalePrivate::DoubleForm form = QLocalePrivate::DFDecimal;
2487     switch (realNumberNotation()) {
2488     case FixedNotation:
2489         form = QLocalePrivate::DFDecimal;
2490         break;
2491     case ScientificNotation:
2492         form = QLocalePrivate::DFExponent;
2493         break;
2494     case SmartNotation:
2495         form = QLocalePrivate::DFSignificantDigits;
2496         break;
2497     }
2498
2499     uint flags = 0;
2500     if (numberFlags() & ShowBase)
2501         flags |= QLocalePrivate::ShowBase;
2502     if (numberFlags() & ForceSign)
2503         flags |= QLocalePrivate::AlwaysShowSign;
2504     if (numberFlags() & UppercaseBase)
2505         flags |= QLocalePrivate::UppercaseBase;
2506     if (numberFlags() & UppercaseDigits)
2507         flags |= QLocalePrivate::CapitalEorX;
2508     if (numberFlags() & ForcePoint)
2509         flags |= QLocalePrivate::Alternate;
2510
2511     const QLocalePrivate *dd = d->locale.d();
2512     QString num = dd->doubleToString(f, d->realNumberPrecision, form, -1, flags);
2513     d->putString(num, true);
2514     return *this;
2515 }
2516
2517 /*!
2518     Writes the string \a string to the stream, and returns a reference
2519     to the QTextStream. The string is first encoded using the assigned
2520     codec (the default codec is QTextCodec::codecForLocale()) before
2521     it is written to the stream.
2522
2523     \sa setFieldWidth(), setCodec()
2524 */
2525 QTextStream &QTextStream::operator<<(const QString &string)
2526 {
2527     Q_D(QTextStream);
2528     CHECK_VALID_STREAM(*this);
2529     d->putString(string);
2530     return *this;
2531 }
2532
2533 /*!
2534     \overload
2535
2536     Writes \a string to the stream, and returns a reference to the
2537     QTextStream. The contents of \a string are converted with the
2538     QString constructor that takes a QLatin1String as argument.
2539 */
2540 QTextStream &QTextStream::operator<<(const QLatin1String &string)
2541 {
2542     Q_D(QTextStream);
2543     CHECK_VALID_STREAM(*this);
2544     d->putString(QString(string));
2545     return *this;
2546 }
2547
2548 /*!
2549     \overload
2550
2551     Writes \a array to the stream. The contents of \a array are
2552     converted with QString::fromAscii().
2553 */
2554 QTextStream &QTextStream::operator<<(const QByteArray &array)
2555 {
2556     Q_D(QTextStream);
2557     CHECK_VALID_STREAM(*this);
2558     d->putString(QString::fromAscii(array.constData(), array.length()));
2559     return *this;
2560 }
2561
2562 /*!
2563     \overload
2564
2565     Writes the constant string pointed to by \a string to the stream. \a
2566     string is assumed to be in ISO-8859-1 encoding. This operator
2567     is convenient when working with constant string data. Example:
2568
2569     \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 8
2570
2571     Warning: QTextStream assumes that \a string points to a string of
2572     text, terminated by a '\0' character. If there is no terminating
2573     '\0' character, your application may crash.
2574 */
2575 QTextStream &QTextStream::operator<<(const char *string)
2576 {
2577     Q_D(QTextStream);
2578     CHECK_VALID_STREAM(*this);
2579     d->putString(QLatin1String(string));
2580     return *this;
2581 }
2582
2583 /*!
2584     \overload
2585
2586     Writes \a ptr to the stream as a hexadecimal number with a base.
2587 */
2588
2589 QTextStream &QTextStream::operator<<(const void *ptr)
2590 {
2591     Q_D(QTextStream);
2592     CHECK_VALID_STREAM(*this);
2593     int oldBase = d->integerBase;
2594     NumberFlags oldFlags = d->numberFlags;
2595     d->integerBase = 16;
2596     d->numberFlags |= ShowBase;
2597     d->putNumber(reinterpret_cast<quintptr>(ptr), false);
2598     d->integerBase = oldBase;
2599     d->numberFlags = oldFlags;
2600     return *this;
2601 }
2602
2603 /*!
2604     \relates QTextStream
2605
2606     Calls QTextStream::setIntegerBase(2) on \a stream and returns \a
2607     stream.
2608
2609     \sa oct(), dec(), hex(), {QTextStream manipulators}
2610 */
2611 QTextStream &bin(QTextStream &stream)
2612 {
2613     stream.setIntegerBase(2);
2614     return stream;
2615 }
2616
2617 /*!
2618     \relates QTextStream
2619
2620     Calls QTextStream::setIntegerBase(8) on \a stream and returns \a
2621     stream.
2622
2623     \sa bin(), dec(), hex(), {QTextStream manipulators}
2624 */
2625 QTextStream &oct(QTextStream &stream)
2626 {
2627     stream.setIntegerBase(8);
2628     return stream;
2629 }
2630
2631 /*!
2632     \relates QTextStream
2633
2634     Calls QTextStream::setIntegerBase(10) on \a stream and returns \a
2635     stream.
2636
2637     \sa bin(), oct(), hex(), {QTextStream manipulators}
2638 */
2639 QTextStream &dec(QTextStream &stream)
2640 {
2641     stream.setIntegerBase(10);
2642     return stream;
2643 }
2644
2645 /*!
2646     \relates QTextStream
2647
2648     Calls QTextStream::setIntegerBase(16) on \a stream and returns \a
2649     stream.
2650
2651     \note The hex modifier can only be used for writing to streams.
2652     \sa bin(), oct(), dec(), {QTextStream manipulators}
2653 */
2654 QTextStream &hex(QTextStream &stream)
2655 {
2656     stream.setIntegerBase(16);
2657     return stream;
2658 }
2659
2660 /*!
2661     \relates QTextStream
2662
2663     Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2664     QTextStream::ShowBase) on \a stream and returns \a stream.
2665
2666     \sa noshowbase(), forcesign(), forcepoint(), {QTextStream manipulators}
2667 */
2668 QTextStream &showbase(QTextStream &stream)
2669 {
2670     stream.setNumberFlags(stream.numberFlags() | QTextStream::ShowBase);
2671     return stream;
2672 }
2673
2674 /*!
2675     \relates QTextStream
2676
2677     Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2678     QTextStream::ForceSign) on \a stream and returns \a stream.
2679
2680     \sa noforcesign(), forcepoint(), showbase(), {QTextStream manipulators}
2681 */
2682 QTextStream &forcesign(QTextStream &stream)
2683 {
2684     stream.setNumberFlags(stream.numberFlags() | QTextStream::ForceSign);
2685     return stream;
2686 }
2687
2688 /*!
2689     \relates QTextStream
2690
2691     Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2692     QTextStream::ForcePoint) on \a stream and returns \a stream.
2693
2694     \sa noforcepoint(), forcesign(), showbase(), {QTextStream manipulators}
2695 */
2696 QTextStream &forcepoint(QTextStream &stream)
2697 {
2698     stream.setNumberFlags(stream.numberFlags() | QTextStream::ForcePoint);
2699     return stream;
2700 }
2701
2702 /*!
2703     \relates QTextStream
2704
2705     Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2706     ~QTextStream::ShowBase) on \a stream and returns \a stream.
2707
2708     \sa showbase(), noforcesign(), noforcepoint(), {QTextStream manipulators}
2709 */
2710 QTextStream &noshowbase(QTextStream &stream)
2711 {
2712     stream.setNumberFlags(stream.numberFlags() &= ~QTextStream::ShowBase);
2713     return stream;
2714 }
2715
2716 /*!
2717     \relates QTextStream
2718
2719     Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2720     ~QTextStream::ForceSign) on \a stream and returns \a stream.
2721
2722     \sa forcesign(), noforcepoint(), noshowbase(), {QTextStream manipulators}
2723 */
2724 QTextStream &noforcesign(QTextStream &stream)
2725 {
2726     stream.setNumberFlags(stream.numberFlags() &= ~QTextStream::ForceSign);
2727     return stream;
2728 }
2729
2730 /*!
2731     \relates QTextStream
2732
2733     Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2734     ~QTextStream::ForcePoint) on \a stream and returns \a stream.
2735
2736     \sa forcepoint(), noforcesign(), noshowbase(), {QTextStream manipulators}
2737 */
2738 QTextStream &noforcepoint(QTextStream &stream)
2739 {
2740     stream.setNumberFlags(stream.numberFlags() &= ~QTextStream::ForcePoint);
2741     return stream;
2742 }
2743
2744 /*!
2745     \relates QTextStream
2746
2747     Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2748     QTextStream::UppercaseBase) on \a stream and returns \a stream.
2749
2750     \sa lowercasebase(), uppercasedigits(), {QTextStream manipulators}
2751 */
2752 QTextStream &uppercasebase(QTextStream &stream)
2753 {
2754     stream.setNumberFlags(stream.numberFlags() | QTextStream::UppercaseBase);
2755     return stream;
2756 }
2757
2758 /*!
2759     \relates QTextStream
2760
2761     Calls QTextStream::setNumberFlags(QTextStream::numberFlags() |
2762     QTextStream::UppercaseDigits) on \a stream and returns \a stream.
2763
2764     \sa lowercasedigits(), uppercasebase(), {QTextStream manipulators}
2765 */
2766 QTextStream &uppercasedigits(QTextStream &stream)
2767 {
2768     stream.setNumberFlags(stream.numberFlags() | QTextStream::UppercaseDigits);
2769     return stream;
2770 }
2771
2772 /*!
2773     \relates QTextStream
2774
2775     Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2776     ~QTextStream::UppercaseBase) on \a stream and returns \a stream.
2777
2778     \sa uppercasebase(), lowercasedigits(), {QTextStream manipulators}
2779 */
2780 QTextStream &lowercasebase(QTextStream &stream)
2781 {
2782     stream.setNumberFlags(stream.numberFlags() & ~QTextStream::UppercaseBase);
2783     return stream;
2784 }
2785
2786 /*!
2787     \relates QTextStream
2788
2789     Calls QTextStream::setNumberFlags(QTextStream::numberFlags() &
2790     ~QTextStream::UppercaseDigits) on \a stream and returns \a stream.
2791
2792     \sa uppercasedigits(), lowercasebase(), {QTextStream manipulators}
2793 */
2794 QTextStream &lowercasedigits(QTextStream &stream)
2795 {
2796     stream.setNumberFlags(stream.numberFlags() & ~QTextStream::UppercaseDigits);
2797     return stream;
2798 }
2799
2800 /*!
2801     \relates QTextStream
2802
2803     Calls QTextStream::setRealNumberNotation(QTextStream::FixedNotation)
2804     on \a stream and returns \a stream.
2805
2806     \sa scientific(), {QTextStream manipulators}
2807 */
2808 QTextStream &fixed(QTextStream &stream)
2809 {
2810     stream.setRealNumberNotation(QTextStream::FixedNotation);
2811     return stream;
2812 }
2813
2814 /*!
2815     \relates QTextStream
2816
2817     Calls QTextStream::setRealNumberNotation(QTextStream::ScientificNotation)
2818     on \a stream and returns \a stream.
2819
2820     \sa fixed(), {QTextStream manipulators}
2821 */
2822 QTextStream &scientific(QTextStream &stream)
2823 {
2824     stream.setRealNumberNotation(QTextStream::ScientificNotation);
2825     return stream;
2826 }
2827
2828 /*!
2829     \relates QTextStream
2830
2831     Calls QTextStream::setFieldAlignment(QTextStream::AlignLeft)
2832     on \a stream and returns \a stream.
2833
2834     \sa right(), center(), {QTextStream manipulators}
2835 */
2836 QTextStream &left(QTextStream &stream)
2837 {
2838     stream.setFieldAlignment(QTextStream::AlignLeft);
2839     return stream;
2840 }
2841
2842 /*!
2843     \relates QTextStream
2844
2845     Calls QTextStream::setFieldAlignment(QTextStream::AlignRight)
2846     on \a stream and returns \a stream.
2847
2848     \sa left(), center(), {QTextStream manipulators}
2849 */
2850 QTextStream &right(QTextStream &stream)
2851 {
2852     stream.setFieldAlignment(QTextStream::AlignRight);
2853     return stream;
2854 }
2855
2856 /*!
2857     \relates QTextStream
2858
2859     Calls QTextStream::setFieldAlignment(QTextStream::AlignCenter)
2860     on \a stream and returns \a stream.
2861
2862     \sa left(), right(), {QTextStream manipulators}
2863 */
2864 QTextStream &center(QTextStream &stream)
2865 {
2866     stream.setFieldAlignment(QTextStream::AlignCenter);
2867     return stream;
2868 }
2869
2870 /*!
2871     \relates QTextStream
2872
2873     Writes '\n' to the \a stream and flushes the stream.
2874
2875     Equivalent to
2876
2877     \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 9
2878
2879     Note: On Windows, all '\n' characters are written as '\r\n' if
2880     QTextStream's device or string is opened using the QIODevice::Text flag.
2881
2882     \sa flush(), reset(), {QTextStream manipulators}
2883 */
2884 QTextStream &endl(QTextStream &stream)
2885 {
2886     return stream << QLatin1Char('\n') << flush;
2887 }
2888
2889 /*!
2890     \relates QTextStream
2891
2892     Calls QTextStream::flush() on \a stream and returns \a stream.
2893
2894     \sa endl(), reset(), {QTextStream manipulators}
2895 */
2896 QTextStream &flush(QTextStream &stream)
2897 {
2898     stream.flush();
2899     return stream;
2900 }
2901
2902 /*!
2903     \relates QTextStream
2904
2905     Calls QTextStream::reset() on \a stream and returns \a stream.
2906
2907     \sa flush(), {QTextStream manipulators}
2908 */
2909 QTextStream &reset(QTextStream &stream)
2910 {
2911     stream.reset();
2912     return stream;
2913 }
2914
2915 /*!
2916     \relates QTextStream
2917
2918     Calls skipWhiteSpace() on \a stream and returns \a stream.
2919
2920     \sa {QTextStream manipulators}
2921 */
2922 QTextStream &ws(QTextStream &stream)
2923 {
2924     stream.skipWhiteSpace();
2925     return stream;
2926 }
2927
2928 /*!
2929     \fn QTextStreamManipulator qSetFieldWidth(int width)
2930     \relates QTextStream
2931
2932     Equivalent to QTextStream::setFieldWidth(\a width).
2933 */
2934
2935 /*!
2936     \fn QTextStreamManipulator qSetPadChar(QChar ch)
2937     \relates QTextStream
2938
2939     Equivalent to QTextStream::setPadChar(\a ch).
2940 */
2941
2942 /*!
2943     \fn QTextStreamManipulator qSetRealNumberPrecision(int precision)
2944     \relates QTextStream
2945
2946     Equivalent to QTextStream::setRealNumberPrecision(\a precision).
2947 */
2948
2949 #ifndef QT_NO_TEXTCODEC
2950 /*!
2951     \relates QTextStream
2952
2953     Toggles insertion of the Byte Order Mark on \a stream when QTextStream is
2954     used with a UTF codec.
2955
2956     \sa QTextStream::setGenerateByteOrderMark(), {QTextStream manipulators}
2957 */
2958 QTextStream &bom(QTextStream &stream)
2959 {
2960     stream.setGenerateByteOrderMark(true);
2961     return stream;
2962 }
2963
2964 /*!
2965     Sets the codec for this stream to \a codec. The codec is used for
2966     decoding any data that is read from the assigned device, and for
2967     encoding any data that is written. By default,
2968     QTextCodec::codecForLocale() is used, and automatic unicode
2969     detection is enabled.
2970
2971     If QTextStream operates on a string, this function does nothing.
2972
2973     \warning If you call this function while the text stream is reading
2974     from an open sequential socket, the internal buffer may still contain
2975     text decoded using the old codec.
2976
2977     \sa codec(), setAutoDetectUnicode(), setLocale()
2978 */
2979 void QTextStream::setCodec(QTextCodec *codec)
2980 {
2981     Q_D(QTextStream);
2982     qint64 seekPos = -1;
2983     if (!d->readBuffer.isEmpty()) {
2984         if (!d->device->isSequential()) {
2985             seekPos = pos();
2986         }
2987     }
2988     d->codec = codec;
2989     if (seekPos >=0 && !d->readBuffer.isEmpty())
2990         seek(seekPos);
2991 }
2992
2993 /*!
2994     Sets the codec for this stream to the QTextCodec for the encoding
2995     specified by \a codecName. Common values for \c codecName include
2996     "ISO 8859-1", "UTF-8", and "UTF-16". If the encoding isn't
2997     recognized, nothing happens.
2998
2999     Example:
3000
3001     \snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 10
3002
3003     \sa QTextCodec::codecForName(), setLocale()
3004 */
3005 void QTextStream::setCodec(const char *codecName)
3006 {
3007     QTextCodec *codec = QTextCodec::codecForName(codecName);
3008     if (codec)
3009         setCodec(codec);
3010 }
3011
3012 /*!
3013     Returns the codec that is current assigned to the stream.
3014
3015     \sa setCodec(), setAutoDetectUnicode(), locale()
3016 */
3017 QTextCodec *QTextStream::codec() const
3018 {
3019     Q_D(const QTextStream);
3020     return d->codec;
3021 }
3022
3023 /*!
3024     If \a enabled is true, QTextStream will attempt to detect Unicode
3025     encoding by peeking into the stream data to see if it can find the
3026     UTF-16 or UTF-32 BOM (Byte Order Mark). If this mark is found, QTextStream
3027     will replace the current codec with the UTF codec.
3028
3029     This function can be used together with setCodec(). It is common
3030     to set the codec to UTF-8, and then enable UTF-16 detection.
3031
3032     \sa autoDetectUnicode(), setCodec()
3033 */
3034 void QTextStream::setAutoDetectUnicode(bool enabled)
3035 {
3036     Q_D(QTextStream);
3037     d->autoDetectUnicode = enabled;
3038 }
3039
3040 /*!
3041     Returns true if automatic Unicode detection is enabled, otherwise
3042     returns false. Automatic Unicode detection is enabled by default.
3043
3044     \sa setAutoDetectUnicode(), setCodec()
3045 */
3046 bool QTextStream::autoDetectUnicode() const
3047 {
3048     Q_D(const QTextStream);
3049     return d->autoDetectUnicode;
3050 }
3051
3052 /*!
3053     If \a generate is true and a UTF codec is used, QTextStream will insert
3054     the BOM (Byte Order Mark) before any data has been written to the
3055     device. If \a generate is false, no BOM will be inserted. This function
3056     must be called before any data is written. Otherwise, it does nothing.
3057
3058     \sa generateByteOrderMark(), bom()
3059 */
3060 void QTextStream::setGenerateByteOrderMark(bool generate)
3061 {
3062     Q_D(QTextStream);
3063     if (d->writeBuffer.isEmpty()) {
3064         if (generate)
3065             d->writeConverterState.flags &= ~QTextCodec::IgnoreHeader;
3066         else
3067             d->writeConverterState.flags |= QTextCodec::IgnoreHeader;
3068     }
3069 }
3070
3071 /*!
3072     Returns true if QTextStream is set to generate the UTF BOM (Byte Order
3073     Mark) when using a UTF codec; otherwise returns false. UTF BOM generation is
3074     set to false by default.
3075
3076     \sa setGenerateByteOrderMark()
3077 */
3078 bool QTextStream::generateByteOrderMark() const
3079 {
3080     Q_D(const QTextStream);
3081     return (d->writeConverterState.flags & QTextCodec::IgnoreHeader) == 0;
3082 }
3083
3084 #endif
3085
3086 /*!
3087     \since 4.5
3088
3089     Sets the locale for this stream to \a locale. The specified locale is
3090     used for conversions between numbers and their string representations.
3091
3092     The default locale is C and it is a special case - the thousands
3093     group separator is not used for backward compatibility reasons.
3094
3095     \sa locale()
3096 */
3097 void QTextStream::setLocale(const QLocale &locale)
3098 {
3099     Q_D(QTextStream);
3100     d->locale = locale;
3101 }
3102
3103 /*!
3104     \since 4.5
3105
3106     Returns the locale for this stream. The default locale is C.
3107
3108     \sa setLocale()
3109 */
3110 QLocale QTextStream::locale() const
3111 {
3112     Q_D(const QTextStream);
3113     return d->locale;
3114 }
3115
3116 QT_END_NAMESPACE
3117
3118 #ifndef QT_NO_QOBJECT
3119 #include "qtextstream.moc"
3120 #endif
3121