~gabriel1984sibiu/minitube/qt5.6

« back to all changes in this revision

Viewing changes to src/corelib/io/qiodevice.cpp

  • Committer: Grevutiu Gabriel
  • Date: 2017-06-13 08:43:17 UTC
  • Revision ID: gabriel1984sibiu@gmail.com-20170613084317-ek0zqe0u9g3ocvi8
OriginalĀ upstreamĀ code

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/****************************************************************************
 
2
**
 
3
** Copyright (C) 2016 The Qt Company Ltd.
 
4
** Contact: https://www.qt.io/licensing/
 
5
**
 
6
** This file is part of the QtCore module of the Qt Toolkit.
 
7
**
 
8
** $QT_BEGIN_LICENSE:LGPL$
 
9
** Commercial License Usage
 
10
** Licensees holding valid commercial Qt licenses may use this file in
 
11
** accordance with the commercial license agreement provided with the
 
12
** Software or, alternatively, in accordance with the terms contained in
 
13
** a written agreement between you and The Qt Company. For licensing terms
 
14
** and conditions see https://www.qt.io/terms-conditions. For further
 
15
** information use the contact form at https://www.qt.io/contact-us.
 
16
**
 
17
** GNU Lesser General Public License Usage
 
18
** Alternatively, this file may be used under the terms of the GNU Lesser
 
19
** General Public License version 3 as published by the Free Software
 
20
** Foundation and appearing in the file LICENSE.LGPL3 included in the
 
21
** packaging of this file. Please review the following information to
 
22
** ensure the GNU Lesser General Public License version 3 requirements
 
23
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
 
24
**
 
25
** GNU General Public License Usage
 
26
** Alternatively, this file may be used under the terms of the GNU
 
27
** General Public License version 2.0 or (at your option) the GNU General
 
28
** Public license version 3 or any later version approved by the KDE Free
 
29
** Qt Foundation. The licenses are as published by the Free Software
 
30
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
 
31
** included in the packaging of this file. Please review the following
 
32
** information to ensure the GNU General Public License requirements will
 
33
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
 
34
** https://www.gnu.org/licenses/gpl-3.0.html.
 
35
**
 
36
** $QT_END_LICENSE$
 
37
**
 
38
****************************************************************************/
 
39
 
 
40
//#define QIODEVICE_DEBUG
 
41
 
 
42
#include "qbytearray.h"
 
43
#include "qdebug.h"
 
44
#include "qiodevice_p.h"
 
45
#include "qfile.h"
 
46
#include "qstringlist.h"
 
47
#include "qdir.h"
 
48
#include "private/qbytearray_p.h"
 
49
 
 
50
#include <algorithm>
 
51
 
 
52
#ifdef QIODEVICE_DEBUG
 
53
#  include <ctype.h>
 
54
#endif
 
55
 
 
56
QT_BEGIN_NAMESPACE
 
57
 
 
58
#ifdef QIODEVICE_DEBUG
 
59
void debugBinaryString(const QByteArray &input)
 
60
{
 
61
    QByteArray tmp;
 
62
    int startOffset = 0;
 
63
    for (int i = 0; i < input.size(); ++i) {
 
64
        tmp += input[i];
 
65
 
 
66
        if ((i % 16) == 15 || i == (input.size() - 1)) {
 
67
            printf("\n%15d:", startOffset);
 
68
            startOffset += tmp.size();
 
69
 
 
70
            for (int j = 0; j < tmp.size(); ++j)
 
71
                printf(" %02x", int(uchar(tmp[j])));
 
72
            for (int j = tmp.size(); j < 16 + 1; ++j)
 
73
                printf("   ");
 
74
            for (int j = 0; j < tmp.size(); ++j)
 
75
                printf("%c", isprint(int(uchar(tmp[j]))) ? tmp[j] : '.');
 
76
            tmp.clear();
 
77
        }
 
78
    }
 
79
    printf("\n\n");
 
80
}
 
81
 
 
82
void debugBinaryString(const char *data, qint64 maxlen)
 
83
{
 
84
    debugBinaryString(QByteArray(data, maxlen));
 
85
}
 
86
#endif
 
87
 
 
88
#define Q_VOID
 
89
 
 
90
static void checkWarnMessage(const QIODevice *device, const char *function, const char *what)
 
91
{
 
92
#ifndef QT_NO_WARNING_OUTPUT
 
93
    QDebug d = qWarning();
 
94
    d.noquote();
 
95
    d.nospace();
 
96
    d << "QIODevice::" << function;
 
97
#ifndef QT_NO_QOBJECT
 
98
    d << " (" << device->metaObject()->className();
 
99
    if (!device->objectName().isEmpty())
 
100
        d << ", \"" << device->objectName() << '"';
 
101
    if (const QFile *f = qobject_cast<const QFile *>(device))
 
102
        d << ", \"" << QDir::toNativeSeparators(f->fileName()) << '"';
 
103
    d << ')';
 
104
#else
 
105
    Q_UNUSED(device)
 
106
#endif // !QT_NO_QOBJECT
 
107
    d << ": " << what;
 
108
#else
 
109
    Q_UNUSED(device);
 
110
    Q_UNUSED(function);
 
111
    Q_UNUSED(what);
 
112
#endif // QT_NO_WARNING_OUTPUT
 
113
}
 
114
 
 
115
#define CHECK_MAXLEN(function, returnType) \
 
116
    do { \
 
117
        if (maxSize < 0) { \
 
118
            checkWarnMessage(this, #function, "Called with maxSize < 0"); \
 
119
            return returnType; \
 
120
        } \
 
121
    } while (0)
 
122
 
 
123
#define CHECK_MAXBYTEARRAYSIZE(function) \
 
124
    do { \
 
125
        if (maxSize >= MaxByteArraySize) { \
 
126
            checkWarnMessage(this, #function, "maxSize argument exceeds QByteArray size limit"); \
 
127
            maxSize = MaxByteArraySize - 1; \
 
128
        } \
 
129
    } while (0)
 
130
 
 
131
#define CHECK_WRITABLE(function, returnType) \
 
132
   do { \
 
133
       if ((d->openMode & WriteOnly) == 0) { \
 
134
           if (d->openMode == NotOpen) { \
 
135
               checkWarnMessage(this, #function, "device not open"); \
 
136
               return returnType; \
 
137
           } \
 
138
           checkWarnMessage(this, #function, "ReadOnly device"); \
 
139
           return returnType; \
 
140
       } \
 
141
   } while (0)
 
142
 
 
143
#define CHECK_READABLE(function, returnType) \
 
144
   do { \
 
145
       if ((d->openMode & ReadOnly) == 0) { \
 
146
           if (d->openMode == NotOpen) { \
 
147
               checkWarnMessage(this, #function, "device not open"); \
 
148
               return returnType; \
 
149
           } \
 
150
           checkWarnMessage(this, #function, "WriteOnly device"); \
 
151
           return returnType; \
 
152
       } \
 
153
   } while (0)
 
154
 
 
155
/*!
 
156
    \internal
 
157
 */
 
158
QIODevicePrivate::QIODevicePrivate()
 
159
    : openMode(QIODevice::NotOpen),
 
160
      pos(0), devicePos(0),
 
161
      readChannelCount(0),
 
162
      writeChannelCount(0),
 
163
      currentReadChannel(0),
 
164
      currentWriteChannel(0),
 
165
      readBufferChunkSize(QIODEVICE_BUFFERSIZE),
 
166
      writeBufferChunkSize(0),
 
167
      transactionPos(0),
 
168
      transactionStarted(false)
 
169
       , baseReadLineDataCalled(false)
 
170
       , accessMode(Unset)
 
171
#ifdef QT_NO_QOBJECT
 
172
       , q_ptr(0)
 
173
#endif
 
174
{
 
175
}
 
176
 
 
177
/*!
 
178
    \internal
 
179
 */
 
180
QIODevicePrivate::~QIODevicePrivate()
 
181
{
 
182
}
 
183
 
 
184
/*!
 
185
    \class QIODevice
 
186
    \inmodule QtCore
 
187
    \reentrant
 
188
 
 
189
    \brief The QIODevice class is the base interface class of all I/O
 
190
    devices in Qt.
 
191
 
 
192
    \ingroup io
 
193
 
 
194
    QIODevice provides both a common implementation and an abstract
 
195
    interface for devices that support reading and writing of blocks
 
196
    of data, such as QFile, QBuffer and QTcpSocket. QIODevice is
 
197
    abstract and can not be instantiated, but it is common to use the
 
198
    interface it defines to provide device-independent I/O features.
 
199
    For example, Qt's XML classes operate on a QIODevice pointer,
 
200
    allowing them to be used with various devices (such as files and
 
201
    buffers).
 
202
 
 
203
    Before accessing the device, open() must be called to set the
 
204
    correct OpenMode (such as ReadOnly or ReadWrite). You can then
 
205
    write to the device with write() or putChar(), and read by calling
 
206
    either read(), readLine(), or readAll(). Call close() when you are
 
207
    done with the device.
 
208
 
 
209
    QIODevice distinguishes between two types of devices:
 
210
    random-access devices and sequential devices.
 
211
 
 
212
    \list
 
213
    \li Random-access devices support seeking to arbitrary
 
214
    positions using seek(). The current position in the file is
 
215
    available by calling pos(). QFile and QBuffer are examples of
 
216
    random-access devices.
 
217
 
 
218
    \li Sequential devices don't support seeking to arbitrary
 
219
    positions. The data must be read in one pass. The functions
 
220
    pos() and size() don't work for sequential devices.
 
221
    QTcpSocket and QProcess are examples of sequential devices.
 
222
    \endlist
 
223
 
 
224
    You can use isSequential() to determine the type of device.
 
225
 
 
226
    QIODevice emits readyRead() when new data is available for
 
227
    reading; for example, if new data has arrived on the network or if
 
228
    additional data is appended to a file that you are reading
 
229
    from. You can call bytesAvailable() to determine the number of
 
230
    bytes that are currently available for reading. It's common to use
 
231
    bytesAvailable() together with the readyRead() signal when
 
232
    programming with asynchronous devices such as QTcpSocket, where
 
233
    fragments of data can arrive at arbitrary points in
 
234
    time. QIODevice emits the bytesWritten() signal every time a
 
235
    payload of data has been written to the device. Use bytesToWrite()
 
236
    to determine the current amount of data waiting to be written.
 
237
 
 
238
    Certain subclasses of QIODevice, such as QTcpSocket and QProcess,
 
239
    are asynchronous. This means that I/O functions such as write()
 
240
    or read() always return immediately, while communication with the
 
241
    device itself may happen when control goes back to the event loop.
 
242
    QIODevice provides functions that allow you to force these
 
243
    operations to be performed immediately, while blocking the
 
244
    calling thread and without entering the event loop. This allows
 
245
    QIODevice subclasses to be used without an event loop, or in
 
246
    a separate thread:
 
247
 
 
248
    \list
 
249
    \li waitForReadyRead() - This function suspends operation in the
 
250
    calling thread until new data is available for reading.
 
251
 
 
252
    \li waitForBytesWritten() - This function suspends operation in the
 
253
    calling thread until one payload of data has been written to the
 
254
    device.
 
255
 
 
256
    \li waitFor....() - Subclasses of QIODevice implement blocking
 
257
    functions for device-specific operations. For example, QProcess
 
258
    has a function called \l {QProcess::}{waitForStarted()} which suspends operation in
 
259
    the calling thread until the process has started.
 
260
    \endlist
 
261
 
 
262
    Calling these functions from the main, GUI thread, may cause your
 
263
    user interface to freeze. Example:
 
264
 
 
265
    \snippet code/src_corelib_io_qiodevice.cpp 0
 
266
 
 
267
    By subclassing QIODevice, you can provide the same interface to
 
268
    your own I/O devices. Subclasses of QIODevice are only required to
 
269
    implement the protected readData() and writeData() functions.
 
270
    QIODevice uses these functions to implement all its convenience
 
271
    functions, such as getChar(), readLine() and write(). QIODevice
 
272
    also handles access control for you, so you can safely assume that
 
273
    the device is opened in write mode if writeData() is called.
 
274
 
 
275
    Some subclasses, such as QFile and QTcpSocket, are implemented
 
276
    using a memory buffer for intermediate storing of data. This
 
277
    reduces the number of required device accessing calls, which are
 
278
    often very slow. Buffering makes functions like getChar() and
 
279
    putChar() fast, as they can operate on the memory buffer instead
 
280
    of directly on the device itself. Certain I/O operations, however,
 
281
    don't work well with a buffer. For example, if several users open
 
282
    the same device and read it character by character, they may end
 
283
    up reading the same data when they meant to read a separate chunk
 
284
    each. For this reason, QIODevice allows you to bypass any
 
285
    buffering by passing the Unbuffered flag to open(). When
 
286
    subclassing QIODevice, remember to bypass any buffer you may use
 
287
    when the device is open in Unbuffered mode.
 
288
 
 
289
    Usually, the incoming data stream from an asynchronous device is
 
290
    fragmented, and chunks of data can arrive at arbitrary points in time.
 
291
    To handle incomplete reads of data structures, use the transaction
 
292
    mechanism implemented by QIODevice. See startTransaction() and related
 
293
    functions for more details.
 
294
 
 
295
    Some sequential devices support communicating via multiple channels. These
 
296
    channels represent separate streams of data that have the property of
 
297
    independently sequenced delivery. Once the device is opened, you can
 
298
    determine the number of channels by calling the readChannelCount() and
 
299
    writeChannelCount() functions. To switch between channels, call
 
300
    setCurrentReadChannel() and setCurrentWriteChannel(), respectively.
 
301
    QIODevice also provides additional signals to handle asynchronous
 
302
    communication on a per-channel basis.
 
303
 
 
304
    \sa QBuffer, QFile, QTcpSocket
 
305
*/
 
306
 
 
307
/*!
 
308
    \enum QIODevice::OpenModeFlag
 
309
 
 
310
    This enum is used with open() to describe the mode in which a device
 
311
    is opened. It is also returned by openMode().
 
312
 
 
313
    \value NotOpen   The device is not open.
 
314
    \value ReadOnly  The device is open for reading.
 
315
    \value WriteOnly The device is open for writing. Note that this mode implies
 
316
                     Truncate.
 
317
    \value ReadWrite The device is open for reading and writing.
 
318
    \value Append    The device is opened in append mode so that all data is
 
319
                     written to the end of the file.
 
320
    \value Truncate  If possible, the device is truncated before it is opened.
 
321
                     All earlier contents of the device are lost.
 
322
    \value Text      When reading, the end-of-line terminators are
 
323
                     translated to '\\n'. When writing, the end-of-line
 
324
                     terminators are translated to the local encoding, for
 
325
                     example '\\r\\n' for Win32.
 
326
    \value Unbuffered Any buffer in the device is bypassed.
 
327
 
 
328
    Certain flags, such as \c Unbuffered and \c Truncate, are
 
329
    meaningless when used with some subclasses. Some of these
 
330
    restrictions are implied by the type of device that is represented
 
331
    by a subclass. In other cases, the restriction may be due to the
 
332
    implementation, or may be imposed by the underlying platform; for
 
333
    example, QTcpSocket does not support \c Unbuffered mode, and
 
334
    limitations in the native API prevent QFile from supporting \c
 
335
    Unbuffered on Windows.
 
336
*/
 
337
 
 
338
/*!     \fn QIODevice::bytesWritten(qint64 bytes)
 
339
 
 
340
    This signal is emitted every time a payload of data has been
 
341
    written to the device's current write channel. The \a bytes argument is
 
342
    set to the number of bytes that were written in this payload.
 
343
 
 
344
    bytesWritten() is not emitted recursively; if you reenter the event loop
 
345
    or call waitForBytesWritten() inside a slot connected to the
 
346
    bytesWritten() signal, the signal will not be reemitted (although
 
347
    waitForBytesWritten() may still return true).
 
348
 
 
349
    \sa readyRead()
 
350
*/
 
351
 
 
352
/*!
 
353
    \fn QIODevice::channelBytesWritten(int channel, qint64 bytes)
 
354
    \since 5.7
 
355
 
 
356
    This signal is emitted every time a payload of data has been written to
 
357
    the device. The \a bytes argument is set to the number of bytes that were
 
358
    written in this payload, while \a channel is the channel they were written
 
359
    to. Unlike bytesWritten(), it is emitted regardless of the
 
360
    \l{currentWriteChannel()}{current write channel}.
 
361
 
 
362
    channelBytesWritten() can be emitted recursively - even for the same
 
363
    channel.
 
364
 
 
365
    \sa bytesWritten(), channelReadyRead()
 
366
*/
 
367
 
 
368
/*!
 
369
    \fn QIODevice::readyRead()
 
370
 
 
371
    This signal is emitted once every time new data is available for
 
372
    reading from the device's current read channel. It will only be emitted
 
373
    again once new data is available, such as when a new payload of network
 
374
    data has arrived on your network socket, or when a new block of data has
 
375
    been appended to your device.
 
376
 
 
377
    readyRead() is not emitted recursively; if you reenter the event loop or
 
378
    call waitForReadyRead() inside a slot connected to the readyRead() signal,
 
379
    the signal will not be reemitted (although waitForReadyRead() may still
 
380
    return true).
 
381
 
 
382
    Note for developers implementing classes derived from QIODevice:
 
383
    you should always emit readyRead() when new data has arrived (do not
 
384
    emit it only because there's data still to be read in your
 
385
    buffers). Do not emit readyRead() in other conditions.
 
386
 
 
387
    \sa bytesWritten()
 
388
*/
 
389
 
 
390
/*!
 
391
    \fn QIODevice::channelReadyRead(int channel)
 
392
    \since 5.7
 
393
 
 
394
    This signal is emitted when new data is available for reading from the
 
395
    device. The \a channel argument is set to the index of the read channel on
 
396
    which the data has arrived. Unlike readyRead(), it is emitted regardless of
 
397
    the \l{currentReadChannel()}{current read channel}.
 
398
 
 
399
    channelReadyRead() can be emitted recursively - even for the same channel.
 
400
 
 
401
    \sa readyRead(), channelBytesWritten()
 
402
*/
 
403
 
 
404
/*! \fn QIODevice::aboutToClose()
 
405
 
 
406
    This signal is emitted when the device is about to close. Connect
 
407
    this signal if you have operations that need to be performed
 
408
    before the device closes (e.g., if you have data in a separate
 
409
    buffer that needs to be written to the device).
 
410
*/
 
411
 
 
412
/*!
 
413
    \fn QIODevice::readChannelFinished()
 
414
    \since 4.4
 
415
 
 
416
    This signal is emitted when the input (reading) stream is closed
 
417
    in this device. It is emitted as soon as the closing is detected,
 
418
    which means that there might still be data available for reading
 
419
    with read().
 
420
 
 
421
    \sa atEnd(), read()
 
422
*/
 
423
 
 
424
#ifdef QT_NO_QOBJECT
 
425
QIODevice::QIODevice()
 
426
    : d_ptr(new QIODevicePrivate)
 
427
{
 
428
    d_ptr->q_ptr = this;
 
429
}
 
430
 
 
431
/*!
 
432
    \internal
 
433
*/
 
434
QIODevice::QIODevice(QIODevicePrivate &dd)
 
435
    : d_ptr(&dd)
 
436
{
 
437
    d_ptr->q_ptr = this;
 
438
}
 
439
#else
 
440
 
 
441
/*!
 
442
    Constructs a QIODevice object.
 
443
*/
 
444
 
 
445
QIODevice::QIODevice()
 
446
    : QObject(*new QIODevicePrivate, 0)
 
447
{
 
448
#if defined QIODEVICE_DEBUG
 
449
    QFile *file = qobject_cast<QFile *>(this);
 
450
    printf("%p QIODevice::QIODevice(\"%s\") %s\n", this, metaObject()->className(),
 
451
           qPrintable(file ? file->fileName() : QString()));
 
452
#endif
 
453
}
 
454
 
 
455
/*!
 
456
    Constructs a QIODevice object with the given \a parent.
 
457
*/
 
458
 
 
459
QIODevice::QIODevice(QObject *parent)
 
460
    : QObject(*new QIODevicePrivate, parent)
 
461
{
 
462
#if defined QIODEVICE_DEBUG
 
463
    printf("%p QIODevice::QIODevice(%p \"%s\")\n", this, parent, metaObject()->className());
 
464
#endif
 
465
}
 
466
 
 
467
/*!
 
468
    \internal
 
469
*/
 
470
QIODevice::QIODevice(QIODevicePrivate &dd, QObject *parent)
 
471
    : QObject(dd, parent)
 
472
{
 
473
}
 
474
#endif
 
475
 
 
476
 
 
477
/*!
 
478
  The destructor is virtual, and QIODevice is an abstract base
 
479
  class. This destructor does not call close(), but the subclass
 
480
  destructor might. If you are in doubt, call close() before
 
481
  destroying the QIODevice.
 
482
*/
 
483
QIODevice::~QIODevice()
 
484
{
 
485
#if defined QIODEVICE_DEBUG
 
486
    printf("%p QIODevice::~QIODevice()\n", this);
 
487
#endif
 
488
}
 
489
 
 
490
/*!
 
491
    Returns \c true if this device is sequential; otherwise returns
 
492
    false.
 
493
 
 
494
    Sequential devices, as opposed to a random-access devices, have no
 
495
    concept of a start, an end, a size, or a current position, and they
 
496
    do not support seeking. You can only read from the device when it
 
497
    reports that data is available. The most common example of a
 
498
    sequential device is a network socket. On Unix, special files such
 
499
    as /dev/zero and fifo pipes are sequential.
 
500
 
 
501
    Regular files, on the other hand, do support random access. They
 
502
    have both a size and a current position, and they also support
 
503
    seeking backwards and forwards in the data stream. Regular files
 
504
    are non-sequential.
 
505
 
 
506
    \sa bytesAvailable()
 
507
*/
 
508
bool QIODevice::isSequential() const
 
509
{
 
510
    return false;
 
511
}
 
512
 
 
513
/*!
 
514
    Returns the mode in which the device has been opened;
 
515
    i.e. ReadOnly or WriteOnly.
 
516
 
 
517
    \sa OpenMode
 
518
*/
 
519
QIODevice::OpenMode QIODevice::openMode() const
 
520
{
 
521
    return d_func()->openMode;
 
522
}
 
523
 
 
524
/*!
 
525
    Sets the OpenMode of the device to \a openMode. Call this
 
526
    function to set the open mode if the flags change after the device
 
527
    has been opened.
 
528
 
 
529
    \sa openMode(), OpenMode
 
530
*/
 
531
void QIODevice::setOpenMode(OpenMode openMode)
 
532
{
 
533
    Q_D(QIODevice);
 
534
#if defined QIODEVICE_DEBUG
 
535
    printf("%p QIODevice::setOpenMode(0x%x)\n", this, int(openMode));
 
536
#endif
 
537
    d->openMode = openMode;
 
538
    d->accessMode = QIODevicePrivate::Unset;
 
539
    d->setReadChannelCount(isReadable() ? qMax(d->readChannelCount, 1) : 0);
 
540
    d->setWriteChannelCount(isWritable() ? qMax(d->writeChannelCount, 1) : 0);
 
541
}
 
542
 
 
543
/*!
 
544
    If \a enabled is true, this function sets the \l Text flag on the device;
 
545
    otherwise the \l Text flag is removed. This feature is useful for classes
 
546
    that provide custom end-of-line handling on a QIODevice.
 
547
 
 
548
    The IO device should be opened before calling this function.
 
549
 
 
550
    \sa open(), setOpenMode()
 
551
 */
 
552
void QIODevice::setTextModeEnabled(bool enabled)
 
553
{
 
554
    Q_D(QIODevice);
 
555
    if (!isOpen()) {
 
556
        checkWarnMessage(this, "setTextModeEnabled", "The device is not open");
 
557
        return;
 
558
    }
 
559
    if (enabled)
 
560
        d->openMode |= Text;
 
561
    else
 
562
        d->openMode &= ~Text;
 
563
}
 
564
 
 
565
/*!
 
566
    Returns \c true if the \l Text flag is enabled; otherwise returns \c false.
 
567
 
 
568
    \sa setTextModeEnabled()
 
569
*/
 
570
bool QIODevice::isTextModeEnabled() const
 
571
{
 
572
    return d_func()->openMode & Text;
 
573
}
 
574
 
 
575
/*!
 
576
    Returns \c true if the device is open; otherwise returns \c false. A
 
577
    device is open if it can be read from and/or written to. By
 
578
    default, this function returns \c false if openMode() returns
 
579
    \c NotOpen.
 
580
 
 
581
    \sa openMode(), OpenMode
 
582
*/
 
583
bool QIODevice::isOpen() const
 
584
{
 
585
    return d_func()->openMode != NotOpen;
 
586
}
 
587
 
 
588
/*!
 
589
    Returns \c true if data can be read from the device; otherwise returns
 
590
    false. Use bytesAvailable() to determine how many bytes can be read.
 
591
 
 
592
    This is a convenience function which checks if the OpenMode of the
 
593
    device contains the ReadOnly flag.
 
594
 
 
595
    \sa openMode(), OpenMode
 
596
*/
 
597
bool QIODevice::isReadable() const
 
598
{
 
599
    return (openMode() & ReadOnly) != 0;
 
600
}
 
601
 
 
602
/*!
 
603
    Returns \c true if data can be written to the device; otherwise returns
 
604
    false.
 
605
 
 
606
    This is a convenience function which checks if the OpenMode of the
 
607
    device contains the WriteOnly flag.
 
608
 
 
609
    \sa openMode(), OpenMode
 
610
*/
 
611
bool QIODevice::isWritable() const
 
612
{
 
613
    return (openMode() & WriteOnly) != 0;
 
614
}
 
615
 
 
616
/*!
 
617
    \since 5.7
 
618
 
 
619
    Returns the number of available read channels if the device is open;
 
620
    otherwise returns 0.
 
621
 
 
622
    \sa writeChannelCount(), QProcess
 
623
*/
 
624
int QIODevice::readChannelCount() const
 
625
{
 
626
    return d_func()->readChannelCount;
 
627
}
 
628
 
 
629
/*!
 
630
    \since 5.7
 
631
 
 
632
    Returns the number of available write channels if the device is open;
 
633
    otherwise returns 0.
 
634
 
 
635
    \sa readChannelCount()
 
636
*/
 
637
int QIODevice::writeChannelCount() const
 
638
{
 
639
    return d_func()->writeChannelCount;
 
640
}
 
641
 
 
642
/*!
 
643
    \since 5.7
 
644
 
 
645
    Returns the index of the current read channel.
 
646
 
 
647
    \sa setCurrentReadChannel(), readChannelCount(), QProcess
 
648
*/
 
649
int QIODevice::currentReadChannel() const
 
650
{
 
651
    return d_func()->currentReadChannel;
 
652
}
 
653
 
 
654
/*!
 
655
    \since 5.7
 
656
 
 
657
    Sets the current read channel of the QIODevice to the given \a
 
658
    channel. The current input channel is used by the functions
 
659
    read(), readAll(), readLine(), and getChar(). It also determines
 
660
    which channel triggers QIODevice to emit readyRead().
 
661
 
 
662
    \sa currentReadChannel(), readChannelCount(), QProcess
 
663
*/
 
664
void QIODevice::setCurrentReadChannel(int channel)
 
665
{
 
666
    Q_D(QIODevice);
 
667
 
 
668
    if (d->transactionStarted) {
 
669
        checkWarnMessage(this, "setReadChannel", "Failed due to read transaction being in progress");
 
670
        return;
 
671
    }
 
672
 
 
673
#if defined QIODEVICE_DEBUG
 
674
    qDebug("%p QIODevice::setCurrentReadChannel(%d), d->currentReadChannel = %d, d->readChannelCount = %d\n",
 
675
           this, channel, d->currentReadChannel, d->readChannelCount);
 
676
#endif
 
677
 
 
678
    d->setCurrentReadChannel(channel);
 
679
}
 
680
 
 
681
/*!
 
682
    \internal
 
683
*/
 
684
void QIODevicePrivate::setReadChannelCount(int count)
 
685
{
 
686
    if (count > readBuffers.size()) {
 
687
        readBuffers.insert(readBuffers.end(), count - readBuffers.size(),
 
688
                           QRingBuffer(readBufferChunkSize));
 
689
    } else {
 
690
        readBuffers.resize(count);
 
691
    }
 
692
    readChannelCount = count;
 
693
    setCurrentReadChannel(currentReadChannel);
 
694
}
 
695
 
 
696
/*!
 
697
    \since 5.7
 
698
 
 
699
    Returns the the index of the current write channel.
 
700
 
 
701
    \sa setCurrentWriteChannel(), writeChannelCount()
 
702
*/
 
703
int QIODevice::currentWriteChannel() const
 
704
{
 
705
    return d_func()->currentWriteChannel;
 
706
}
 
707
 
 
708
/*!
 
709
    \since 5.7
 
710
 
 
711
    Sets the current write channel of the QIODevice to the given \a
 
712
    channel. The current output channel is used by the functions
 
713
    write(), putChar(). It also determines  which channel triggers
 
714
    QIODevice to emit bytesWritten().
 
715
 
 
716
    \sa currentWriteChannel(), writeChannelCount()
 
717
*/
 
718
void QIODevice::setCurrentWriteChannel(int channel)
 
719
{
 
720
    Q_D(QIODevice);
 
721
 
 
722
#if defined QIODEVICE_DEBUG
 
723
    qDebug("%p QIODevice::setCurrentWriteChannel(%d), d->currentWriteChannel = %d, d->writeChannelCount = %d\n",
 
724
           this, channel, d->currentWriteChannel, d->writeChannelCount);
 
725
#endif
 
726
 
 
727
    d->setCurrentWriteChannel(channel);
 
728
}
 
729
 
 
730
/*!
 
731
    \internal
 
732
*/
 
733
void QIODevicePrivate::setWriteChannelCount(int count)
 
734
{
 
735
    if (count > writeBuffers.size()) {
 
736
        // If writeBufferChunkSize is zero (default value), we don't use
 
737
        // QIODevice's write buffers.
 
738
        if (writeBufferChunkSize != 0) {
 
739
            writeBuffers.insert(writeBuffers.end(), count - writeBuffers.size(),
 
740
                                QRingBuffer(writeBufferChunkSize));
 
741
        }
 
742
    } else {
 
743
        writeBuffers.resize(count);
 
744
    }
 
745
    writeChannelCount = count;
 
746
    setCurrentWriteChannel(currentWriteChannel);
 
747
}
 
748
 
 
749
/*!
 
750
    Opens the device and sets its OpenMode to \a mode. Returns \c true if successful;
 
751
    otherwise returns \c false. This function should be called from any
 
752
    reimplementations of open() or other functions that open the device.
 
753
 
 
754
    \sa openMode(), OpenMode
 
755
*/
 
756
bool QIODevice::open(OpenMode mode)
 
757
{
 
758
    Q_D(QIODevice);
 
759
    d->openMode = mode;
 
760
    d->pos = (mode & Append) ? size() : qint64(0);
 
761
    d->accessMode = QIODevicePrivate::Unset;
 
762
    d->readBuffers.clear();
 
763
    d->writeBuffers.clear();
 
764
    d->setReadChannelCount(isReadable() ? 1 : 0);
 
765
    d->setWriteChannelCount(isWritable() ? 1 : 0);
 
766
#if defined QIODEVICE_DEBUG
 
767
    printf("%p QIODevice::open(0x%x)\n", this, quint32(mode));
 
768
#endif
 
769
    return true;
 
770
}
 
771
 
 
772
/*!
 
773
    First emits aboutToClose(), then closes the device and sets its
 
774
    OpenMode to NotOpen. The error string is also reset.
 
775
 
 
776
    \sa setOpenMode(), OpenMode
 
777
*/
 
778
void QIODevice::close()
 
779
{
 
780
    Q_D(QIODevice);
 
781
    if (d->openMode == NotOpen)
 
782
        return;
 
783
 
 
784
#if defined QIODEVICE_DEBUG
 
785
    printf("%p QIODevice::close()\n", this);
 
786
#endif
 
787
 
 
788
#ifndef QT_NO_QOBJECT
 
789
    emit aboutToClose();
 
790
#endif
 
791
    d->openMode = NotOpen;
 
792
    d->errorString.clear();
 
793
    d->pos = 0;
 
794
    d->transactionStarted = false;
 
795
    d->transactionPos = 0;
 
796
    d->setReadChannelCount(0);
 
797
    // Do not clear write buffers to allow delayed close in sockets
 
798
    d->writeChannelCount = 0;
 
799
}
 
800
 
 
801
/*!
 
802
    For random-access devices, this function returns the position that
 
803
    data is written to or read from. For sequential devices or closed
 
804
    devices, where there is no concept of a "current position", 0 is
 
805
    returned.
 
806
 
 
807
    The current read/write position of the device is maintained internally by
 
808
    QIODevice, so reimplementing this function is not necessary. When
 
809
    subclassing QIODevice, use QIODevice::seek() to notify QIODevice about
 
810
    changes in the device position.
 
811
 
 
812
    \sa isSequential(), seek()
 
813
*/
 
814
qint64 QIODevice::pos() const
 
815
{
 
816
    Q_D(const QIODevice);
 
817
#if defined QIODEVICE_DEBUG
 
818
    printf("%p QIODevice::pos() == %lld\n", this, d->pos);
 
819
#endif
 
820
    return d->pos;
 
821
}
 
822
 
 
823
/*!
 
824
    For open random-access devices, this function returns the size of the
 
825
    device. For open sequential devices, bytesAvailable() is returned.
 
826
 
 
827
    If the device is closed, the size returned will not reflect the actual
 
828
    size of the device.
 
829
 
 
830
    \sa isSequential(), pos()
 
831
*/
 
832
qint64 QIODevice::size() const
 
833
{
 
834
    return d_func()->isSequential() ?  bytesAvailable() : qint64(0);
 
835
}
 
836
 
 
837
/*!
 
838
    For random-access devices, this function sets the current position
 
839
    to \a pos, returning true on success, or false if an error occurred.
 
840
    For sequential devices, the default behavior is to produce a warning
 
841
    and return false.
 
842
 
 
843
    When subclassing QIODevice, you must call QIODevice::seek() at the
 
844
    start of your function to ensure integrity with QIODevice's
 
845
    built-in buffer.
 
846
 
 
847
    \sa pos(), isSequential()
 
848
*/
 
849
bool QIODevice::seek(qint64 pos)
 
850
{
 
851
    Q_D(QIODevice);
 
852
    if (d->isSequential()) {
 
853
        checkWarnMessage(this, "seek", "Cannot call seek on a sequential device");
 
854
        return false;
 
855
    }
 
856
    if (d->openMode == NotOpen) {
 
857
        checkWarnMessage(this, "seek", "The device is not open");
 
858
        return false;
 
859
    }
 
860
    if (pos < 0) {
 
861
        qWarning("QIODevice::seek: Invalid pos: %lld", pos);
 
862
        return false;
 
863
    }
 
864
 
 
865
#if defined QIODEVICE_DEBUG
 
866
    printf("%p QIODevice::seek(%lld), before: d->pos = %lld, d->buffer.size() = %lld\n",
 
867
           this, pos, d->pos, d->buffer.size());
 
868
#endif
 
869
 
 
870
    d->devicePos = pos;
 
871
    d->seekBuffer(pos);
 
872
 
 
873
#if defined QIODEVICE_DEBUG
 
874
    printf("%p \tafter: d->pos == %lld, d->buffer.size() == %lld\n", this, d->pos,
 
875
           d->buffer.size());
 
876
#endif
 
877
    return true;
 
878
}
 
879
 
 
880
/*!
 
881
    \internal
 
882
*/
 
883
void QIODevicePrivate::seekBuffer(qint64 newPos)
 
884
{
 
885
    const qint64 offset = newPos - pos;
 
886
    pos = newPos;
 
887
 
 
888
    if (offset < 0 || offset >= buffer.size()) {
 
889
        // When seeking backwards, an operation that is only allowed for
 
890
        // random-access devices, the buffer is cleared. The next read
 
891
        // operation will then refill the buffer.
 
892
        buffer.clear();
 
893
    } else {
 
894
        buffer.free(offset);
 
895
    }
 
896
}
 
897
 
 
898
/*!
 
899
    Returns \c true if the current read and write position is at the end
 
900
    of the device (i.e. there is no more data available for reading on
 
901
    the device); otherwise returns \c false.
 
902
 
 
903
    For some devices, atEnd() can return true even though there is more data
 
904
    to read. This special case only applies to devices that generate data in
 
905
    direct response to you calling read() (e.g., \c /dev or \c /proc files on
 
906
    Unix and \macos, or console input / \c stdin on all platforms).
 
907
 
 
908
    \sa bytesAvailable(), read(), isSequential()
 
909
*/
 
910
bool QIODevice::atEnd() const
 
911
{
 
912
    Q_D(const QIODevice);
 
913
    const bool result = (d->openMode == NotOpen || (d->isBufferEmpty()
 
914
                                                    && bytesAvailable() == 0));
 
915
#if defined QIODEVICE_DEBUG
 
916
    printf("%p QIODevice::atEnd() returns %s, d->openMode == %d, d->pos == %lld\n", this,
 
917
           result ? "true" : "false", int(d->openMode), d->pos);
 
918
#endif
 
919
    return result;
 
920
}
 
921
 
 
922
/*!
 
923
    Seeks to the start of input for random-access devices. Returns
 
924
    true on success; otherwise returns \c false (for example, if the
 
925
    device is not open).
 
926
 
 
927
    Note that when using a QTextStream on a QFile, calling reset() on
 
928
    the QFile will not have the expected result because QTextStream
 
929
    buffers the file. Use the QTextStream::seek() function instead.
 
930
 
 
931
    \sa seek()
 
932
*/
 
933
bool QIODevice::reset()
 
934
{
 
935
#if defined QIODEVICE_DEBUG
 
936
    printf("%p QIODevice::reset()\n", this);
 
937
#endif
 
938
    return seek(0);
 
939
}
 
940
 
 
941
/*!
 
942
    Returns the number of bytes that are available for reading. This
 
943
    function is commonly used with sequential devices to determine the
 
944
    number of bytes to allocate in a buffer before reading.
 
945
 
 
946
    Subclasses that reimplement this function must call the base
 
947
    implementation in order to include the size of the buffer of QIODevice. Example:
 
948
 
 
949
    \snippet code/src_corelib_io_qiodevice.cpp 1
 
950
 
 
951
    \sa bytesToWrite(), readyRead(), isSequential()
 
952
*/
 
953
qint64 QIODevice::bytesAvailable() const
 
954
{
 
955
    Q_D(const QIODevice);
 
956
    if (!d->isSequential())
 
957
        return qMax(size() - d->pos, qint64(0));
 
958
    return d->buffer.size() - d->transactionPos;
 
959
}
 
960
 
 
961
/*!  For buffered devices, this function returns the number of bytes
 
962
    waiting to be written. For devices with no buffer, this function
 
963
    returns 0.
 
964
 
 
965
    Subclasses that reimplement this function must call the base
 
966
    implementation in order to include the size of the buffer of QIODevice.
 
967
 
 
968
    \sa bytesAvailable(), bytesWritten(), isSequential()
 
969
*/
 
970
qint64 QIODevice::bytesToWrite() const
 
971
{
 
972
    return d_func()->writeBuffer.size();
 
973
}
 
974
 
 
975
/*!
 
976
    Reads at most \a maxSize bytes from the device into \a data, and
 
977
    returns the number of bytes read. If an error occurs, such as when
 
978
    attempting to read from a device opened in WriteOnly mode, this
 
979
    function returns -1.
 
980
 
 
981
    0 is returned when no more data is available for reading. However,
 
982
    reading past the end of the stream is considered an error, so this
 
983
    function returns -1 in those cases (that is, reading on a closed
 
984
    socket or after a process has died).
 
985
 
 
986
    \sa readData(), readLine(), write()
 
987
*/
 
988
qint64 QIODevice::read(char *data, qint64 maxSize)
 
989
{
 
990
    Q_D(QIODevice);
 
991
 
 
992
#if defined QIODEVICE_DEBUG
 
993
    printf("%p QIODevice::read(%p, %lld), d->pos = %lld, d->buffer.size() = %lld\n",
 
994
           this, data, maxSize, d->pos, d->buffer.size());
 
995
#endif
 
996
 
 
997
    const bool sequential = d->isSequential();
 
998
    const bool keepDataInBuffer = sequential && d->transactionStarted;
 
999
 
 
1000
    // Short circuit for getChar()
 
1001
    if (maxSize == 1 && !keepDataInBuffer) {
 
1002
        int chint;
 
1003
        while ((chint = d->buffer.getChar()) != -1) {
 
1004
            if (!sequential)
 
1005
                ++d->pos;
 
1006
 
 
1007
            char c = char(uchar(chint));
 
1008
            if (c == '\r' && (d->openMode & Text))
 
1009
                continue;
 
1010
            *data = c;
 
1011
#if defined QIODEVICE_DEBUG
 
1012
            printf("%p \tread 0x%hhx (%c) returning 1 (shortcut)\n", this,
 
1013
                   int(c), isprint(c) ? c : '?');
 
1014
#endif
 
1015
            if (d->buffer.isEmpty())
 
1016
                readData(data, 0);
 
1017
            return qint64(1);
 
1018
        }
 
1019
    }
 
1020
 
 
1021
    CHECK_MAXLEN(read, qint64(-1));
 
1022
    qint64 readSoFar = 0;
 
1023
    bool madeBufferReadsOnly = true;
 
1024
    bool deviceAtEof = false;
 
1025
    char *readPtr = data;
 
1026
    forever {
 
1027
        // Try reading from the buffer.
 
1028
        qint64 bufferReadChunkSize = keepDataInBuffer
 
1029
                                     ? d->buffer.peek(data, maxSize, d->transactionPos)
 
1030
                                     : d->buffer.read(data, maxSize);
 
1031
        if (bufferReadChunkSize > 0) {
 
1032
            if (keepDataInBuffer)
 
1033
                d->transactionPos += bufferReadChunkSize;
 
1034
            else if (!sequential)
 
1035
                d->pos += bufferReadChunkSize;
 
1036
            readSoFar += bufferReadChunkSize;
 
1037
            data += bufferReadChunkSize;
 
1038
            maxSize -= bufferReadChunkSize;
 
1039
#if defined QIODEVICE_DEBUG
 
1040
            printf("%p \treading %lld bytes from buffer into position %lld\n", this,
 
1041
                   bufferReadChunkSize, readSoFar - bufferReadChunkSize);
 
1042
#endif
 
1043
        } else {
 
1044
            CHECK_READABLE(read, qint64(-1));
 
1045
        }
 
1046
 
 
1047
        if (maxSize > 0 && !deviceAtEof) {
 
1048
            qint64 readFromDevice = 0;
 
1049
            // Make sure the device is positioned correctly.
 
1050
            if (sequential || d->pos == d->devicePos || seek(d->pos)) {
 
1051
                madeBufferReadsOnly = false; // fix readData attempt
 
1052
                if ((maxSize >= d->readBufferChunkSize || (d->openMode & Unbuffered))
 
1053
                    && !keepDataInBuffer) {
 
1054
                    // Read big chunk directly to output buffer
 
1055
                    readFromDevice = readData(data, maxSize);
 
1056
                    deviceAtEof = (readFromDevice != maxSize);
 
1057
#if defined QIODEVICE_DEBUG
 
1058
                    printf("%p \treading %lld bytes from device (total %lld)\n", this,
 
1059
                           readFromDevice, readSoFar);
 
1060
#endif
 
1061
                    if (readFromDevice > 0) {
 
1062
                        readSoFar += readFromDevice;
 
1063
                        data += readFromDevice;
 
1064
                        maxSize -= readFromDevice;
 
1065
                        if (!sequential) {
 
1066
                            d->pos += readFromDevice;
 
1067
                            d->devicePos += readFromDevice;
 
1068
                        }
 
1069
                    }
 
1070
                } else {
 
1071
                    // Do not read more than maxSize on unbuffered devices
 
1072
                    const qint64 bytesToBuffer = (d->openMode & Unbuffered)
 
1073
                            ? qMin(maxSize, qint64(d->readBufferChunkSize))
 
1074
                            : qint64(d->readBufferChunkSize);
 
1075
                    // Try to fill QIODevice buffer by single read
 
1076
                    readFromDevice = readData(d->buffer.reserve(bytesToBuffer), bytesToBuffer);
 
1077
                    deviceAtEof = (readFromDevice != bytesToBuffer);
 
1078
                    d->buffer.chop(bytesToBuffer - qMax(Q_INT64_C(0), readFromDevice));
 
1079
                    if (readFromDevice > 0) {
 
1080
                        if (!sequential)
 
1081
                            d->devicePos += readFromDevice;
 
1082
#if defined QIODEVICE_DEBUG
 
1083
                        printf("%p \treading %lld from device into buffer\n", this,
 
1084
                               readFromDevice);
 
1085
#endif
 
1086
                        continue;
 
1087
                    }
 
1088
                }
 
1089
            } else {
 
1090
                readFromDevice = -1;
 
1091
            }
 
1092
 
 
1093
            if (readFromDevice < 0 && readSoFar == 0) {
 
1094
                // error and we haven't read anything: return immediately
 
1095
                return qint64(-1);
 
1096
            }
 
1097
        }
 
1098
 
 
1099
        if ((d->openMode & Text) && readPtr < data) {
 
1100
            const char *endPtr = data;
 
1101
 
 
1102
            // optimization to avoid initial self-assignment
 
1103
            while (*readPtr != '\r') {
 
1104
                if (++readPtr == endPtr)
 
1105
                    break;
 
1106
            }
 
1107
 
 
1108
            char *writePtr = readPtr;
 
1109
 
 
1110
            while (readPtr < endPtr) {
 
1111
                char ch = *readPtr++;
 
1112
                if (ch != '\r')
 
1113
                    *writePtr++ = ch;
 
1114
                else {
 
1115
                    --readSoFar;
 
1116
                    --data;
 
1117
                    ++maxSize;
 
1118
                }
 
1119
            }
 
1120
 
 
1121
            // Make sure we get more data if there is room for more. This
 
1122
            // is very important for when someone seeks to the start of a
 
1123
            // '\r\n' and reads one character - they should get the '\n'.
 
1124
            readPtr = data;
 
1125
            continue;
 
1126
        }
 
1127
 
 
1128
        break;
 
1129
    }
 
1130
 
 
1131
#if defined QIODEVICE_DEBUG
 
1132
    printf("%p \treturning %lld, d->pos == %lld, d->buffer.size() == %lld\n", this,
 
1133
           readSoFar, d->pos, d->buffer.size());
 
1134
    debugBinaryString(data - readSoFar, readSoFar);
 
1135
#endif
 
1136
 
 
1137
    if (madeBufferReadsOnly && d->isBufferEmpty())
 
1138
        readData(data, 0);
 
1139
 
 
1140
    return readSoFar;
 
1141
}
 
1142
 
 
1143
/*!
 
1144
    \overload
 
1145
 
 
1146
    Reads at most \a maxSize bytes from the device, and returns the
 
1147
    data read as a QByteArray.
 
1148
 
 
1149
    This function has no way of reporting errors; returning an empty
 
1150
    QByteArray can mean either that no data was currently available
 
1151
    for reading, or that an error occurred.
 
1152
*/
 
1153
 
 
1154
QByteArray QIODevice::read(qint64 maxSize)
 
1155
{
 
1156
    Q_D(QIODevice);
 
1157
    QByteArray result;
 
1158
 
 
1159
    CHECK_MAXLEN(read, result);
 
1160
    CHECK_MAXBYTEARRAYSIZE(read);
 
1161
 
 
1162
#if defined QIODEVICE_DEBUG
 
1163
    printf("%p QIODevice::read(%lld), d->pos = %lld, d->buffer.size() = %lld\n",
 
1164
           this, maxSize, d->pos, d->buffer.size());
 
1165
#endif
 
1166
 
 
1167
    qint64 readBytes = 0;
 
1168
    if (maxSize) {
 
1169
        result.resize(int(maxSize));
 
1170
        if (!result.size()) {
 
1171
            // If resize fails, read incrementally.
 
1172
            qint64 readResult;
 
1173
            do {
 
1174
                result.resize(int(qMin(maxSize, qint64(result.size() + d->readBufferChunkSize))));
 
1175
                readResult = read(result.data() + readBytes, result.size() - readBytes);
 
1176
                if (readResult > 0 || readBytes == 0)
 
1177
                    readBytes += readResult;
 
1178
            } while (readResult == d->readBufferChunkSize);
 
1179
        } else {
 
1180
            readBytes = read(result.data(), result.size());
 
1181
        }
 
1182
    }
 
1183
 
 
1184
    if (readBytes <= 0)
 
1185
        result.clear();
 
1186
    else
 
1187
        result.resize(int(readBytes));
 
1188
 
 
1189
    return result;
 
1190
}
 
1191
 
 
1192
/*!
 
1193
    Reads all remaining data from the device, and returns it as a
 
1194
    byte array.
 
1195
 
 
1196
    This function has no way of reporting errors; returning an empty
 
1197
    QByteArray can mean either that no data was currently available
 
1198
    for reading, or that an error occurred.
 
1199
*/
 
1200
QByteArray QIODevice::readAll()
 
1201
{
 
1202
    Q_D(QIODevice);
 
1203
#if defined QIODEVICE_DEBUG
 
1204
    printf("%p QIODevice::readAll(), d->pos = %lld, d->buffer.size() = %lld\n",
 
1205
           this, d->pos, d->buffer.size());
 
1206
#endif
 
1207
 
 
1208
    QByteArray result;
 
1209
    qint64 readBytes = (d->isSequential() ? Q_INT64_C(0) : size());
 
1210
    if (readBytes == 0) {
 
1211
        // Size is unknown, read incrementally.
 
1212
        qint64 readChunkSize = qMax(qint64(d->readBufferChunkSize),
 
1213
                                    d->isSequential() ? (d->buffer.size() - d->transactionPos)
 
1214
                                                      : d->buffer.size());
 
1215
        qint64 readResult;
 
1216
        do {
 
1217
            if (readBytes + readChunkSize >= MaxByteArraySize) {
 
1218
                // If resize would fail, don't read more, return what we have.
 
1219
                break;
 
1220
            }
 
1221
            result.resize(readBytes + readChunkSize);
 
1222
            readResult = read(result.data() + readBytes, readChunkSize);
 
1223
            if (readResult > 0 || readBytes == 0) {
 
1224
                readBytes += readResult;
 
1225
                readChunkSize = d->readBufferChunkSize;
 
1226
            }
 
1227
        } while (readResult > 0);
 
1228
    } else {
 
1229
        // Read it all in one go.
 
1230
        // If resize fails, don't read anything.
 
1231
        readBytes -= d->pos;
 
1232
        if (readBytes >= MaxByteArraySize)
 
1233
            return QByteArray();
 
1234
        result.resize(readBytes);
 
1235
        readBytes = read(result.data(), readBytes);
 
1236
    }
 
1237
 
 
1238
    if (readBytes <= 0)
 
1239
        result.clear();
 
1240
    else
 
1241
        result.resize(int(readBytes));
 
1242
 
 
1243
    return result;
 
1244
}
 
1245
 
 
1246
/*!
 
1247
    This function reads a line of ASCII characters from the device, up
 
1248
    to a maximum of \a maxSize - 1 bytes, stores the characters in \a
 
1249
    data, and returns the number of bytes read. If a line could not be
 
1250
    read but no error ocurred, this function returns 0. If an error
 
1251
    occurs, this function returns the length of what could be read, or
 
1252
    -1 if nothing was read.
 
1253
 
 
1254
    A terminating '\\0' byte is always appended to \a data, so \a
 
1255
    maxSize must be larger than 1.
 
1256
 
 
1257
    Data is read until either of the following conditions are met:
 
1258
 
 
1259
    \list
 
1260
    \li The first '\\n' character is read.
 
1261
    \li \a maxSize - 1 bytes are read.
 
1262
    \li The end of the device data is detected.
 
1263
    \endlist
 
1264
 
 
1265
    For example, the following code reads a line of characters from a
 
1266
    file:
 
1267
 
 
1268
    \snippet code/src_corelib_io_qiodevice.cpp 2
 
1269
 
 
1270
    The newline character ('\\n') is included in the buffer. If a
 
1271
    newline is not encountered before maxSize - 1 bytes are read, a
 
1272
    newline will not be inserted into the buffer. On windows newline
 
1273
    characters are replaced with '\\n'.
 
1274
 
 
1275
    This function calls readLineData(), which is implemented using
 
1276
    repeated calls to getChar(). You can provide a more efficient
 
1277
    implementation by reimplementing readLineData() in your own
 
1278
    subclass.
 
1279
 
 
1280
    \sa getChar(), read(), write()
 
1281
*/
 
1282
qint64 QIODevice::readLine(char *data, qint64 maxSize)
 
1283
{
 
1284
    Q_D(QIODevice);
 
1285
    if (maxSize < 2) {
 
1286
        checkWarnMessage(this, "readLine", "Called with maxSize < 2");
 
1287
        return qint64(-1);
 
1288
    }
 
1289
 
 
1290
#if defined QIODEVICE_DEBUG
 
1291
    printf("%p QIODevice::readLine(%p, %lld), d->pos = %lld, d->buffer.size() = %lld\n",
 
1292
           this, data, maxSize, d->pos, d->buffer.size());
 
1293
#endif
 
1294
 
 
1295
    // Leave room for a '\0'
 
1296
    --maxSize;
 
1297
 
 
1298
    const bool sequential = d->isSequential();
 
1299
    const bool keepDataInBuffer = sequential && d->transactionStarted;
 
1300
 
 
1301
    qint64 readSoFar = 0;
 
1302
    if (keepDataInBuffer) {
 
1303
        if (d->transactionPos < d->buffer.size()) {
 
1304
            // Peek line from the specified position
 
1305
            const qint64 i = d->buffer.indexOf('\n', maxSize, d->transactionPos);
 
1306
            readSoFar = d->buffer.peek(data, i >= 0 ? (i - d->transactionPos + 1) : maxSize,
 
1307
                                       d->transactionPos);
 
1308
            d->transactionPos += readSoFar;
 
1309
            if (d->transactionPos == d->buffer.size())
 
1310
                readData(data, 0);
 
1311
        }
 
1312
    } else if (!d->buffer.isEmpty()) {
 
1313
        // QRingBuffer::readLine() terminates the line with '\0'
 
1314
        readSoFar = d->buffer.readLine(data, maxSize + 1);
 
1315
        if (d->buffer.isEmpty())
 
1316
            readData(data,0);
 
1317
        if (!sequential)
 
1318
            d->pos += readSoFar;
 
1319
    }
 
1320
 
 
1321
    if (readSoFar) {
 
1322
#if defined QIODEVICE_DEBUG
 
1323
        printf("%p \tread from buffer: %lld bytes, last character read: %hhx\n", this,
 
1324
               readSoFar, data[readSoFar - 1]);
 
1325
        debugBinaryString(data, int(readSoFar));
 
1326
#endif
 
1327
        if (data[readSoFar - 1] == '\n') {
 
1328
            if (d->openMode & Text) {
 
1329
                // QRingBuffer::readLine() isn't Text aware.
 
1330
                if (readSoFar > 1 && data[readSoFar - 2] == '\r') {
 
1331
                    --readSoFar;
 
1332
                    data[readSoFar - 1] = '\n';
 
1333
                }
 
1334
            }
 
1335
            data[readSoFar] = '\0';
 
1336
            return readSoFar;
 
1337
        }
 
1338
    }
 
1339
 
 
1340
    if (d->pos != d->devicePos && !sequential && !seek(d->pos))
 
1341
        return qint64(-1);
 
1342
    d->baseReadLineDataCalled = false;
 
1343
    // Force base implementation for transaction on sequential device
 
1344
    // as it stores the data in internal buffer automatically.
 
1345
    qint64 readBytes = keepDataInBuffer
 
1346
                       ? QIODevice::readLineData(data + readSoFar, maxSize - readSoFar)
 
1347
                       : readLineData(data + readSoFar, maxSize - readSoFar);
 
1348
#if defined QIODEVICE_DEBUG
 
1349
    printf("%p \tread from readLineData: %lld bytes, readSoFar = %lld bytes\n", this,
 
1350
           readBytes, readSoFar);
 
1351
    if (readBytes > 0) {
 
1352
        debugBinaryString(data, int(readSoFar + readBytes));
 
1353
    }
 
1354
#endif
 
1355
    if (readBytes < 0) {
 
1356
        data[readSoFar] = '\0';
 
1357
        return readSoFar ? readSoFar : -1;
 
1358
    }
 
1359
    readSoFar += readBytes;
 
1360
    if (!d->baseReadLineDataCalled && !sequential) {
 
1361
        d->pos += readBytes;
 
1362
        // If the base implementation was not called, then we must
 
1363
        // assume the device position is invalid and force a seek.
 
1364
        d->devicePos = qint64(-1);
 
1365
    }
 
1366
    data[readSoFar] = '\0';
 
1367
 
 
1368
    if (d->openMode & Text) {
 
1369
        if (readSoFar > 1 && data[readSoFar - 1] == '\n' && data[readSoFar - 2] == '\r') {
 
1370
            data[readSoFar - 2] = '\n';
 
1371
            data[readSoFar - 1] = '\0';
 
1372
            --readSoFar;
 
1373
        }
 
1374
    }
 
1375
 
 
1376
#if defined QIODEVICE_DEBUG
 
1377
    printf("%p \treturning %lld, d->pos = %lld, d->buffer.size() = %lld, size() = %lld\n",
 
1378
           this, readSoFar, d->pos, d->buffer.size(), size());
 
1379
    debugBinaryString(data, int(readSoFar));
 
1380
#endif
 
1381
    return readSoFar;
 
1382
}
 
1383
 
 
1384
/*!
 
1385
    \overload
 
1386
 
 
1387
    Reads a line from the device, but no more than \a maxSize characters,
 
1388
    and returns the result as a byte array.
 
1389
 
 
1390
    This function has no way of reporting errors; returning an empty
 
1391
    QByteArray can mean either that no data was currently available
 
1392
    for reading, or that an error occurred.
 
1393
*/
 
1394
QByteArray QIODevice::readLine(qint64 maxSize)
 
1395
{
 
1396
    Q_D(QIODevice);
 
1397
    QByteArray result;
 
1398
 
 
1399
    CHECK_MAXLEN(readLine, result);
 
1400
    CHECK_MAXBYTEARRAYSIZE(readLine);
 
1401
 
 
1402
#if defined QIODEVICE_DEBUG
 
1403
    printf("%p QIODevice::readLine(%lld), d->pos = %lld, d->buffer.size() = %lld\n",
 
1404
           this, maxSize, d->pos, d->buffer.size());
 
1405
#endif
 
1406
 
 
1407
    result.resize(int(maxSize));
 
1408
    qint64 readBytes = 0;
 
1409
    if (!result.size()) {
 
1410
        // If resize fails or maxSize == 0, read incrementally
 
1411
        if (maxSize == 0)
 
1412
            maxSize = MaxByteArraySize - 1;
 
1413
 
 
1414
        // The first iteration needs to leave an extra byte for the terminating null
 
1415
        result.resize(1);
 
1416
 
 
1417
        qint64 readResult;
 
1418
        do {
 
1419
            result.resize(int(qMin(maxSize, qint64(result.size() + d->readBufferChunkSize))));
 
1420
            readResult = readLine(result.data() + readBytes, result.size() - readBytes);
 
1421
            if (readResult > 0 || readBytes == 0)
 
1422
                readBytes += readResult;
 
1423
        } while (readResult == d->readBufferChunkSize
 
1424
                && result[int(readBytes - 1)] != '\n');
 
1425
    } else
 
1426
        readBytes = readLine(result.data(), result.size());
 
1427
 
 
1428
    if (readBytes <= 0)
 
1429
        result.clear();
 
1430
    else
 
1431
        result.resize(readBytes);
 
1432
 
 
1433
    return result;
 
1434
}
 
1435
 
 
1436
/*!
 
1437
    Reads up to \a maxSize characters into \a data and returns the
 
1438
    number of characters read.
 
1439
 
 
1440
    This function is called by readLine(), and provides its base
 
1441
    implementation, using getChar(). Buffered devices can improve the
 
1442
    performance of readLine() by reimplementing this function.
 
1443
 
 
1444
    readLine() appends a '\\0' byte to \a data; readLineData() does not
 
1445
    need to do this.
 
1446
 
 
1447
    If you reimplement this function, be careful to return the correct
 
1448
    value: it should return the number of bytes read in this line,
 
1449
    including the terminating newline, or 0 if there is no line to be
 
1450
    read at this point. If an error occurs, it should return -1 if and
 
1451
    only if no bytes were read. Reading past EOF is considered an error.
 
1452
*/
 
1453
qint64 QIODevice::readLineData(char *data, qint64 maxSize)
 
1454
{
 
1455
    Q_D(QIODevice);
 
1456
    qint64 readSoFar = 0;
 
1457
    char c;
 
1458
    int lastReadReturn = 0;
 
1459
    d->baseReadLineDataCalled = true;
 
1460
 
 
1461
    while (readSoFar < maxSize && (lastReadReturn = read(&c, 1)) == 1) {
 
1462
        *data++ = c;
 
1463
        ++readSoFar;
 
1464
        if (c == '\n')
 
1465
            break;
 
1466
    }
 
1467
 
 
1468
#if defined QIODEVICE_DEBUG
 
1469
    printf("%p QIODevice::readLineData(%p, %lld), d->pos = %lld, d->buffer.size() = %lld, "
 
1470
           "returns %lld\n", this, data, maxSize, d->pos, d->buffer.size(), readSoFar);
 
1471
#endif
 
1472
    if (lastReadReturn != 1 && readSoFar == 0)
 
1473
        return isSequential() ? lastReadReturn : -1;
 
1474
    return readSoFar;
 
1475
}
 
1476
 
 
1477
/*!
 
1478
    Returns \c true if a complete line of data can be read from the device;
 
1479
    otherwise returns \c false.
 
1480
 
 
1481
    Note that unbuffered devices, which have no way of determining what
 
1482
    can be read, always return false.
 
1483
 
 
1484
    This function is often called in conjunction with the readyRead()
 
1485
    signal.
 
1486
 
 
1487
    Subclasses that reimplement this function must call the base
 
1488
    implementation in order to include the contents of the QIODevice's buffer. Example:
 
1489
 
 
1490
    \snippet code/src_corelib_io_qiodevice.cpp 3
 
1491
 
 
1492
    \sa readyRead(), readLine()
 
1493
*/
 
1494
bool QIODevice::canReadLine() const
 
1495
{
 
1496
    Q_D(const QIODevice);
 
1497
    return d->buffer.indexOf('\n', d->buffer.size(),
 
1498
                             d->isSequential() ? d->transactionPos : Q_INT64_C(0)) >= 0;
 
1499
}
 
1500
 
 
1501
/*!
 
1502
    \since 5.7
 
1503
 
 
1504
    Starts a new read transaction on the device.
 
1505
 
 
1506
    Defines a restorable point within the sequence of read operations. For
 
1507
    sequential devices, read data will be duplicated internally to allow
 
1508
    recovery in case of incomplete reads. For random-access devices,
 
1509
    this function saves the current position. Call commitTransaction() or
 
1510
    rollbackTransaction() to finish the transaction.
 
1511
 
 
1512
    \note Nesting transactions is not supported.
 
1513
 
 
1514
    \sa commitTransaction(), rollbackTransaction()
 
1515
*/
 
1516
void QIODevice::startTransaction()
 
1517
{
 
1518
    Q_D(QIODevice);
 
1519
    if (d->transactionStarted) {
 
1520
        checkWarnMessage(this, "startTransaction", "Called while transaction already in progress");
 
1521
        return;
 
1522
    }
 
1523
    d->transactionPos = d->pos;
 
1524
    d->transactionStarted = true;
 
1525
}
 
1526
 
 
1527
/*!
 
1528
    \since 5.7
 
1529
 
 
1530
    Completes a read transaction.
 
1531
 
 
1532
    For sequential devices, all data recorded in the internal buffer during
 
1533
    the transaction will be discarded.
 
1534
 
 
1535
    \sa startTransaction(), rollbackTransaction()
 
1536
*/
 
1537
void QIODevice::commitTransaction()
 
1538
{
 
1539
    Q_D(QIODevice);
 
1540
    if (!d->transactionStarted) {
 
1541
        checkWarnMessage(this, "commitTransaction", "Called while no transaction in progress");
 
1542
        return;
 
1543
    }
 
1544
    if (d->isSequential())
 
1545
        d->buffer.free(d->transactionPos);
 
1546
    d->transactionStarted = false;
 
1547
    d->transactionPos = 0;
 
1548
}
 
1549
 
 
1550
/*!
 
1551
    \since 5.7
 
1552
 
 
1553
    Rolls back a read transaction.
 
1554
 
 
1555
    Restores the input stream to the point of the startTransaction() call.
 
1556
    This function is commonly used to rollback the transaction when an
 
1557
    incomplete read was detected prior to committing the transaction.
 
1558
 
 
1559
    \sa startTransaction(), commitTransaction()
 
1560
*/
 
1561
void QIODevice::rollbackTransaction()
 
1562
{
 
1563
    Q_D(QIODevice);
 
1564
    if (!d->transactionStarted) {
 
1565
        checkWarnMessage(this, "rollbackTransaction", "Called while no transaction in progress");
 
1566
        return;
 
1567
    }
 
1568
    if (!d->isSequential())
 
1569
        d->seekBuffer(d->transactionPos);
 
1570
    d->transactionStarted = false;
 
1571
    d->transactionPos = 0;
 
1572
}
 
1573
 
 
1574
/*!
 
1575
    \since 5.7
 
1576
 
 
1577
    Returns \c true if a transaction is in progress on the device, otherwise
 
1578
    \c false.
 
1579
 
 
1580
    \sa startTransaction()
 
1581
*/
 
1582
bool QIODevice::isTransactionStarted() const
 
1583
{
 
1584
    return d_func()->transactionStarted;
 
1585
}
 
1586
 
 
1587
/*!
 
1588
    Writes at most \a maxSize bytes of data from \a data to the
 
1589
    device. Returns the number of bytes that were actually written, or
 
1590
    -1 if an error occurred.
 
1591
 
 
1592
    \sa read(), writeData()
 
1593
*/
 
1594
qint64 QIODevice::write(const char *data, qint64 maxSize)
 
1595
{
 
1596
    Q_D(QIODevice);
 
1597
    CHECK_WRITABLE(write, qint64(-1));
 
1598
    CHECK_MAXLEN(write, qint64(-1));
 
1599
 
 
1600
    const bool sequential = d->isSequential();
 
1601
    // Make sure the device is positioned correctly.
 
1602
    if (d->pos != d->devicePos && !sequential && !seek(d->pos))
 
1603
        return qint64(-1);
 
1604
 
 
1605
#ifdef Q_OS_WIN
 
1606
    if (d->openMode & Text) {
 
1607
        const char *endOfData = data + maxSize;
 
1608
        const char *startOfBlock = data;
 
1609
 
 
1610
        qint64 writtenSoFar = 0;
 
1611
        const qint64 savedPos = d->pos;
 
1612
 
 
1613
        forever {
 
1614
            const char *endOfBlock = startOfBlock;
 
1615
            while (endOfBlock < endOfData && *endOfBlock != '\n')
 
1616
                ++endOfBlock;
 
1617
 
 
1618
            qint64 blockSize = endOfBlock - startOfBlock;
 
1619
            if (blockSize > 0) {
 
1620
                qint64 ret = writeData(startOfBlock, blockSize);
 
1621
                if (ret <= 0) {
 
1622
                    if (writtenSoFar && !sequential)
 
1623
                        d->buffer.skip(d->pos - savedPos);
 
1624
                    return writtenSoFar ? writtenSoFar : ret;
 
1625
                }
 
1626
                if (!sequential) {
 
1627
                    d->pos += ret;
 
1628
                    d->devicePos += ret;
 
1629
                }
 
1630
                writtenSoFar += ret;
 
1631
            }
 
1632
 
 
1633
            if (endOfBlock == endOfData)
 
1634
                break;
 
1635
 
 
1636
            qint64 ret = writeData("\r\n", 2);
 
1637
            if (ret <= 0) {
 
1638
                if (writtenSoFar && !sequential)
 
1639
                    d->buffer.skip(d->pos - savedPos);
 
1640
                return writtenSoFar ? writtenSoFar : ret;
 
1641
            }
 
1642
            if (!sequential) {
 
1643
                d->pos += ret;
 
1644
                d->devicePos += ret;
 
1645
            }
 
1646
            ++writtenSoFar;
 
1647
 
 
1648
            startOfBlock = endOfBlock + 1;
 
1649
        }
 
1650
 
 
1651
        if (writtenSoFar && !sequential)
 
1652
            d->buffer.skip(d->pos - savedPos);
 
1653
        return writtenSoFar;
 
1654
    }
 
1655
#endif
 
1656
 
 
1657
    qint64 written = writeData(data, maxSize);
 
1658
    if (!sequential && written > 0) {
 
1659
        d->pos += written;
 
1660
        d->devicePos += written;
 
1661
        d->buffer.skip(written);
 
1662
    }
 
1663
    return written;
 
1664
}
 
1665
 
 
1666
/*!
 
1667
    \since 4.5
 
1668
 
 
1669
    \overload
 
1670
 
 
1671
    Writes data from a zero-terminated string of 8-bit characters to the
 
1672
    device. Returns the number of bytes that were actually written, or
 
1673
    -1 if an error occurred. This is equivalent to
 
1674
    \code
 
1675
    ...
 
1676
    QIODevice::write(data, qstrlen(data));
 
1677
    ...
 
1678
    \endcode
 
1679
 
 
1680
    \sa read(), writeData()
 
1681
*/
 
1682
qint64 QIODevice::write(const char *data)
 
1683
{
 
1684
    return write(data, qstrlen(data));
 
1685
}
 
1686
 
 
1687
/*! \fn qint64 QIODevice::write(const QByteArray &byteArray)
 
1688
 
 
1689
    \overload
 
1690
 
 
1691
    Writes the content of \a byteArray to the device. Returns the number of
 
1692
    bytes that were actually written, or -1 if an error occurred.
 
1693
 
 
1694
    \sa read(), writeData()
 
1695
*/
 
1696
 
 
1697
/*!
 
1698
    Puts the character \a c back into the device, and decrements the
 
1699
    current position unless the position is 0. This function is
 
1700
    usually called to "undo" a getChar() operation, such as when
 
1701
    writing a backtracking parser.
 
1702
 
 
1703
    If \a c was not previously read from the device, the behavior is
 
1704
    undefined.
 
1705
 
 
1706
    \note This function is not available while a transaction is in progress.
 
1707
*/
 
1708
void QIODevice::ungetChar(char c)
 
1709
{
 
1710
    Q_D(QIODevice);
 
1711
    CHECK_READABLE(read, Q_VOID);
 
1712
 
 
1713
    if (d->transactionStarted) {
 
1714
        checkWarnMessage(this, "ungetChar", "Called while transaction is in progress");
 
1715
        return;
 
1716
    }
 
1717
 
 
1718
#if defined QIODEVICE_DEBUG
 
1719
    printf("%p QIODevice::ungetChar(0x%hhx '%c')\n", this, c, isprint(c) ? c : '?');
 
1720
#endif
 
1721
 
 
1722
    d->buffer.ungetChar(c);
 
1723
    if (!d->isSequential())
 
1724
        --d->pos;
 
1725
}
 
1726
 
 
1727
/*! \fn bool QIODevice::putChar(char c)
 
1728
 
 
1729
    Writes the character \a c to the device. Returns \c true on success;
 
1730
    otherwise returns \c false.
 
1731
 
 
1732
    \sa write(), getChar(), ungetChar()
 
1733
*/
 
1734
bool QIODevice::putChar(char c)
 
1735
{
 
1736
    return d_func()->putCharHelper(c);
 
1737
}
 
1738
 
 
1739
/*!
 
1740
    \internal
 
1741
*/
 
1742
bool QIODevicePrivate::putCharHelper(char c)
 
1743
{
 
1744
    return q_func()->write(&c, 1) == 1;
 
1745
}
 
1746
 
 
1747
/*!
 
1748
    \internal
 
1749
*/
 
1750
qint64 QIODevicePrivate::peek(char *data, qint64 maxSize)
 
1751
{
 
1752
    Q_Q(QIODevice);
 
1753
 
 
1754
    if (transactionStarted) {
 
1755
        const qint64 savedTransactionPos = transactionPos;
 
1756
        const qint64 savedPos = pos;
 
1757
 
 
1758
        qint64 readBytes = q->read(data, maxSize);
 
1759
 
 
1760
        // Restore initial position
 
1761
        if (isSequential())
 
1762
            transactionPos = savedTransactionPos;
 
1763
        else
 
1764
            seekBuffer(savedPos);
 
1765
        return readBytes;
 
1766
    }
 
1767
 
 
1768
    q->startTransaction();
 
1769
    qint64 readBytes = q->read(data, maxSize);
 
1770
    q->rollbackTransaction();
 
1771
 
 
1772
    return readBytes;
 
1773
}
 
1774
 
 
1775
/*!
 
1776
    \internal
 
1777
*/
 
1778
QByteArray QIODevicePrivate::peek(qint64 maxSize)
 
1779
{
 
1780
    Q_Q(QIODevice);
 
1781
 
 
1782
    if (transactionStarted) {
 
1783
        const qint64 savedTransactionPos = transactionPos;
 
1784
        const qint64 savedPos = pos;
 
1785
 
 
1786
        QByteArray result = q->read(maxSize);
 
1787
 
 
1788
        // Restore initial position
 
1789
        if (isSequential())
 
1790
            transactionPos = savedTransactionPos;
 
1791
        else
 
1792
            seekBuffer(savedPos);
 
1793
        return result;
 
1794
    }
 
1795
 
 
1796
    q->startTransaction();
 
1797
    QByteArray result = q->read(maxSize);
 
1798
    q->rollbackTransaction();
 
1799
 
 
1800
    return result;
 
1801
}
 
1802
 
 
1803
/*! \fn bool QIODevice::getChar(char *c)
 
1804
 
 
1805
    Reads one character from the device and stores it in \a c. If \a c
 
1806
    is 0, the character is discarded. Returns \c true on success;
 
1807
    otherwise returns \c false.
 
1808
 
 
1809
    \sa read(), putChar(), ungetChar()
 
1810
*/
 
1811
bool QIODevice::getChar(char *c)
 
1812
{
 
1813
    // readability checked in read()
 
1814
    char ch;
 
1815
    return (1 == read(c ? c : &ch, 1));
 
1816
}
 
1817
 
 
1818
/*!
 
1819
    \since 4.1
 
1820
 
 
1821
    Reads at most \a maxSize bytes from the device into \a data, without side
 
1822
    effects (i.e., if you call read() after peek(), you will get the same
 
1823
    data).  Returns the number of bytes read. If an error occurs, such as
 
1824
    when attempting to peek a device opened in WriteOnly mode, this function
 
1825
    returns -1.
 
1826
 
 
1827
    0 is returned when no more data is available for reading.
 
1828
 
 
1829
    Example:
 
1830
 
 
1831
    \snippet code/src_corelib_io_qiodevice.cpp 4
 
1832
 
 
1833
    \sa read()
 
1834
*/
 
1835
qint64 QIODevice::peek(char *data, qint64 maxSize)
 
1836
{
 
1837
    return d_func()->peek(data, maxSize);
 
1838
}
 
1839
 
 
1840
/*!
 
1841
    \since 4.1
 
1842
    \overload
 
1843
 
 
1844
    Peeks at most \a maxSize bytes from the device, returning the data peeked
 
1845
    as a QByteArray.
 
1846
 
 
1847
    Example:
 
1848
 
 
1849
    \snippet code/src_corelib_io_qiodevice.cpp 5
 
1850
 
 
1851
    This function has no way of reporting errors; returning an empty
 
1852
    QByteArray can mean either that no data was currently available
 
1853
    for peeking, or that an error occurred.
 
1854
 
 
1855
    \sa read()
 
1856
*/
 
1857
QByteArray QIODevice::peek(qint64 maxSize)
 
1858
{
 
1859
    return d_func()->peek(maxSize);
 
1860
}
 
1861
 
 
1862
/*!
 
1863
    Blocks until new data is available for reading and the readyRead()
 
1864
    signal has been emitted, or until \a msecs milliseconds have
 
1865
    passed. If msecs is -1, this function will not time out.
 
1866
 
 
1867
    Returns \c true if new data is available for reading; otherwise returns
 
1868
    false (if the operation timed out or if an error occurred).
 
1869
 
 
1870
    This function can operate without an event loop. It is
 
1871
    useful when writing non-GUI applications and when performing
 
1872
    I/O operations in a non-GUI thread.
 
1873
 
 
1874
    If called from within a slot connected to the readyRead() signal,
 
1875
    readyRead() will not be reemitted.
 
1876
 
 
1877
    Reimplement this function to provide a blocking API for a custom
 
1878
    device. The default implementation does nothing, and returns \c false.
 
1879
 
 
1880
    \warning Calling this function from the main (GUI) thread
 
1881
    might cause your user interface to freeze.
 
1882
 
 
1883
    \sa waitForBytesWritten()
 
1884
*/
 
1885
bool QIODevice::waitForReadyRead(int msecs)
 
1886
{
 
1887
    Q_UNUSED(msecs);
 
1888
    return false;
 
1889
}
 
1890
 
 
1891
/*!
 
1892
    For buffered devices, this function waits until a payload of
 
1893
    buffered written data has been written to the device and the
 
1894
    bytesWritten() signal has been emitted, or until \a msecs
 
1895
    milliseconds have passed. If msecs is -1, this function will
 
1896
    not time out. For unbuffered devices, it returns immediately.
 
1897
 
 
1898
    Returns \c true if a payload of data was written to the device;
 
1899
    otherwise returns \c false (i.e. if the operation timed out, or if an
 
1900
    error occurred).
 
1901
 
 
1902
    This function can operate without an event loop. It is
 
1903
    useful when writing non-GUI applications and when performing
 
1904
    I/O operations in a non-GUI thread.
 
1905
 
 
1906
    If called from within a slot connected to the bytesWritten() signal,
 
1907
    bytesWritten() will not be reemitted.
 
1908
 
 
1909
    Reimplement this function to provide a blocking API for a custom
 
1910
    device. The default implementation does nothing, and returns \c false.
 
1911
 
 
1912
    \warning Calling this function from the main (GUI) thread
 
1913
    might cause your user interface to freeze.
 
1914
 
 
1915
    \sa waitForReadyRead()
 
1916
*/
 
1917
bool QIODevice::waitForBytesWritten(int msecs)
 
1918
{
 
1919
    Q_UNUSED(msecs);
 
1920
    return false;
 
1921
}
 
1922
 
 
1923
/*!
 
1924
    Sets the human readable description of the last device error that
 
1925
    occurred to \a str.
 
1926
 
 
1927
    \sa errorString()
 
1928
*/
 
1929
void QIODevice::setErrorString(const QString &str)
 
1930
{
 
1931
    d_func()->errorString = str;
 
1932
}
 
1933
 
 
1934
/*!
 
1935
    Returns a human-readable description of the last device error that
 
1936
    occurred.
 
1937
 
 
1938
    \sa setErrorString()
 
1939
*/
 
1940
QString QIODevice::errorString() const
 
1941
{
 
1942
    Q_D(const QIODevice);
 
1943
    if (d->errorString.isEmpty()) {
 
1944
#ifdef QT_NO_QOBJECT
 
1945
        return QLatin1String(QT_TRANSLATE_NOOP(QIODevice, "Unknown error"));
 
1946
#else
 
1947
        return tr("Unknown error");
 
1948
#endif
 
1949
    }
 
1950
    return d->errorString;
 
1951
}
 
1952
 
 
1953
/*!
 
1954
    \fn qint64 QIODevice::readData(char *data, qint64 maxSize)
 
1955
 
 
1956
    Reads up to \a maxSize bytes from the device into \a data, and
 
1957
    returns the number of bytes read or -1 if an error occurred.
 
1958
 
 
1959
    If there are no bytes to be read and there can never be more bytes
 
1960
    available (examples include socket closed, pipe closed, sub-process
 
1961
    finished), this function returns -1.
 
1962
 
 
1963
    This function is called by QIODevice. Reimplement this function
 
1964
    when creating a subclass of QIODevice.
 
1965
 
 
1966
    When reimplementing this function it is important that this function
 
1967
    reads all the required data before returning. This is required in order
 
1968
    for QDataStream to be able to operate on the class. QDataStream assumes
 
1969
    all the requested information was read and therefore does not retry reading
 
1970
    if there was a problem.
 
1971
 
 
1972
    This function might be called with a maxSize of 0, which can be used to
 
1973
    perform post-reading operations.
 
1974
 
 
1975
    \sa read(), readLine(), writeData()
 
1976
*/
 
1977
 
 
1978
/*!
 
1979
    \fn qint64 QIODevice::writeData(const char *data, qint64 maxSize)
 
1980
 
 
1981
    Writes up to \a maxSize bytes from \a data to the device. Returns
 
1982
    the number of bytes written, or -1 if an error occurred.
 
1983
 
 
1984
    This function is called by QIODevice. Reimplement this function
 
1985
    when creating a subclass of QIODevice.
 
1986
 
 
1987
    When reimplementing this function it is important that this function
 
1988
    writes all the data available before returning. This is required in order
 
1989
    for QDataStream to be able to operate on the class. QDataStream assumes
 
1990
    all the information was written and therefore does not retry writing if
 
1991
    there was a problem.
 
1992
 
 
1993
    \sa read(), write()
 
1994
*/
 
1995
 
 
1996
/*!
 
1997
  \internal
 
1998
  \fn int qt_subtract_from_timeout(int timeout, int elapsed)
 
1999
 
 
2000
  Reduces the \a timeout by \a elapsed, taking into account that -1 is a
 
2001
  special value for timeouts.
 
2002
*/
 
2003
 
 
2004
int qt_subtract_from_timeout(int timeout, int elapsed)
 
2005
{
 
2006
    if (timeout == -1)
 
2007
        return -1;
 
2008
 
 
2009
    timeout = timeout - elapsed;
 
2010
    return timeout < 0 ? 0 : timeout;
 
2011
}
 
2012
 
 
2013
 
 
2014
#if !defined(QT_NO_DEBUG_STREAM)
 
2015
QDebug operator<<(QDebug debug, QIODevice::OpenMode modes)
 
2016
{
 
2017
    debug << "OpenMode(";
 
2018
    QStringList modeList;
 
2019
    if (modes == QIODevice::NotOpen) {
 
2020
        modeList << QLatin1String("NotOpen");
 
2021
    } else {
 
2022
        if (modes & QIODevice::ReadOnly)
 
2023
            modeList << QLatin1String("ReadOnly");
 
2024
        if (modes & QIODevice::WriteOnly)
 
2025
            modeList << QLatin1String("WriteOnly");
 
2026
        if (modes & QIODevice::Append)
 
2027
            modeList << QLatin1String("Append");
 
2028
        if (modes & QIODevice::Truncate)
 
2029
            modeList << QLatin1String("Truncate");
 
2030
        if (modes & QIODevice::Text)
 
2031
            modeList << QLatin1String("Text");
 
2032
        if (modes & QIODevice::Unbuffered)
 
2033
            modeList << QLatin1String("Unbuffered");
 
2034
    }
 
2035
    std::sort(modeList.begin(), modeList.end());
 
2036
    debug << modeList.join(QLatin1Char('|'));
 
2037
    debug << ')';
 
2038
    return debug;
 
2039
}
 
2040
#endif
 
2041
 
 
2042
QT_END_NAMESPACE