/
qtextstream.cpp
3399 lines (2891 loc) · 92.7 KB
/
qtextstream.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
//#define QTEXTSTREAM_DEBUG
static const int QTEXTSTREAM_BUFFERSIZE = 16384;
/*!
\class QTextStream
\brief The QTextStream class provides a convenient interface for
reading and writing text.
\ingroup io
\ingroup string-processing
\reentrant
QTextStream can operate on a QIODevice, a QByteArray or a
QString. Using QTextStream's streaming operators, you can
conveniently read and write words, lines and numbers. For
generating text, QTextStream supports formatting options for field
padding and alignment, and formatting of numbers. Example:
\snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 0
It's also common to use QTextStream to read console input and write
console output. QTextStream is locale aware, and will automatically decode
standard input using the correct codec. Example:
\snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 1
Note that you cannot use QTextStream::atEnd(), which returns true when you
have reached the end of the data stream, with stdin. The reason for this is
that as long as stdin doesn't give any input to the QTextStream, \c atEnd()
will return true even if the stdin is open and waiting for more characters.
Besides using QTextStream's constructors, you can also set the
device or string QTextStream operates on by calling setDevice() or
setString(). You can seek to a position by calling seek(), and
atEnd() will return true when there is no data left to be read. If
you call flush(), QTextStream will empty all data from its write
buffer into the device and call flush() on the device.
Internally, QTextStream uses a Unicode based buffer, and
QTextCodec is used by QTextStream to automatically support
different character sets. By default, QTextCodec::codecForLocale()
is used for reading and writing, but you can also set the codec by
calling setCodec(). Automatic Unicode detection is also
supported. When this feature is enabled (the default behavior),
QTextStream will detect the UTF-16 or the UTF-32 BOM (Byte Order Mark) and
switch to the appropriate UTF codec when reading. QTextStream
does not write a BOM by default, but you can enable this by calling
setGenerateByteOrderMark(true). When QTextStream operates on a QString
directly, the codec is disabled.
There are three general ways to use QTextStream when reading text
files:
\list
\o Chunk by chunk, by calling readLine() or readAll().
\o Word by word. QTextStream supports streaming into QStrings,
QByteArrays and char* buffers. Words are delimited by space, and
leading white space is automatically skipped.
\o Character by character, by streaming into QChar or char types.
This method is often used for convenient input handling when
parsing files, independent of character encoding and end-of-line
semantics. To skip white space, call skipWhiteSpace().
\endlist
Since the text stream uses a buffer, you should not read from
the stream using the implementation of a superclass. For instance,
if you have a QFile and read from it directly using
QFile::readLine() instead of using the stream, the text stream's
internal position will be out of sync with the file's position.
By default, when reading numbers from a stream of text,
QTextStream will automatically detect the number's base
representation. For example, if the number starts with "0x", it is
assumed to be in hexadecimal form. If it starts with the digits
1-9, it is assumed to be in decimal form, and so on. You can set
the integer base, thereby disabling the automatic detection, by
calling setIntegerBase(). Example:
\snippet doc/src/snippets/code/src_corelib_io_qtextstream.cpp 2
QTextStream supports many formatting options for generating text.
You can set the field width and pad character by calling
setFieldWidth() and setPadChar(). Use setFieldAlignment() to set
the alignment within each field. For real numbers, call
setRealNumberNotation() and setRealNumberPrecision() to set the
notation (SmartNotation, ScientificNotation, FixedNotation) and precision in
digits of the generated number. Some extra number formatting
options are also available through setNumberFlags().
\keyword QTextStream manipulators
Like \c <iostream> in the standard C++ library, QTextStream also
defines several global manipulator functions:
\table
\header \o Manipulator \o Description
\row \o \c bin \o Same as setIntegerBase(2).
\row \o \c oct \o Same as setIntegerBase(8).
\row \o \c dec \o Same as setIntegerBase(10).
\row \o \c hex \o Same as setIntegerBase(16).
\row \o \c showbase \o Same as setNumberFlags(numberFlags() | ShowBase).
\row \o \c forcesign \o Same as setNumberFlags(numberFlags() | ForceSign).
\row \o \c forcepoint \o Same as setNumberFlags(numberFlags() | ForcePoint).
\row \o \c noshowbase \o Same as setNumberFlags(numberFlags() & ~ShowBase).
\row \o \c noforcesign \o Same as setNumberFlags(numberFlags() & ~ForceSign).
\row \o \c noforcepoint \o Same as setNumberFlags(numberFlags() & ~ForcePoint).
\row \o \c uppercasebase \o Same as setNumberFlags(numberFlags() | UppercaseBase).
\row \o \c uppercasedigits \o Same as setNumberFlags(numberFlags() | UppercaseDigits).
\row \o \c lowercasebase \o Same as setNumberFlags(numberFlags() & ~UppercaseBase).
\row \o \c lowercasedigits \o Same as setNumberFlags(numberFlags() & ~UppercaseDigits).
\row \o \c fixed \o Same as setRealNumberNotation(FixedNotation).
\row \o \c scientific \o Same as setRealNumberNotation(ScientificNotation).
\row \o \c left \o Same as setFieldAlignment(AlignLeft).
\row \o \c right \o Same as setFieldAlignment(AlignRight).
\row \o \c center \o Same as setFieldAlignment(AlignCenter).
\row \o \c endl \o Same as operator<<('\n') and flush().
\row \o \c flush \o Same as flush().
\row \o \c reset \o Same as reset().
\row \o \c ws \o Same as skipWhiteSpace().
\row \o \c bom \o Same as setGenerateByteOrderMark(true).
\endtable
In addition, Qt provides three global manipulators that take a
parameter: qSetFieldWidth(), qSetPadChar(), and
qSetRealNumberPrecision().
\sa QDataStream, QIODevice, QFile, QBuffer, QTcpSocket, {Codecs Example}
*/
/*! \enum QTextStream::RealNumberNotation
This enum specifies which notations to use for expressing \c
float and \c double as strings.
\value ScientificNotation Scientific notation (\c{printf()}'s \c %e flag).
\value FixedNotation Fixed-point notation (\c{printf()}'s \c %f flag).
\value SmartNotation Scientific or fixed-point notation, depending on which makes most sense (\c{printf()}'s \c %g flag).
\sa setRealNumberNotation()
*/
/*! \enum QTextStream::FieldAlignment
This enum specifies how to align text in fields when the field is
wider than the text that occupies it.
\value AlignLeft Pad on the right side of fields.
\value AlignRight Pad on the left side of fields.
\value AlignCenter Pad on both sides of field.
\value AlignAccountingStyle Same as AlignRight, except that the
sign of a number is flush left.
\sa setFieldAlignment()
*/
/*! \enum QTextStream::NumberFlag
This enum specifies various flags that can be set to affect the
output of integers, \c{float}s, and \c{double}s.
\value ShowBase Show the base as a prefix if the base
is 16 ("0x"), 8 ("0"), or 2 ("0b").
\value ForcePoint Always put the decimal separator in numbers, even if
there are no decimals.
\value ForceSign Always put the sign in numbers, even for positive numbers.
\value UppercaseBase Use uppercase versions of base prefixes ("0X", "0B").
\value UppercaseDigits Use uppercase letters for expressing
digits 10 to 35 instead of lowercase.
\sa setNumberFlags()
*/
/*! \enum QTextStream::Status
This enum describes the current status of the text stream.
\value Ok The text stream is operating normally.
\value ReadPastEnd The text stream has read past the end of the
data in the underlying device.
\value ReadCorruptData The text stream has read corrupt data.
\sa status()
*/
#include "qtextstream.h"
#include "qbuffer.h"
#include "qfile.h"
#include "qnumeric.h"
#ifndef QT_NO_TEXTCODEC
#include "qtextcodec.h"
#endif
#ifndef Q_OS_WINCE
#include <locale.h>
#endif
#include "private/qlocale_p.h"
#include <stdlib.h>
#include <limits.h>
#include <new>
#if defined QTEXTSTREAM_DEBUG
#include <ctype.h>
QT_BEGIN_NAMESPACE
// Returns a human readable representation of the first \a len
// characters in \a data.
static QByteArray qt_prettyDebug(const char *data, int len, int maxSize)
{
if (!data) return "(null)";
QByteArray out;
for (int i = 0; i < len; ++i) {
char c = data[i];
if (isprint(int(uchar(c)))) {
out += c;
} else switch (c) {
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
QString tmp;
tmp.sprintf("\\x%x", (unsigned int)(unsigned char)c);
out += tmp.toLatin1();
}
}
if (len < maxSize)
out += "...";
return out;
}
QT_END_NAMESPACE
#endif
// A precondition macro
#define Q_VOID
#define CHECK_VALID_STREAM(x) do { \
if (!d->string && !d->device) { \
qWarning("QTextStream: No device"); \
return x; \
} } while (0)
// Base implementations of operator>> for ints and reals
#define IMPLEMENT_STREAM_RIGHT_INT_OPERATOR(type) do { \
Q_D(QTextStream); \
CHECK_VALID_STREAM(*this); \
qulonglong tmp; \
switch (d->getNumber(&tmp)) { \
case QTextStreamPrivate::npsOk: \
i = (type)tmp; \
break; \
case QTextStreamPrivate::npsMissingDigit: \
case QTextStreamPrivate::npsInvalidPrefix: \
i = (type)0; \
setStatus(atEnd() ? QTextStream::ReadPastEnd : QTextStream::ReadCorruptData); \
break; \
} \
return *this; } while (0)
#define IMPLEMENT_STREAM_RIGHT_REAL_OPERATOR(type) do { \
Q_D(QTextStream); \
CHECK_VALID_STREAM(*this); \
double tmp; \
if (d->getReal(&tmp)) { \
f = (type)tmp; \
} else { \
f = (type)0; \
setStatus(atEnd() ? QTextStream::ReadPastEnd : QTextStream::ReadCorruptData); \
} \
return *this; } while (0)
QT_BEGIN_NAMESPACE
#ifndef QT_NO_QOBJECT
class QDeviceClosedNotifier : public QObject
{
Q_OBJECT
public:
inline QDeviceClosedNotifier()
{ }
inline void setupDevice(QTextStream *stream, QIODevice *device)
{
disconnect();
if (device)
connect(device, SIGNAL(aboutToClose()), this, SLOT(flushStream()));
this->stream = stream;
}
public Q_SLOTS:
inline void flushStream() { stream->flush(); }
private:
QTextStream *stream;
};
#endif
//-------------------------------------------------------------------
class QTextStreamPrivate
{
Q_DECLARE_PUBLIC(QTextStream)
public:
QTextStreamPrivate(QTextStream *q_ptr);
~QTextStreamPrivate();
void reset();
// device
QIODevice *device;
#ifndef QT_NO_QOBJECT
QDeviceClosedNotifier deviceClosedNotifier;
#endif
bool deleteDevice;
// string
QString *string;
int stringOffset;
QIODevice::OpenMode stringOpenMode;
#ifndef QT_NO_TEXTCODEC
// codec
QTextCodec *codec;
QTextCodec::ConverterState readConverterState;
QTextCodec::ConverterState writeConverterState;
QTextCodec::ConverterState *readConverterSavedState;
bool autoDetectUnicode;
#endif
// i/o
enum TokenDelimiter {
Space,
NotSpace,
EndOfLine
};
QString read(int maxlen);
bool scan(const QChar **ptr, int *tokenLength,
int maxlen, TokenDelimiter delimiter);
inline const QChar *readPtr() const;
inline void consumeLastToken();
inline void consume(int nchars);
void saveConverterState(qint64 newPos);
void restoreToSavedConverterState();
int lastTokenSize;
// Return value type for getNumber()
enum NumberParsingStatus {
npsOk,
npsMissingDigit,
npsInvalidPrefix
};
inline bool write(const QString &data);
inline bool getChar(QChar *ch);
inline void ungetChar(const QChar &ch);
NumberParsingStatus getNumber(qulonglong *l);
bool getReal(double *f);
bool putNumber(qulonglong number, bool negative);
inline bool putString(const QString &ch, bool number = false);
// buffers
bool fillReadBuffer(qint64 maxBytes = -1);
void resetReadBuffer();
bool flushWriteBuffer();
QString writeBuffer;
QString readBuffer;
int readBufferOffset;
int readConverterSavedStateOffset; //the offset between readBufferStartDevicePos and that start of the buffer
qint64 readBufferStartDevicePos;
// streaming parameters
int realNumberPrecision;
int integerBase;
int fieldWidth;
QChar padChar;
QTextStream::FieldAlignment fieldAlignment;
QTextStream::RealNumberNotation realNumberNotation;
QTextStream::NumberFlags numberFlags;
// status
QTextStream::Status status;
QLocale locale;
QTextStream *q_ptr;
};
/*! \internal
*/
QTextStreamPrivate::QTextStreamPrivate(QTextStream *q_ptr)
:
#ifndef QT_NO_TEXTCODEC
readConverterSavedState(0),
#endif
readConverterSavedStateOffset(0),
locale(QLocale::C)
{
this->q_ptr = q_ptr;
reset();
}
/*! \internal
*/
QTextStreamPrivate::~QTextStreamPrivate()
{
if (deleteDevice) {
#ifndef QT_NO_QOBJECT
device->blockSignals(true);
#endif
delete device;
}
#ifndef QT_NO_TEXTCODEC
delete readConverterSavedState;
#endif
}
#ifndef QT_NO_TEXTCODEC
static void resetCodecConverterStateHelper(QTextCodec::ConverterState *state)
{
state->~ConverterState();
new (state) QTextCodec::ConverterState;
}
static void copyConverterStateHelper(QTextCodec::ConverterState *dest,
const QTextCodec::ConverterState *src)
{
// ### QTextCodec::ConverterState's copy constructors and assignments are
// private. This function copies the structure manually.
Q_ASSERT(!src->d);
dest->flags = src->flags;
dest->invalidChars = src->invalidChars;
dest->state_data[0] = src->state_data[0];
dest->state_data[1] = src->state_data[1];
dest->state_data[2] = src->state_data[2];
}
#endif
/*! \internal
*/
void QTextStreamPrivate::reset()
{
realNumberPrecision = 6;
integerBase = 0;
fieldWidth = 0;
padChar = QLatin1Char(' ');
fieldAlignment = QTextStream::AlignRight;
realNumberNotation = QTextStream::SmartNotation;
numberFlags = 0;
device = 0;
deleteDevice = false;
string = 0;
stringOffset = 0;
stringOpenMode = QIODevice::NotOpen;
readBufferOffset = 0;
readBufferStartDevicePos = 0;
lastTokenSize = 0;
#ifndef QT_NO_TEXTCODEC
codec = QTextCodec::codecForLocale();
resetCodecConverterStateHelper(&readConverterState);
resetCodecConverterStateHelper(&writeConverterState);
delete readConverterSavedState;
readConverterSavedState = 0;
writeConverterState.flags |= QTextCodec::IgnoreHeader;
autoDetectUnicode = true;
#endif
}
/*! \internal
*/
bool QTextStreamPrivate::fillReadBuffer(qint64 maxBytes)
{
// no buffer next to the QString itself; this function should only
// be called internally, for devices.
Q_ASSERT(!string);
Q_ASSERT(device);
// handle text translation and bypass the Text flag in the device.
bool textModeEnabled = device->isTextModeEnabled();
if (textModeEnabled)
device->setTextModeEnabled(false);
// read raw data into a temporary buffer
char buf[QTEXTSTREAM_BUFFERSIZE];
qint64 bytesRead = 0;
#if defined(Q_OS_WIN)
// On Windows, there is no non-blocking stdin - so we fall back to reading
// lines instead. If there is no QOBJECT, we read lines for all sequential
// devices; otherwise, we read lines only for stdin.
QFile *file = 0;
Q_UNUSED(file);
if (device->isSequential()
#if !defined(QT_NO_QOBJECT)
&& (file = qobject_cast<QFile *>(device)) && file->handle() == 0
#endif
) {
if (maxBytes != -1)
bytesRead = device->readLine(buf, qMin<qint64>(sizeof(buf), maxBytes));
else
bytesRead = device->readLine(buf, sizeof(buf));
} else
#endif
{
if (maxBytes != -1)
bytesRead = device->read(buf, qMin<qint64>(sizeof(buf), maxBytes));
else
bytesRead = device->read(buf, sizeof(buf));
}
#ifndef QT_NO_TEXTCODEC
// codec auto detection, explicitly defaults to locale encoding if the
// codec has been set to 0.
if (!codec || autoDetectUnicode) {
autoDetectUnicode = false;
codec = QTextCodec::codecForUtfText(QByteArray::fromRawData(buf, bytesRead), codec);
if (!codec) {
codec = QTextCodec::codecForLocale();
writeConverterState.flags |= QTextCodec::IgnoreHeader;
}
}
#if defined (QTEXTSTREAM_DEBUG)
qDebug("QTextStreamPrivate::fillReadBuffer(), using %s codec",
codec->name().constData());
#endif
#endif
#if defined (QTEXTSTREAM_DEBUG)
qDebug("QTextStreamPrivate::fillReadBuffer(), device->read(\"%s\", %d) == %d",
qt_prettyDebug(buf, qMin(32,int(bytesRead)) , int(bytesRead)).constData(), sizeof(buf), int(bytesRead));
#endif
if (bytesRead <= 0)
return false;
int oldReadBufferSize = readBuffer.size();
#ifndef QT_NO_TEXTCODEC
// convert to unicode
readBuffer += codec->toUnicode(buf, bytesRead, &readConverterState);
#else
readBuffer += QString::fromLatin1(QByteArray(buf, bytesRead).constData());
#endif
// reset the Text flag.
if (textModeEnabled)
device->setTextModeEnabled(true);
// remove all '\r\n' in the string.
if (readBuffer.size() > oldReadBufferSize && textModeEnabled) {
QChar CR = QLatin1Char('\r');
QChar *writePtr = readBuffer.data() + oldReadBufferSize;
QChar *readPtr = readBuffer.data() + oldReadBufferSize;
QChar *endPtr = readBuffer.data() + readBuffer.size();
int n = oldReadBufferSize;
if (readPtr < endPtr) {
// Cut-off to avoid unnecessary self-copying.
while (*readPtr++ != CR) {
++n;
if (++writePtr == endPtr)
break;
}
}
while (readPtr < endPtr) {
QChar ch = *readPtr++;
if (ch != CR) {
*writePtr++ = ch;
} else {
if (n < readBufferOffset)
--readBufferOffset;
--bytesRead;
}
++n;
}
readBuffer.resize(writePtr - readBuffer.data());
}
#if defined (QTEXTSTREAM_DEBUG)
qDebug("QTextStreamPrivate::fillReadBuffer() read %d bytes from device. readBuffer = [%s]", int(bytesRead),
qt_prettyDebug(readBuffer.toLatin1(), readBuffer.size(), readBuffer.size()).data());
#endif
return true;
}
/*! \internal
*/
void QTextStreamPrivate::resetReadBuffer()
{
readBuffer.clear();
readBufferOffset = 0;
readBufferStartDevicePos = (device ? device->pos() : 0);
}
/*! \internal
*/
bool QTextStreamPrivate::flushWriteBuffer()
{
// no buffer next to the QString itself; this function should only
// be called internally, for devices.
if (string || !device)
return false;
if (writeBuffer.isEmpty())
return true;
#if defined (Q_OS_WIN)
// handle text translation and bypass the Text flag in the device.
bool textModeEnabled = device->isTextModeEnabled();
if (textModeEnabled) {
device->setTextModeEnabled(false);
writeBuffer.replace(QLatin1Char('\n'), QLatin1String("\r\n"));
}
#endif
#ifndef QT_NO_TEXTCODEC
if (!codec)
codec = QTextCodec::codecForLocale();
#if defined (QTEXTSTREAM_DEBUG)
qDebug("QTextStreamPrivate::flushWriteBuffer(), using %s codec (%s generating BOM)",
codec->name().constData(), writeConverterState.flags & QTextCodec::IgnoreHeader ? "not" : "");
#endif
// convert from unicode to raw data
QByteArray data = codec->fromUnicode(writeBuffer.data(), writeBuffer.size(), &writeConverterState);
#else
QByteArray data = writeBuffer.toLocal8Bit();
#endif
writeBuffer.clear();
// write raw data to the device
qint64 bytesWritten = device->write(data);
#if defined (QTEXTSTREAM_DEBUG)
qDebug("QTextStreamPrivate::flushWriteBuffer(), device->write(\"%s\") == %d",
qt_prettyDebug(data.constData(), qMin(data.size(),32), data.size()).constData(), int(bytesWritten));
#endif
if (bytesWritten <= 0)
return false;
#if defined (Q_OS_WIN)
// replace the text flag
if (textModeEnabled)
device->setTextModeEnabled(true);
#endif
// flush the file
#ifndef QT_NO_QOBJECT
QFile *file = qobject_cast<QFile *>(device);
bool flushed = file && file->flush();
#else
bool flushed = true;
#endif
#if defined (QTEXTSTREAM_DEBUG)
qDebug("QTextStreamPrivate::flushWriteBuffer() wrote %d bytes",
int(bytesWritten));
#endif
return flushed && bytesWritten == qint64(data.size());
}
QString QTextStreamPrivate::read(int maxlen)
{
QString ret;
if (string) {
lastTokenSize = qMin(maxlen, string->size() - stringOffset);
ret = string->mid(stringOffset, lastTokenSize);
} else {
while (readBuffer.size() - readBufferOffset < maxlen && fillReadBuffer()) ;
lastTokenSize = qMin(maxlen, readBuffer.size() - readBufferOffset);
ret = readBuffer.mid(readBufferOffset, lastTokenSize);
}
consumeLastToken();
#if defined (QTEXTSTREAM_DEBUG)
qDebug("QTextStreamPrivate::read() maxlen = %d, token length = %d", maxlen, ret.length());
#endif
return ret;
}
/*! \internal
Scans no more than \a maxlen QChars in the current buffer for the
first \a delimiter. Stores a pointer to the start offset of the
token in \a ptr, and the length in QChars in \a length.
*/
bool QTextStreamPrivate::scan(const QChar **ptr, int *length, int maxlen, TokenDelimiter delimiter)
{
int totalSize = 0;
int delimSize = 0;
bool consumeDelimiter = false;
bool foundToken = false;
int startOffset = device ? readBufferOffset : stringOffset;
QChar lastChar;
bool canStillReadFromDevice = true;
do {
int endOffset;
const QChar *chPtr;
if (device) {
chPtr = readBuffer.constData();
endOffset = readBuffer.size();
} else {
chPtr = string->constData();
endOffset = string->size();
}
chPtr += startOffset;
for (; !foundToken && startOffset < endOffset && (!maxlen || totalSize < maxlen); ++startOffset) {
const QChar ch = *chPtr++;
++totalSize;
switch (delimiter) {
case Space:
if (ch.isSpace()) {
foundToken = true;
delimSize = 1;
}
break;
case NotSpace:
if (!ch.isSpace()) {
foundToken = true;
delimSize = 1;
}
break;
case EndOfLine:
if (ch == QLatin1Char('\n')) {
foundToken = true;
delimSize = (lastChar == QLatin1Char('\r')) ? 2 : 1;
consumeDelimiter = true;
}
lastChar = ch;
break;
}
}
} while (!foundToken
&& (!maxlen || totalSize < maxlen)
&& (device && (canStillReadFromDevice = fillReadBuffer())));
// if the token was not found, but we reached the end of input,
// then we accept what we got. if we are not at the end of input,
// we return false.
if (!foundToken && (!maxlen || totalSize < maxlen)
&& (totalSize == 0
|| (string && stringOffset + totalSize < string->size())
|| (device && !device->atEnd() && canStillReadFromDevice))) {
#if defined (QTEXTSTREAM_DEBUG)
qDebug("QTextStreamPrivate::scan() did not find the token.");
#endif
return false;
}
// if we find a '\r' at the end of the data when reading lines,
// don't make it part of the line.
if (delimiter == EndOfLine && totalSize > 0 && !foundToken) {
if (((string && stringOffset + totalSize == string->size()) || (device && device->atEnd()))
&& lastChar == QLatin1Char('\r')) {
consumeDelimiter = true;
++delimSize;
}
}
// set the read offset and length of the token
if (length)
*length = totalSize - delimSize;
if (ptr)
*ptr = readPtr();
// update last token size. the callee will call consumeLastToken() when
// done.
lastTokenSize = totalSize;
if (!consumeDelimiter)
lastTokenSize -= delimSize;
#if defined (QTEXTSTREAM_DEBUG)
qDebug("QTextStreamPrivate::scan(%p, %p, %d, %x) token length = %d, delimiter = %d",
ptr, length, maxlen, (int)delimiter, totalSize - delimSize, delimSize);
#endif
return true;
}
/*! \internal
*/
inline const QChar *QTextStreamPrivate::readPtr() const
{
Q_ASSERT(readBufferOffset <= readBuffer.size());
if (string)
return string->constData() + stringOffset;
return readBuffer.constData() + readBufferOffset;
}
/*! \internal
*/
inline void QTextStreamPrivate::consumeLastToken()
{
if (lastTokenSize)
consume(lastTokenSize);
lastTokenSize = 0;
}
/*! \internal
*/
inline void QTextStreamPrivate::consume(int size)
{
#if defined (QTEXTSTREAM_DEBUG)
qDebug("QTextStreamPrivate::consume(%d)", size);
#endif
if (string) {
stringOffset += size;
if (stringOffset > string->size())
stringOffset = string->size();
} else {
readBufferOffset += size;
if (readBufferOffset >= readBuffer.size()) {
readBufferOffset = 0;
readBuffer.clear();
saveConverterState(device->pos());
} else if (readBufferOffset > QTEXTSTREAM_BUFFERSIZE) {
readBuffer = readBuffer.remove(0,readBufferOffset);
readConverterSavedStateOffset += readBufferOffset;
readBufferOffset = 0;
}
}
}
/*! \internal
*/
inline void QTextStreamPrivate::saveConverterState(qint64 newPos)
{
#ifndef QT_NO_TEXTCODEC
if (readConverterState.d) {
// converter cannot be copied, so don't save anything
// don't update readBufferStartDevicePos either
return;
}
if (!readConverterSavedState)
readConverterSavedState = new QTextCodec::ConverterState;
copyConverterStateHelper(readConverterSavedState, &readConverterState);
#endif
readBufferStartDevicePos = newPos;
readConverterSavedStateOffset = 0;
}
/*! \internal
*/
inline void QTextStreamPrivate::restoreToSavedConverterState()
{
#ifndef QT_NO_TEXTCODEC
if (readConverterSavedState) {
// we have a saved state
// that means the converter can be copied
copyConverterStateHelper(&readConverterState, readConverterSavedState);
} else {
// the only state we could save was the initial
// so reset to that
resetCodecConverterStateHelper(&readConverterState);
}
#endif
}
/*! \internal
*/
inline bool QTextStreamPrivate::write(const QString &data)
{
if (string) {
// ### What about seek()??
string->append(data);
} else {
writeBuffer += data;
if (writeBuffer.size() > QTEXTSTREAM_BUFFERSIZE)
return flushWriteBuffer();
}
return true;
}
/*! \internal
*/
inline bool QTextStreamPrivate::getChar(QChar *ch)
{
if ((string && stringOffset == string->size())
|| (device && readBuffer.isEmpty() && !fillReadBuffer())) {
if (ch)
*ch = 0;
return false;
}
if (ch)
*ch = *readPtr();
consume(1);
return true;
}
/*! \internal
*/
inline void QTextStreamPrivate::ungetChar(const QChar &ch)
{
if (string) {
if (stringOffset == 0)
string->prepend(ch);
else
(*string)[--stringOffset] = ch;
return;
}
if (readBufferOffset == 0) {
readBuffer.prepend(ch);
return;
}
readBuffer[--readBufferOffset] = ch;
}
/*! \internal
*/
inline bool QTextStreamPrivate::putString(const QString &s, bool number)
{
QString tmp = s;
// handle padding
int padSize = fieldWidth - s.size();
if (padSize > 0) {
QString pad(padSize, padChar);
if (fieldAlignment == QTextStream::AlignLeft) {
tmp.append(QString(padSize, padChar));
} else if (fieldAlignment == QTextStream::AlignRight
|| fieldAlignment == QTextStream::AlignAccountingStyle) {
tmp.prepend(QString(padSize, padChar));
if (fieldAlignment == QTextStream::AlignAccountingStyle && number) {
const QChar sign = s.size() > 0 ? s.at(0) : QChar();
if (sign == locale.negativeSign() || sign == locale.positiveSign()) {
QChar *data = tmp.data();
data[padSize] = tmp.at(0);
data[0] = sign;
}
}
} else if (fieldAlignment == QTextStream::AlignCenter) {
tmp.prepend(QString(padSize/2, padChar));
tmp.append(QString(padSize - padSize/2, padChar));
}
}
#if defined (QTEXTSTREAM_DEBUG)
QByteArray a = s.toUtf8();
QByteArray b = tmp.toUtf8();
qDebug("QTextStreamPrivate::putString(\"%s\") calls write(\"%s\")",
qt_prettyDebug(a.constData(), a.size(), qMax(16, a.size())).constData(),
qt_prettyDebug(b.constData(), b.size(), qMax(16, b.size())).constData());
#endif
return write(tmp);
}
/*!
Constructs a QTextStream. Before you can use it for reading or