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
56QT_BEGIN_NAMESPACE
57
58#ifdef QIODEVICE_DEBUG
59void 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
82void debugBinaryString(const char *data, qint64 maxlen)
83{
84 debugBinaryString(QByteArray(data, maxlen));
85}
86#endif
87
88#define Q_VOID
89
90static 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 */
158QIODevicePrivate::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(nullptr)
173#endif
174{
175}
176
177/*!
178 \internal
179 */
180QIODevicePrivate::~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 cannot 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, for file-system
316 subclasses (e.g. QFile), this mode implies Truncate unless
317 combined with ReadOnly, Append or NewOnly.
318 \value ReadWrite The device is open for reading and writing.
319 \value Append The device is opened in append mode so that all data is
320 written to the end of the file.
321 \value Truncate If possible, the device is truncated before it is opened.
322 All earlier contents of the device are lost.
323 \value Text When reading, the end-of-line terminators are
324 translated to '\\n'. When writing, the end-of-line
325 terminators are translated to the local encoding, for
326 example '\\r\\n' for Win32.
327 \value Unbuffered Any buffer in the device is bypassed.
328 \value NewOnly Fail if the file to be opened already exists. Create and
329 open the file only if it does not exist. There is a
330 guarantee from the operating system that you are the only
331 one creating and opening the file. Note that this mode
332 implies WriteOnly, and combining it with ReadWrite is
333 allowed. This flag currently only affects QFile. Other
334 classes might use this flag in the future, but until then
335 using this flag with any classes other than QFile may
336 result in undefined behavior. (since Qt 5.11)
337 \value ExistingOnly Fail if the file to be opened does not exist. This flag
338 must be specified alongside ReadOnly, WriteOnly, or
339 ReadWrite. Note that using this flag with ReadOnly alone
340 is redundant, as ReadOnly already fails when the file does
341 not exist. This flag currently only affects QFile. Other
342 classes might use this flag in the future, but until then
343 using this flag with any classes other than QFile may
344 result in undefined behavior. (since Qt 5.11)
345
346 Certain flags, such as \c Unbuffered and \c Truncate, are
347 meaningless when used with some subclasses. Some of these
348 restrictions are implied by the type of device that is represented
349 by a subclass. In other cases, the restriction may be due to the
350 implementation, or may be imposed by the underlying platform; for
351 example, QTcpSocket does not support \c Unbuffered mode, and
352 limitations in the native API prevent QFile from supporting \c
353 Unbuffered on Windows.
354*/
355
356/*! \fn QIODevice::bytesWritten(qint64 bytes)
357
358 This signal is emitted every time a payload of data has been
359 written to the device's current write channel. The \a bytes argument is
360 set to the number of bytes that were written in this payload.
361
362 bytesWritten() is not emitted recursively; if you reenter the event loop
363 or call waitForBytesWritten() inside a slot connected to the
364 bytesWritten() signal, the signal will not be reemitted (although
365 waitForBytesWritten() may still return true).
366
367 \sa readyRead()
368*/
369
370/*!
371 \fn QIODevice::channelBytesWritten(int channel, qint64 bytes)
372 \since 5.7
373
374 This signal is emitted every time a payload of data has been written to
375 the device. The \a bytes argument is set to the number of bytes that were
376 written in this payload, while \a channel is the channel they were written
377 to. Unlike bytesWritten(), it is emitted regardless of the
378 \l{currentWriteChannel()}{current write channel}.
379
380 channelBytesWritten() can be emitted recursively - even for the same
381 channel.
382
383 \sa bytesWritten(), channelReadyRead()
384*/
385
386/*!
387 \fn QIODevice::readyRead()
388
389 This signal is emitted once every time new data is available for
390 reading from the device's current read channel. It will only be emitted
391 again once new data is available, such as when a new payload of network
392 data has arrived on your network socket, or when a new block of data has
393 been appended to your device.
394
395 readyRead() is not emitted recursively; if you reenter the event loop or
396 call waitForReadyRead() inside a slot connected to the readyRead() signal,
397 the signal will not be reemitted (although waitForReadyRead() may still
398 return true).
399
400 Note for developers implementing classes derived from QIODevice:
401 you should always emit readyRead() when new data has arrived (do not
402 emit it only because there's data still to be read in your
403 buffers). Do not emit readyRead() in other conditions.
404
405 \sa bytesWritten()
406*/
407
408/*!
409 \fn QIODevice::channelReadyRead(int channel)
410 \since 5.7
411
412 This signal is emitted when new data is available for reading from the
413 device. The \a channel argument is set to the index of the read channel on
414 which the data has arrived. Unlike readyRead(), it is emitted regardless of
415 the \l{currentReadChannel()}{current read channel}.
416
417 channelReadyRead() can be emitted recursively - even for the same channel.
418
419 \sa readyRead(), channelBytesWritten()
420*/
421
422/*! \fn QIODevice::aboutToClose()
423
424 This signal is emitted when the device is about to close. Connect
425 this signal if you have operations that need to be performed
426 before the device closes (e.g., if you have data in a separate
427 buffer that needs to be written to the device).
428*/
429
430/*!
431 \fn QIODevice::readChannelFinished()
432 \since 4.4
433
434 This signal is emitted when the input (reading) stream is closed
435 in this device. It is emitted as soon as the closing is detected,
436 which means that there might still be data available for reading
437 with read().
438
439 \sa atEnd(), read()
440*/
441
442#ifdef QT_NO_QOBJECT
443QIODevice::QIODevice()
444 : d_ptr(new QIODevicePrivate)
445{
446 d_ptr->q_ptr = this;
447}
448
449/*!
450 \internal
451*/
452QIODevice::QIODevice(QIODevicePrivate &dd)
453 : d_ptr(&dd)
454{
455 d_ptr->q_ptr = this;
456}
457#else
458
459/*!
460 Constructs a QIODevice object.
461*/
462
463QIODevice::QIODevice()
464 : QObject(*new QIODevicePrivate, 0)
465{
466#if defined QIODEVICE_DEBUG
467 QFile *file = qobject_cast<QFile *>(this);
468 printf("%p QIODevice::QIODevice(\"%s\") %s\n", this, metaObject()->className(),
469 qPrintable(file ? file->fileName() : QString()));
470#endif
471}
472
473/*!
474 Constructs a QIODevice object with the given \a parent.
475*/
476
477QIODevice::QIODevice(QObject *parent)
478 : QObject(*new QIODevicePrivate, parent)
479{
480#if defined QIODEVICE_DEBUG
481 printf("%p QIODevice::QIODevice(%p \"%s\")\n", this, parent, metaObject()->className());
482#endif
483}
484
485/*!
486 \internal
487*/
488QIODevice::QIODevice(QIODevicePrivate &dd, QObject *parent)
489 : QObject(dd, parent)
490{
491}
492#endif
493
494
495/*!
496 The destructor is virtual, and QIODevice is an abstract base
497 class. This destructor does not call close(), but the subclass
498 destructor might. If you are in doubt, call close() before
499 destroying the QIODevice.
500*/
501QIODevice::~QIODevice()
502{
503#if defined QIODEVICE_DEBUG
504 printf("%p QIODevice::~QIODevice()\n", this);
505#endif
506}
507
508/*!
509 Returns \c true if this device is sequential; otherwise returns
510 false.
511
512 Sequential devices, as opposed to a random-access devices, have no
513 concept of a start, an end, a size, or a current position, and they
514 do not support seeking. You can only read from the device when it
515 reports that data is available. The most common example of a
516 sequential device is a network socket. On Unix, special files such
517 as /dev/zero and fifo pipes are sequential.
518
519 Regular files, on the other hand, do support random access. They
520 have both a size and a current position, and they also support
521 seeking backwards and forwards in the data stream. Regular files
522 are non-sequential.
523
524 \sa bytesAvailable()
525*/
526bool QIODevice::isSequential() const
527{
528 return false;
529}
530
531/*!
532 Returns the mode in which the device has been opened;
533 i.e. ReadOnly or WriteOnly.
534
535 \sa OpenMode
536*/
537QIODevice::OpenMode QIODevice::openMode() const
538{
539 return d_func()->openMode;
540}
541
542/*!
543 Sets the OpenMode of the device to \a openMode. Call this
544 function to set the open mode if the flags change after the device
545 has been opened.
546
547 \sa openMode(), OpenMode
548*/
549void QIODevice::setOpenMode(OpenMode openMode)
550{
551 Q_D(QIODevice);
552#if defined QIODEVICE_DEBUG
553 printf("%p QIODevice::setOpenMode(0x%x)\n", this, int(openMode));
554#endif
555 d->openMode = openMode;
556 d->accessMode = QIODevicePrivate::Unset;
557 d->setReadChannelCount(isReadable() ? qMax(d->readChannelCount, 1) : 0);
558 d->setWriteChannelCount(isWritable() ? qMax(d->writeChannelCount, 1) : 0);
559}
560
561/*!
562 If \a enabled is true, this function sets the \l Text flag on the device;
563 otherwise the \l Text flag is removed. This feature is useful for classes
564 that provide custom end-of-line handling on a QIODevice.
565
566 The IO device should be opened before calling this function.
567
568 \sa open(), setOpenMode()
569 */
570void QIODevice::setTextModeEnabled(bool enabled)
571{
572 Q_D(QIODevice);
573 if (!isOpen()) {
574 checkWarnMessage(this, "setTextModeEnabled", "The device is not open");
575 return;
576 }
577 if (enabled)
578 d->openMode |= Text;
579 else
580 d->openMode &= ~Text;
581}
582
583/*!
584 Returns \c true if the \l Text flag is enabled; otherwise returns \c false.
585
586 \sa setTextModeEnabled()
587*/
588bool QIODevice::isTextModeEnabled() const
589{
590 return d_func()->openMode & Text;
591}
592
593/*!
594 Returns \c true if the device is open; otherwise returns \c false. A
595 device is open if it can be read from and/or written to. By
596 default, this function returns \c false if openMode() returns
597 \c NotOpen.
598
599 \sa openMode(), OpenMode
600*/
601bool QIODevice::isOpen() const
602{
603 return d_func()->openMode != NotOpen;
604}
605
606/*!
607 Returns \c true if data can be read from the device; otherwise returns
608 false. Use bytesAvailable() to determine how many bytes can be read.
609
610 This is a convenience function which checks if the OpenMode of the
611 device contains the ReadOnly flag.
612
613 \sa openMode(), OpenMode
614*/
615bool QIODevice::isReadable() const
616{
617 return (openMode() & ReadOnly) != 0;
618}
619
620/*!
621 Returns \c true if data can be written to the device; otherwise returns
622 false.
623
624 This is a convenience function which checks if the OpenMode of the
625 device contains the WriteOnly flag.
626
627 \sa openMode(), OpenMode
628*/
629bool QIODevice::isWritable() const
630{
631 return (openMode() & WriteOnly) != 0;
632}
633
634/*!
635 \since 5.7
636
637 Returns the number of available read channels if the device is open;
638 otherwise returns 0.
639
640 \sa writeChannelCount(), QProcess
641*/
642int QIODevice::readChannelCount() const
643{
644 return d_func()->readChannelCount;
645}
646
647/*!
648 \since 5.7
649
650 Returns the number of available write channels if the device is open;
651 otherwise returns 0.
652
653 \sa readChannelCount()
654*/
655int QIODevice::writeChannelCount() const
656{
657 return d_func()->writeChannelCount;
658}
659
660/*!
661 \since 5.7
662
663 Returns the index of the current read channel.
664
665 \sa setCurrentReadChannel(), readChannelCount(), QProcess
666*/
667int QIODevice::currentReadChannel() const
668{
669 return d_func()->currentReadChannel;
670}
671
672/*!
673 \since 5.7
674
675 Sets the current read channel of the QIODevice to the given \a
676 channel. The current input channel is used by the functions
677 read(), readAll(), readLine(), and getChar(). It also determines
678 which channel triggers QIODevice to emit readyRead().
679
680 \sa currentReadChannel(), readChannelCount(), QProcess
681*/
682void QIODevice::setCurrentReadChannel(int channel)
683{
684 Q_D(QIODevice);
685
686 if (d->transactionStarted) {
687 checkWarnMessage(this, "setReadChannel", "Failed due to read transaction being in progress");
688 return;
689 }
690
691#if defined QIODEVICE_DEBUG
692 qDebug("%p QIODevice::setCurrentReadChannel(%d), d->currentReadChannel = %d, d->readChannelCount = %d\n",
693 this, channel, d->currentReadChannel, d->readChannelCount);
694#endif
695
696 d->setCurrentReadChannel(channel);
697}
698
699/*!
700 \internal
701*/
702void QIODevicePrivate::setReadChannelCount(int count)
703{
704 if (count > readBuffers.size()) {
705 readBuffers.insert(readBuffers.end(), count - readBuffers.size(),
706 QRingBuffer(readBufferChunkSize));
707 } else {
708 readBuffers.resize(count);
709 }
710 readChannelCount = count;
711 setCurrentReadChannel(currentReadChannel);
712}
713
714/*!
715 \since 5.7
716
717 Returns the the index of the current write channel.
718
719 \sa setCurrentWriteChannel(), writeChannelCount()
720*/
721int QIODevice::currentWriteChannel() const
722{
723 return d_func()->currentWriteChannel;
724}
725
726/*!
727 \since 5.7
728
729 Sets the current write channel of the QIODevice to the given \a
730 channel. The current output channel is used by the functions
731 write(), putChar(). It also determines which channel triggers
732 QIODevice to emit bytesWritten().
733
734 \sa currentWriteChannel(), writeChannelCount()
735*/
736void QIODevice::setCurrentWriteChannel(int channel)
737{
738 Q_D(QIODevice);
739
740#if defined QIODEVICE_DEBUG
741 qDebug("%p QIODevice::setCurrentWriteChannel(%d), d->currentWriteChannel = %d, d->writeChannelCount = %d\n",
742 this, channel, d->currentWriteChannel, d->writeChannelCount);
743#endif
744
745 d->setCurrentWriteChannel(channel);
746}
747
748/*!
749 \internal
750*/
751void QIODevicePrivate::setWriteChannelCount(int count)
752{
753 if (count > writeBuffers.size()) {
754 // If writeBufferChunkSize is zero (default value), we don't use
755 // QIODevice's write buffers.
756 if (writeBufferChunkSize != 0) {
757 writeBuffers.insert(writeBuffers.end(), count - writeBuffers.size(),
758 QRingBuffer(writeBufferChunkSize));
759 }
760 } else {
761 writeBuffers.resize(count);
762 }
763 writeChannelCount = count;
764 setCurrentWriteChannel(currentWriteChannel);
765}
766
767/*!
768 \internal
769*/
770bool QIODevicePrivate::allWriteBuffersEmpty() const
771{
772 for (const QRingBuffer &ringBuffer : writeBuffers) {
773 if (!ringBuffer.isEmpty())
774 return false;
775 }
776 return true;
777}
778
779/*!
780 Opens the device and sets its OpenMode to \a mode. Returns \c true if successful;
781 otherwise returns \c false. This function should be called from any
782 reimplementations of open() or other functions that open the device.
783
784 \sa openMode(), OpenMode
785*/
786bool QIODevice::open(OpenMode mode)
787{
788 Q_D(QIODevice);
789 d->openMode = mode;
790 d->pos = (mode & Append) ? size() : qint64(0);
791 d->accessMode = QIODevicePrivate::Unset;
792 d->readBuffers.clear();
793 d->writeBuffers.clear();
794 d->setReadChannelCount(isReadable() ? 1 : 0);
795 d->setWriteChannelCount(isWritable() ? 1 : 0);
796 d->errorString.clear();
797#if defined QIODEVICE_DEBUG
798 printf("%p QIODevice::open(0x%x)\n", this, quint32(mode));
799#endif
800 return true;
801}
802
803/*!
804 First emits aboutToClose(), then closes the device and sets its
805 OpenMode to NotOpen. The error string is also reset.
806
807 \sa setOpenMode(), OpenMode
808*/
809void QIODevice::close()
810{
811 Q_D(QIODevice);
812 if (d->openMode == NotOpen)
813 return;
814
815#if defined QIODEVICE_DEBUG
816 printf("%p QIODevice::close()\n", this);
817#endif
818
819#ifndef QT_NO_QOBJECT
820 emit aboutToClose();
821#endif
822 d->openMode = NotOpen;
823 d->pos = 0;
824 d->transactionStarted = false;
825 d->transactionPos = 0;
826 d->setReadChannelCount(0);
827 // Do not clear write buffers to allow delayed close in sockets
828 d->writeChannelCount = 0;
829}
830
831/*!
832 For random-access devices, this function returns the position that
833 data is written to or read from. For sequential devices or closed
834 devices, where there is no concept of a "current position", 0 is
835 returned.
836
837 The current read/write position of the device is maintained internally by
838 QIODevice, so reimplementing this function is not necessary. When
839 subclassing QIODevice, use QIODevice::seek() to notify QIODevice about
840 changes in the device position.
841
842 \sa isSequential(), seek()
843*/
844qint64 QIODevice::pos() const
845{
846 Q_D(const QIODevice);
847#if defined QIODEVICE_DEBUG
848 printf("%p QIODevice::pos() == %lld\n", this, d->pos);
849#endif
850 return d->pos;
851}
852
853/*!
854 For open random-access devices, this function returns the size of the
855 device. For open sequential devices, bytesAvailable() is returned.
856
857 If the device is closed, the size returned will not reflect the actual
858 size of the device.
859
860 \sa isSequential(), pos()
861*/
862qint64 QIODevice::size() const
863{
864 return d_func()->isSequential() ? bytesAvailable() : qint64(0);
865}
866
867/*!
868 For random-access devices, this function sets the current position
869 to \a pos, returning true on success, or false if an error occurred.
870 For sequential devices, the default behavior is to produce a warning
871 and return false.
872
873 When subclassing QIODevice, you must call QIODevice::seek() at the
874 start of your function to ensure integrity with QIODevice's
875 built-in buffer.
876
877 \sa pos(), isSequential()
878*/
879bool QIODevice::seek(qint64 pos)
880{
881 Q_D(QIODevice);
882 if (d->isSequential()) {
883 checkWarnMessage(this, "seek", "Cannot call seek on a sequential device");
884 return false;
885 }
886 if (d->openMode == NotOpen) {
887 checkWarnMessage(this, "seek", "The device is not open");
888 return false;
889 }
890 if (pos < 0) {
891 qWarning("QIODevice::seek: Invalid pos: %lld", pos);
892 return false;
893 }
894
895#if defined QIODEVICE_DEBUG
896 printf("%p QIODevice::seek(%lld), before: d->pos = %lld, d->buffer.size() = %lld\n",
897 this, pos, d->pos, d->buffer.size());
898#endif
899
900 d->devicePos = pos;
901 d->seekBuffer(pos);
902
903#if defined QIODEVICE_DEBUG
904 printf("%p \tafter: d->pos == %lld, d->buffer.size() == %lld\n", this, d->pos,
905 d->buffer.size());
906#endif
907 return true;
908}
909
910/*!
911 \internal
912*/
913void QIODevicePrivate::seekBuffer(qint64 newPos)
914{
915 const qint64 offset = newPos - pos;
916 pos = newPos;
917
918 if (offset < 0 || offset >= buffer.size()) {
919 // When seeking backwards, an operation that is only allowed for
920 // random-access devices, the buffer is cleared. The next read
921 // operation will then refill the buffer.
922 buffer.clear();
923 } else {
924 buffer.free(offset);
925 }
926}
927
928/*!
929 Returns \c true if the current read and write position is at the end
930 of the device (i.e. there is no more data available for reading on
931 the device); otherwise returns \c false.
932
933 For some devices, atEnd() can return true even though there is more data
934 to read. This special case only applies to devices that generate data in
935 direct response to you calling read() (e.g., \c /dev or \c /proc files on
936 Unix and \macos, or console input / \c stdin on all platforms).
937
938 \sa bytesAvailable(), read(), isSequential()
939*/
940bool QIODevice::atEnd() const
941{
942 Q_D(const QIODevice);
943 const bool result = (d->openMode == NotOpen || (d->isBufferEmpty()
944 && bytesAvailable() == 0));
945#if defined QIODEVICE_DEBUG
946 printf("%p QIODevice::atEnd() returns %s, d->openMode == %d, d->pos == %lld\n", this,
947 result ? "true" : "false", int(d->openMode), d->pos);
948#endif
949 return result;
950}
951
952/*!
953 Seeks to the start of input for random-access devices. Returns
954 true on success; otherwise returns \c false (for example, if the
955 device is not open).
956
957 Note that when using a QTextStream on a QFile, calling reset() on
958 the QFile will not have the expected result because QTextStream
959 buffers the file. Use the QTextStream::seek() function instead.
960
961 \sa seek()
962*/
963bool QIODevice::reset()
964{
965#if defined QIODEVICE_DEBUG
966 printf("%p QIODevice::reset()\n", this);
967#endif
968 return seek(0);
969}
970
971/*!
972 Returns the number of bytes that are available for reading. This
973 function is commonly used with sequential devices to determine the
974 number of bytes to allocate in a buffer before reading.
975
976 Subclasses that reimplement this function must call the base
977 implementation in order to include the size of the buffer of QIODevice. Example:
978
979 \snippet code/src_corelib_io_qiodevice.cpp 1
980
981 \sa bytesToWrite(), readyRead(), isSequential()
982*/
983qint64 QIODevice::bytesAvailable() const
984{
985 Q_D(const QIODevice);
986 if (!d->isSequential())
987 return qMax(size() - d->pos, qint64(0));
988 return d->buffer.size() - d->transactionPos;
989}
990
991/*! For buffered devices, this function returns the number of bytes
992 waiting to be written. For devices with no buffer, this function
993 returns 0.
994
995 Subclasses that reimplement this function must call the base
996 implementation in order to include the size of the buffer of QIODevice.
997
998 \sa bytesAvailable(), bytesWritten(), isSequential()
999*/
1000qint64 QIODevice::bytesToWrite() const
1001{
1002 return d_func()->writeBuffer.size();
1003}
1004
1005/*!
1006 Reads at most \a maxSize bytes from the device into \a data, and
1007 returns the number of bytes read. If an error occurs, such as when
1008 attempting to read from a device opened in WriteOnly mode, this
1009 function returns -1.
1010
1011 0 is returned when no more data is available for reading. However,
1012 reading past the end of the stream is considered an error, so this
1013 function returns -1 in those cases (that is, reading on a closed
1014 socket or after a process has died).
1015
1016 \sa readData(), readLine(), write()
1017*/
1018qint64 QIODevice::read(char *data, qint64 maxSize)
1019{
1020 Q_D(QIODevice);
1021
1022#if defined QIODEVICE_DEBUG
1023 printf("%p QIODevice::read(%p, %lld), d->pos = %lld, d->buffer.size() = %lld\n",
1024 this, data, maxSize, d->pos, d->buffer.size());
1025#endif
1026
1027 const bool sequential = d->isSequential();
1028
1029 // Short-cut for getChar(), unless we need to keep the data in the buffer.
1030 if (maxSize == 1 && !(sequential && d->transactionStarted)) {
1031 int chint;
1032 while ((chint = d->buffer.getChar()) != -1) {
1033 if (!sequential)
1034 ++d->pos;
1035
1036 char c = char(uchar(chint));
1037 if (c == '\r' && (d->openMode & Text))
1038 continue;
1039 *data = c;
1040#if defined QIODEVICE_DEBUG
1041 printf("%p \tread 0x%hhx (%c) returning 1 (shortcut)\n", this,
1042 int(c), isprint(c) ? c : '?');
1043#endif
1044 if (d->buffer.isEmpty())
1045 readData(data, 0);
1046 return qint64(1);
1047 }
1048 }
1049
1050 CHECK_MAXLEN(read, qint64(-1));
1051 CHECK_READABLE(read, qint64(-1));
1052
1053 const qint64 readBytes = d->read(data, maxSize);
1054
1055#if defined QIODEVICE_DEBUG
1056 printf("%p \treturning %lld, d->pos == %lld, d->buffer.size() == %lld\n", this,
1057 readBytes, d->pos, d->buffer.size());
1058 if (readBytes > 0)
1059 debugBinaryString(data - readBytes, readBytes);
1060#endif
1061
1062 return readBytes;
1063}
1064
1065/*!
1066 \internal
1067*/
1068qint64 QIODevicePrivate::read(char *data, qint64 maxSize, bool peeking)
1069{
1070 Q_Q(QIODevice);
1071
1072 const bool buffered = (openMode & QIODevice::Unbuffered) == 0;
1073 const bool sequential = isSequential();
1074 const bool keepDataInBuffer = sequential
1075 ? peeking || transactionStarted
1076 : peeking && buffered;
1077 const qint64 savedPos = pos;
1078 qint64 readSoFar = 0;
1079 bool madeBufferReadsOnly = true;
1080 bool deviceAtEof = false;
1081 char *readPtr = data;
1082 qint64 bufferPos = (sequential && transactionStarted) ? transactionPos : Q_INT64_C(0);
1083 forever {
1084 // Try reading from the buffer.
1085 qint64 bufferReadChunkSize = keepDataInBuffer
1086 ? buffer.peek(data, maxSize, bufferPos)
1087 : buffer.read(data, maxSize);
1088 if (bufferReadChunkSize > 0) {
1089 bufferPos += bufferReadChunkSize;
1090 if (!sequential)
1091 pos += bufferReadChunkSize;
1092#if defined QIODEVICE_DEBUG
1093 printf("%p \treading %lld bytes from buffer into position %lld\n", q,
1094 bufferReadChunkSize, readSoFar);
1095#endif
1096 readSoFar += bufferReadChunkSize;
1097 data += bufferReadChunkSize;
1098 maxSize -= bufferReadChunkSize;
1099 }
1100
1101 if (maxSize > 0 && !deviceAtEof) {
1102 qint64 readFromDevice = 0;
1103 // Make sure the device is positioned correctly.
1104 if (sequential || pos == devicePos || q->seek(pos)) {
1105 madeBufferReadsOnly = false; // fix readData attempt
1106 if ((!buffered || maxSize >= readBufferChunkSize) && !keepDataInBuffer) {
1107 // Read big chunk directly to output buffer
1108 readFromDevice = q->readData(data, maxSize);
1109 deviceAtEof = (readFromDevice != maxSize);
1110#if defined QIODEVICE_DEBUG
1111 printf("%p \treading %lld bytes from device (total %lld)\n", q,
1112 readFromDevice, readSoFar);
1113#endif
1114 if (readFromDevice > 0) {
1115 readSoFar += readFromDevice;
1116 data += readFromDevice;
1117 maxSize -= readFromDevice;
1118 if (!sequential) {
1119 pos += readFromDevice;
1120 devicePos += readFromDevice;
1121 }
1122 }
1123 } else {
1124 // Do not read more than maxSize on unbuffered devices
1125 const qint64 bytesToBuffer = (buffered || readBufferChunkSize < maxSize)
1126 ? qint64(readBufferChunkSize)
1127 : maxSize;
1128 // Try to fill QIODevice buffer by single read
1129 readFromDevice = q->readData(buffer.reserve(bytesToBuffer), bytesToBuffer);
1130 deviceAtEof = (readFromDevice != bytesToBuffer);
1131 buffer.chop(bytesToBuffer - qMax(Q_INT64_C(0), readFromDevice));
1132 if (readFromDevice > 0) {
1133 if (!sequential)
1134 devicePos += readFromDevice;
1135#if defined QIODEVICE_DEBUG
1136 printf("%p \treading %lld from device into buffer\n", q,
1137 readFromDevice);
1138#endif
1139 continue;
1140 }
1141 }
1142 } else {
1143 readFromDevice = -1;
1144 }
1145
1146 if (readFromDevice < 0 && readSoFar == 0) {
1147 // error and we haven't read anything: return immediately
1148 return qint64(-1);
1149 }
1150 }
1151
1152 if ((openMode & QIODevice::Text) && readPtr < data) {
1153 const char *endPtr = data;
1154
1155 // optimization to avoid initial self-assignment
1156 while (*readPtr != '\r') {
1157 if (++readPtr == endPtr)
1158 break;
1159 }
1160
1161 char *writePtr = readPtr;
1162
1163 while (readPtr < endPtr) {
1164 char ch = *readPtr++;
1165 if (ch != '\r')
1166 *writePtr++ = ch;
1167 else {
1168 --readSoFar;
1169 --data;
1170 ++maxSize;
1171 }
1172 }
1173
1174 // Make sure we get more data if there is room for more. This
1175 // is very important for when someone seeks to the start of a
1176 // '\r\n' and reads one character - they should get the '\n'.
1177 readPtr = data;
1178 continue;
1179 }
1180
1181 break;
1182 }
1183
1184 // Restore positions after reading
1185 if (keepDataInBuffer) {
1186 if (peeking)
1187 pos = savedPos; // does nothing on sequential devices
1188 else
1189 transactionPos = bufferPos;
1190 } else if (peeking) {
1191 seekBuffer(savedPos); // unbuffered random-access device
1192 }
1193
1194 if (madeBufferReadsOnly && isBufferEmpty())
1195 q->readData(data, 0);
1196
1197 return readSoFar;
1198}
1199
1200/*!
1201 \overload
1202
1203 Reads at most \a maxSize bytes from the device, and returns the
1204 data read as a QByteArray.
1205
1206 This function has no way of reporting errors; returning an empty
1207 QByteArray can mean either that no data was currently available
1208 for reading, or that an error occurred.
1209*/
1210
1211QByteArray QIODevice::read(qint64 maxSize)
1212{
1213 Q_D(QIODevice);
1214 QByteArray result;
1215
1216#if defined QIODEVICE_DEBUG
1217 printf("%p QIODevice::read(%lld), d->pos = %lld, d->buffer.size() = %lld\n",
1218 this, maxSize, d->pos, d->buffer.size());
1219#endif
1220
1221 // Try to prevent the data from being copied, if we have a chunk
1222 // with the same size in the read buffer.
1223 if (maxSize == d->buffer.nextDataBlockSize() && !d->transactionStarted
1224 && (d->openMode & (QIODevice::ReadOnly | QIODevice::Text)) == QIODevice::ReadOnly) {
1225 result = d->buffer.read();
1226 if (!d->isSequential())
1227 d->pos += maxSize;
1228 if (d->buffer.isEmpty())
1229 readData(nullptr, 0);
1230 return result;
1231 }
1232
1233 CHECK_MAXLEN(read, result);
1234 CHECK_MAXBYTEARRAYSIZE(read);
1235
1236 result.resize(int(maxSize));
1237 qint64 readBytes = read(result.data(), result.size());
1238
1239 if (readBytes <= 0)
1240 result.clear();
1241 else
1242 result.resize(int(readBytes));
1243
1244 return result;
1245}
1246
1247/*!
1248 Reads all remaining data from the device, and returns it as a
1249 byte array.
1250
1251 This function has no way of reporting errors; returning an empty
1252 QByteArray can mean either that no data was currently available
1253 for reading, or that an error occurred.
1254*/
1255QByteArray QIODevice::readAll()
1256{
1257 Q_D(QIODevice);
1258#if defined QIODEVICE_DEBUG
1259 printf("%p QIODevice::readAll(), d->pos = %lld, d->buffer.size() = %lld\n",
1260 this, d->pos, d->buffer.size());
1261#endif
1262
1263 QByteArray result;
1264 qint64 readBytes = (d->isSequential() ? Q_INT64_C(0) : size());
1265 if (readBytes == 0) {
1266 // Size is unknown, read incrementally.
1267 qint64 readChunkSize = qMax(qint64(d->readBufferChunkSize),
1268 d->isSequential() ? (d->buffer.size() - d->transactionPos)
1269 : d->buffer.size());
1270 qint64 readResult;
1271 do {
1272 if (readBytes + readChunkSize >= MaxByteArraySize) {
1273 // If resize would fail, don't read more, return what we have.
1274 break;
1275 }
1276 result.resize(readBytes + readChunkSize);
1277 readResult = read(result.data() + readBytes, readChunkSize);
1278 if (readResult > 0 || readBytes == 0) {
1279 readBytes += readResult;
1280 readChunkSize = d->readBufferChunkSize;
1281 }
1282 } while (readResult > 0);
1283 } else {
1284 // Read it all in one go.
1285 // If resize fails, don't read anything.
1286 readBytes -= d->pos;
1287 if (readBytes >= MaxByteArraySize)
1288 return QByteArray();
1289 result.resize(readBytes);
1290 readBytes = read(result.data(), readBytes);
1291 }
1292
1293 if (readBytes <= 0)
1294 result.clear();
1295 else
1296 result.resize(int(readBytes));
1297
1298 return result;
1299}
1300
1301/*!
1302 This function reads a line of ASCII characters from the device, up
1303 to a maximum of \a maxSize - 1 bytes, stores the characters in \a
1304 data, and returns the number of bytes read. If a line could not be
1305 read but no error ocurred, this function returns 0. If an error
1306 occurs, this function returns the length of what could be read, or
1307 -1 if nothing was read.
1308
1309 A terminating '\\0' byte is always appended to \a data, so \a
1310 maxSize must be larger than 1.
1311
1312 Data is read until either of the following conditions are met:
1313
1314 \list
1315 \li The first '\\n' character is read.
1316 \li \a maxSize - 1 bytes are read.
1317 \li The end of the device data is detected.
1318 \endlist
1319
1320 For example, the following code reads a line of characters from a
1321 file:
1322
1323 \snippet code/src_corelib_io_qiodevice.cpp 2
1324
1325 The newline character ('\\n') is included in the buffer. If a
1326 newline is not encountered before maxSize - 1 bytes are read, a
1327 newline will not be inserted into the buffer. On windows newline
1328 characters are replaced with '\\n'.
1329
1330 This function calls readLineData(), which is implemented using
1331 repeated calls to getChar(). You can provide a more efficient
1332 implementation by reimplementing readLineData() in your own
1333 subclass.
1334
1335 \sa getChar(), read(), write()
1336*/
1337qint64 QIODevice::readLine(char *data, qint64 maxSize)
1338{
1339 Q_D(QIODevice);
1340 if (maxSize < 2) {
1341 checkWarnMessage(this, "readLine", "Called with maxSize < 2");
1342 return qint64(-1);
1343 }
1344
1345#if defined QIODEVICE_DEBUG
1346 printf("%p QIODevice::readLine(%p, %lld), d->pos = %lld, d->buffer.size() = %lld\n",
1347 this, data, maxSize, d->pos, d->buffer.size());
1348#endif
1349
1350 // Leave room for a '\0'
1351 --maxSize;
1352
1353 const bool sequential = d->isSequential();
1354 const bool keepDataInBuffer = sequential && d->transactionStarted;
1355
1356 qint64 readSoFar = 0;
1357 if (keepDataInBuffer) {
1358 if (d->transactionPos < d->buffer.size()) {
1359 // Peek line from the specified position
1360 const qint64 i = d->buffer.indexOf('\n', maxSize, d->transactionPos);
1361 readSoFar = d->buffer.peek(data, i >= 0 ? (i - d->transactionPos + 1) : maxSize,
1362 d->transactionPos);
1363 d->transactionPos += readSoFar;
1364 if (d->transactionPos == d->buffer.size())
1365 readData(data, 0);
1366 }
1367 } else if (!d->buffer.isEmpty()) {
1368 // QRingBuffer::readLine() terminates the line with '\0'
1369 readSoFar = d->buffer.readLine(data, maxSize + 1);
1370 if (d->buffer.isEmpty())
1371 readData(data,0);
1372 if (!sequential)
1373 d->pos += readSoFar;
1374 }
1375
1376 if (readSoFar) {
1377#if defined QIODEVICE_DEBUG
1378 printf("%p \tread from buffer: %lld bytes, last character read: %hhx\n", this,
1379 readSoFar, data[readSoFar - 1]);
1380 debugBinaryString(data, int(readSoFar));
1381#endif
1382 if (data[readSoFar - 1] == '\n') {
1383 if (d->openMode & Text) {
1384 // QRingBuffer::readLine() isn't Text aware.
1385 if (readSoFar > 1 && data[readSoFar - 2] == '\r') {
1386 --readSoFar;
1387 data[readSoFar - 1] = '\n';
1388 }
1389 }
1390 data[readSoFar] = '\0';
1391 return readSoFar;
1392 }
1393 }
1394
1395 if (d->pos != d->devicePos && !sequential && !seek(d->pos))
1396 return qint64(-1);
1397 d->baseReadLineDataCalled = false;
1398 // Force base implementation for transaction on sequential device
1399 // as it stores the data in internal buffer automatically.
1400 qint64 readBytes = keepDataInBuffer
1401 ? QIODevice::readLineData(data + readSoFar, maxSize - readSoFar)
1402 : readLineData(data + readSoFar, maxSize - readSoFar);
1403#if defined QIODEVICE_DEBUG
1404 printf("%p \tread from readLineData: %lld bytes, readSoFar = %lld bytes\n", this,
1405 readBytes, readSoFar);
1406 if (readBytes > 0) {
1407 debugBinaryString(data, int(readSoFar + readBytes));
1408 }
1409#endif
1410 if (readBytes < 0) {
1411 data[readSoFar] = '\0';
1412 return readSoFar ? readSoFar : -1;
1413 }
1414 readSoFar += readBytes;
1415 if (!d->baseReadLineDataCalled && !sequential) {
1416 d->pos += readBytes;
1417 // If the base implementation was not called, then we must
1418 // assume the device position is invalid and force a seek.
1419 d->devicePos = qint64(-1);
1420 }
1421 data[readSoFar] = '\0';
1422
1423 if (d->openMode & Text) {
1424 if (readSoFar > 1 && data[readSoFar - 1] == '\n' && data[readSoFar - 2] == '\r') {
1425 data[readSoFar - 2] = '\n';
1426 data[readSoFar - 1] = '\0';
1427 --readSoFar;
1428 }
1429 }
1430
1431#if defined QIODEVICE_DEBUG
1432 printf("%p \treturning %lld, d->pos = %lld, d->buffer.size() = %lld, size() = %lld\n",
1433 this, readSoFar, d->pos, d->buffer.size(), size());
1434 debugBinaryString(data, int(readSoFar));
1435#endif
1436 return readSoFar;
1437}
1438
1439/*!
1440 \overload
1441
1442 Reads a line from the device, but no more than \a maxSize characters,
1443 and returns the result as a byte array.
1444
1445 This function has no way of reporting errors; returning an empty
1446 QByteArray can mean either that no data was currently available
1447 for reading, or that an error occurred.
1448*/
1449QByteArray QIODevice::readLine(qint64 maxSize)
1450{
1451 Q_D(QIODevice);
1452 QByteArray result;
1453
1454 CHECK_MAXLEN(readLine, result);
1455 CHECK_MAXBYTEARRAYSIZE(readLine);
1456
1457#if defined QIODEVICE_DEBUG
1458 printf("%p QIODevice::readLine(%lld), d->pos = %lld, d->buffer.size() = %lld\n",
1459 this, maxSize, d->pos, d->buffer.size());
1460#endif
1461
1462 result.resize(int(maxSize));
1463 qint64 readBytes = 0;
1464 if (!result.size()) {
1465 // If resize fails or maxSize == 0, read incrementally
1466 if (maxSize == 0)
1467 maxSize = MaxByteArraySize - 1;
1468
1469 // The first iteration needs to leave an extra byte for the terminating null
1470 result.resize(1);
1471
1472 qint64 readResult;
1473 do {
1474 result.resize(int(qMin(maxSize, qint64(result.size() + d->readBufferChunkSize))));
1475 readResult = readLine(result.data() + readBytes, result.size() - readBytes);
1476 if (readResult > 0 || readBytes == 0)
1477 readBytes += readResult;
1478 } while (readResult == d->readBufferChunkSize
1479 && result[int(readBytes - 1)] != '\n');
1480 } else
1481 readBytes = readLine(result.data(), result.size());
1482
1483 if (readBytes <= 0)
1484 result.clear();
1485 else
1486 result.resize(readBytes);
1487
1488 return result;
1489}
1490
1491/*!
1492 Reads up to \a maxSize characters into \a data and returns the
1493 number of characters read.
1494
1495 This function is called by readLine(), and provides its base
1496 implementation, using getChar(). Buffered devices can improve the
1497 performance of readLine() by reimplementing this function.
1498
1499 readLine() appends a '\\0' byte to \a data; readLineData() does not
1500 need to do this.
1501
1502 If you reimplement this function, be careful to return the correct
1503 value: it should return the number of bytes read in this line,
1504 including the terminating newline, or 0 if there is no line to be
1505 read at this point. If an error occurs, it should return -1 if and
1506 only if no bytes were read. Reading past EOF is considered an error.
1507*/
1508qint64 QIODevice::readLineData(char *data, qint64 maxSize)
1509{
1510 Q_D(QIODevice);
1511 qint64 readSoFar = 0;
1512 char c;
1513 int lastReadReturn = 0;
1514 d->baseReadLineDataCalled = true;
1515
1516 while (readSoFar < maxSize && (lastReadReturn = read(&c, 1)) == 1) {
1517 *data++ = c;
1518 ++readSoFar;
1519 if (c == '\n')
1520 break;
1521 }
1522
1523#if defined QIODEVICE_DEBUG
1524 printf("%p QIODevice::readLineData(%p, %lld), d->pos = %lld, d->buffer.size() = %lld, "
1525 "returns %lld\n", this, data, maxSize, d->pos, d->buffer.size(), readSoFar);
1526#endif
1527 if (lastReadReturn != 1 && readSoFar == 0)
1528 return isSequential() ? lastReadReturn : -1;
1529 return readSoFar;
1530}
1531
1532/*!
1533 Returns \c true if a complete line of data can be read from the device;
1534 otherwise returns \c false.
1535
1536 Note that unbuffered devices, which have no way of determining what
1537 can be read, always return false.
1538
1539 This function is often called in conjunction with the readyRead()
1540 signal.
1541
1542 Subclasses that reimplement this function must call the base
1543 implementation in order to include the contents of the QIODevice's buffer. Example:
1544
1545 \snippet code/src_corelib_io_qiodevice.cpp 3
1546
1547 \sa readyRead(), readLine()
1548*/
1549bool QIODevice::canReadLine() const
1550{
1551 Q_D(const QIODevice);
1552 return d->buffer.indexOf('\n', d->buffer.size(),
1553 d->isSequential() ? d->transactionPos : Q_INT64_C(0)) >= 0;
1554}
1555
1556/*!
1557 \since 5.7
1558
1559 Starts a new read transaction on the device.
1560
1561 Defines a restorable point within the sequence of read operations. For
1562 sequential devices, read data will be duplicated internally to allow
1563 recovery in case of incomplete reads. For random-access devices,
1564 this function saves the current position. Call commitTransaction() or
1565 rollbackTransaction() to finish the transaction.
1566
1567 \note Nesting transactions is not supported.
1568
1569 \sa commitTransaction(), rollbackTransaction()
1570*/
1571void QIODevice::startTransaction()
1572{
1573 Q_D(QIODevice);
1574 if (d->transactionStarted) {
1575 checkWarnMessage(this, "startTransaction", "Called while transaction already in progress");
1576 return;
1577 }
1578 d->transactionPos = d->pos;
1579 d->transactionStarted = true;
1580}
1581
1582/*!
1583 \since 5.7
1584
1585 Completes a read transaction.
1586
1587 For sequential devices, all data recorded in the internal buffer during
1588 the transaction will be discarded.
1589
1590 \sa startTransaction(), rollbackTransaction()
1591*/
1592void QIODevice::commitTransaction()
1593{
1594 Q_D(QIODevice);
1595 if (!d->transactionStarted) {
1596 checkWarnMessage(this, "commitTransaction", "Called while no transaction in progress");
1597 return;
1598 }
1599 if (d->isSequential())
1600 d->buffer.free(d->transactionPos);
1601 d->transactionStarted = false;
1602 d->transactionPos = 0;
1603}
1604
1605/*!
1606 \since 5.7
1607
1608 Rolls back a read transaction.
1609
1610 Restores the input stream to the point of the startTransaction() call.
1611 This function is commonly used to rollback the transaction when an
1612 incomplete read was detected prior to committing the transaction.
1613
1614 \sa startTransaction(), commitTransaction()
1615*/
1616void QIODevice::rollbackTransaction()
1617{
1618 Q_D(QIODevice);
1619 if (!d->transactionStarted) {
1620 checkWarnMessage(this, "rollbackTransaction", "Called while no transaction in progress");
1621 return;
1622 }
1623 if (!d->isSequential())
1624 d->seekBuffer(d->transactionPos);
1625 d->transactionStarted = false;
1626 d->transactionPos = 0;
1627}
1628
1629/*!
1630 \since 5.7
1631
1632 Returns \c true if a transaction is in progress on the device, otherwise
1633 \c false.
1634
1635 \sa startTransaction()
1636*/
1637bool QIODevice::isTransactionStarted() const
1638{
1639 return d_func()->transactionStarted;
1640}
1641
1642/*!
1643 Writes at most \a maxSize bytes of data from \a data to the
1644 device. Returns the number of bytes that were actually written, or
1645 -1 if an error occurred.
1646
1647 \sa read(), writeData()
1648*/
1649qint64 QIODevice::write(const char *data, qint64 maxSize)
1650{
1651 Q_D(QIODevice);
1652 CHECK_WRITABLE(write, qint64(-1));
1653 CHECK_MAXLEN(write, qint64(-1));
1654
1655 const bool sequential = d->isSequential();
1656 // Make sure the device is positioned correctly.
1657 if (d->pos != d->devicePos && !sequential && !seek(d->pos))
1658 return qint64(-1);
1659
1660#ifdef Q_OS_WIN
1661 if (d->openMode & Text) {
1662 const char *endOfData = data + maxSize;
1663 const char *startOfBlock = data;
1664
1665 qint64 writtenSoFar = 0;
1666 const qint64 savedPos = d->pos;
1667
1668 forever {
1669 const char *endOfBlock = startOfBlock;
1670 while (endOfBlock < endOfData && *endOfBlock != '\n')
1671 ++endOfBlock;
1672
1673 qint64 blockSize = endOfBlock - startOfBlock;
1674 if (blockSize > 0) {
1675 qint64 ret = writeData(startOfBlock, blockSize);
1676 if (ret <= 0) {
1677 if (writtenSoFar && !sequential)
1678 d->buffer.skip(d->pos - savedPos);
1679 return writtenSoFar ? writtenSoFar : ret;
1680 }
1681 if (!sequential) {
1682 d->pos += ret;
1683 d->devicePos += ret;
1684 }
1685 writtenSoFar += ret;
1686 }
1687
1688 if (endOfBlock == endOfData)
1689 break;
1690
1691 qint64 ret = writeData("\r\n", 2);
1692 if (ret <= 0) {
1693 if (writtenSoFar && !sequential)
1694 d->buffer.skip(d->pos - savedPos);
1695 return writtenSoFar ? writtenSoFar : ret;
1696 }
1697 if (!sequential) {
1698 d->pos += ret;
1699 d->devicePos += ret;
1700 }
1701 ++writtenSoFar;
1702
1703 startOfBlock = endOfBlock + 1;
1704 }
1705
1706 if (writtenSoFar && !sequential)
1707 d->buffer.skip(d->pos - savedPos);
1708 return writtenSoFar;
1709 }
1710#endif
1711
1712 qint64 written = writeData(data, maxSize);
1713 if (!sequential && written > 0) {
1714 d->pos += written;
1715 d->devicePos += written;
1716 d->buffer.skip(written);
1717 }
1718 return written;
1719}
1720
1721/*!
1722 \since 4.5
1723
1724 \overload
1725
1726 Writes data from a zero-terminated string of 8-bit characters to the
1727 device. Returns the number of bytes that were actually written, or
1728 -1 if an error occurred. This is equivalent to
1729 \code
1730 ...
1731 QIODevice::write(data, qstrlen(data));
1732 ...
1733 \endcode
1734
1735 \sa read(), writeData()
1736*/
1737qint64 QIODevice::write(const char *data)
1738{
1739 return write(data, qstrlen(data));
1740}
1741
1742/*! \fn qint64 QIODevice::write(const QByteArray &byteArray)
1743
1744 \overload
1745
1746 Writes the content of \a byteArray to the device. Returns the number of
1747 bytes that were actually written, or -1 if an error occurred.
1748
1749 \sa read(), writeData()
1750*/
1751
1752/*!
1753 Puts the character \a c back into the device, and decrements the
1754 current position unless the position is 0. This function is
1755 usually called to "undo" a getChar() operation, such as when
1756 writing a backtracking parser.
1757
1758 If \a c was not previously read from the device, the behavior is
1759 undefined.
1760
1761 \note This function is not available while a transaction is in progress.
1762*/
1763void QIODevice::ungetChar(char c)
1764{
1765 Q_D(QIODevice);
1766 CHECK_READABLE(read, Q_VOID);
1767
1768 if (d->transactionStarted) {
1769 checkWarnMessage(this, "ungetChar", "Called while transaction is in progress");
1770 return;
1771 }
1772
1773#if defined QIODEVICE_DEBUG
1774 printf("%p QIODevice::ungetChar(0x%hhx '%c')\n", this, c, isprint(c) ? c : '?');
1775#endif
1776
1777 d->buffer.ungetChar(c);
1778 if (!d->isSequential())
1779 --d->pos;
1780}
1781
1782/*! \fn bool QIODevice::putChar(char c)
1783
1784 Writes the character \a c to the device. Returns \c true on success;
1785 otherwise returns \c false.
1786
1787 \sa write(), getChar(), ungetChar()
1788*/
1789bool QIODevice::putChar(char c)
1790{
1791 return d_func()->putCharHelper(c);
1792}
1793
1794/*!
1795 \internal
1796*/
1797bool QIODevicePrivate::putCharHelper(char c)
1798{
1799 return q_func()->write(&c, 1) == 1;
1800}
1801
1802/*!
1803 \internal
1804*/
1805qint64 QIODevicePrivate::peek(char *data, qint64 maxSize)
1806{
1807 return read(data, maxSize, true);
1808}
1809
1810/*!
1811 \internal
1812*/
1813QByteArray QIODevicePrivate::peek(qint64 maxSize)
1814{
1815 QByteArray result(maxSize, Qt::Uninitialized);
1816
1817 const qint64 readBytes = read(result.data(), maxSize, true);
1818
1819 if (readBytes < maxSize) {
1820 if (readBytes <= 0)
1821 result.clear();
1822 else
1823 result.resize(readBytes);
1824 }
1825
1826 return result;
1827}
1828
1829/*! \fn bool QIODevice::getChar(char *c)
1830
1831 Reads one character from the device and stores it in \a c. If \a c
1832 is 0, the character is discarded. Returns \c true on success;
1833 otherwise returns \c false.
1834
1835 \sa read(), putChar(), ungetChar()
1836*/
1837bool QIODevice::getChar(char *c)
1838{
1839 // readability checked in read()
1840 char ch;
1841 return (1 == read(c ? c : &ch, 1));
1842}
1843
1844/*!
1845 \since 4.1
1846
1847 Reads at most \a maxSize bytes from the device into \a data, without side
1848 effects (i.e., if you call read() after peek(), you will get the same
1849 data). Returns the number of bytes read. If an error occurs, such as
1850 when attempting to peek a device opened in WriteOnly mode, this function
1851 returns -1.
1852
1853 0 is returned when no more data is available for reading.
1854
1855 Example:
1856
1857 \snippet code/src_corelib_io_qiodevice.cpp 4
1858
1859 \sa read()
1860*/
1861qint64 QIODevice::peek(char *data, qint64 maxSize)
1862{
1863 Q_D(QIODevice);
1864
1865 CHECK_MAXLEN(peek, qint64(-1));
1866 CHECK_READABLE(peek, qint64(-1));
1867
1868 return d->peek(data, maxSize);
1869}
1870
1871/*!
1872 \since 4.1
1873 \overload
1874
1875 Peeks at most \a maxSize bytes from the device, returning the data peeked
1876 as a QByteArray.
1877
1878 Example:
1879
1880 \snippet code/src_corelib_io_qiodevice.cpp 5
1881
1882 This function has no way of reporting errors; returning an empty
1883 QByteArray can mean either that no data was currently available
1884 for peeking, or that an error occurred.
1885
1886 \sa read()
1887*/
1888QByteArray QIODevice::peek(qint64 maxSize)
1889{
1890 Q_D(QIODevice);
1891
1892 CHECK_MAXLEN(peek, QByteArray());
1893 CHECK_MAXBYTEARRAYSIZE(peek);
1894 CHECK_READABLE(peek, QByteArray());
1895
1896 return d->peek(maxSize);
1897}
1898
1899/*!
1900 \since 5.10
1901
1902 Skips up to \a maxSize bytes from the device. Returns the number of bytes
1903 actually skipped, or -1 on error.
1904
1905 This function does not wait and only discards the data that is already
1906 available for reading.
1907
1908 If the device is opened in text mode, end-of-line terminators are
1909 translated to '\n' symbols and count as a single byte identically to the
1910 read() and peek() behavior.
1911
1912 This function works for all devices, including sequential ones that cannot
1913 seek(). It is optimized to skip unwanted data after a peek() call.
1914
1915 For random-access devices, skip() can be used to seek forward from the
1916 current position. Negative \a maxSize values are not allowed.
1917
1918 \sa peek(), seek(), read()
1919*/
1920qint64 QIODevice::skip(qint64 maxSize)
1921{
1922 Q_D(QIODevice);
1923 CHECK_MAXLEN(skip, qint64(-1));
1924 CHECK_READABLE(skip, qint64(-1));
1925
1926 const bool sequential = d->isSequential();
1927
1928#if defined QIODEVICE_DEBUG
1929 printf("%p QIODevice::skip(%lld), d->pos = %lld, d->buffer.size() = %lld\n",
1930 this, maxSize, d->pos, d->buffer.size());
1931#endif
1932
1933 if ((sequential && d->transactionStarted) || (d->openMode & QIODevice::Text) != 0)
1934 return d->skipByReading(maxSize);
1935
1936 // First, skip over any data in the internal buffer.
1937 qint64 skippedSoFar = 0;
1938 if (!d->buffer.isEmpty()) {
1939 skippedSoFar = d->buffer.skip(maxSize);
1940#if defined QIODEVICE_DEBUG
1941 printf("%p \tskipping %lld bytes in buffer\n", this, skippedSoFar);
1942#endif
1943 if (!sequential)
1944 d->pos += skippedSoFar;
1945 if (d->buffer.isEmpty())
1946 readData(nullptr, 0);
1947 if (skippedSoFar == maxSize)
1948 return skippedSoFar;
1949
1950 maxSize -= skippedSoFar;
1951 }
1952
1953 // Try to seek on random-access device. At this point,
1954 // the internal read buffer is empty.
1955 if (!sequential) {
1956 const qint64 bytesToSkip = qMin(size() - d->pos, maxSize);
1957
1958 // If the size is unknown or file position is at the end,
1959 // fall back to reading below.
1960 if (bytesToSkip > 0) {
1961 if (!seek(d->pos + bytesToSkip))
1962 return skippedSoFar ? skippedSoFar : Q_INT64_C(-1);
1963 if (bytesToSkip == maxSize)
1964 return skippedSoFar + bytesToSkip;
1965
1966 skippedSoFar += bytesToSkip;
1967 maxSize -= bytesToSkip;
1968 }
1969 }
1970
1971 const qint64 skipResult = d->skip(maxSize);
1972 if (skippedSoFar == 0)
1973 return skipResult;
1974
1975 if (skipResult == -1)
1976 return skippedSoFar;
1977
1978 return skippedSoFar + skipResult;
1979}
1980
1981/*!
1982 \internal
1983*/
1984qint64 QIODevicePrivate::skipByReading(qint64 maxSize)
1985{
1986 qint64 readSoFar = 0;
1987 do {
1988 char dummy[4096];
1989 const qint64 readBytes = qMin<qint64>(maxSize, sizeof(dummy));
1990 const qint64 readResult = read(dummy, readBytes);
1991
1992 // Do not try again, if we got less data.
1993 if (readResult != readBytes) {
1994 if (readSoFar == 0)
1995 return readResult;
1996
1997 if (readResult == -1)
1998 return readSoFar;
1999
2000 return readSoFar + readResult;
2001 }
2002
2003 readSoFar += readResult;
2004 maxSize -= readResult;
2005 } while (maxSize > 0);
2006
2007 return readSoFar;
2008}
2009
2010/*!
2011 \internal
2012*/
2013qint64 QIODevicePrivate::skip(qint64 maxSize)
2014{
2015 // Base implementation discards the data by reading into the dummy buffer.
2016 // It's slow, but this works for all types of devices. Subclasses can
2017 // reimplement this function to improve on that.
2018 return skipByReading(maxSize);
2019}
2020
2021/*!
2022 Blocks until new data is available for reading and the readyRead()
2023 signal has been emitted, or until \a msecs milliseconds have
2024 passed. If msecs is -1, this function will not time out.
2025
2026 Returns \c true if new data is available for reading; otherwise returns
2027 false (if the operation timed out or if an error occurred).
2028
2029 This function can operate without an event loop. It is
2030 useful when writing non-GUI applications and when performing
2031 I/O operations in a non-GUI thread.
2032
2033 If called from within a slot connected to the readyRead() signal,
2034 readyRead() will not be reemitted.
2035
2036 Reimplement this function to provide a blocking API for a custom
2037 device. The default implementation does nothing, and returns \c false.
2038
2039 \warning Calling this function from the main (GUI) thread
2040 might cause your user interface to freeze.
2041
2042 \sa waitForBytesWritten()
2043*/
2044bool QIODevice::waitForReadyRead(int msecs)
2045{
2046 Q_UNUSED(msecs);
2047 return false;
2048}
2049
2050/*!
2051 For buffered devices, this function waits until a payload of
2052 buffered written data has been written to the device and the
2053 bytesWritten() signal has been emitted, or until \a msecs
2054 milliseconds have passed. If msecs is -1, this function will
2055 not time out. For unbuffered devices, it returns immediately.
2056
2057 Returns \c true if a payload of data was written to the device;
2058 otherwise returns \c false (i.e. if the operation timed out, or if an
2059 error occurred).
2060
2061 This function can operate without an event loop. It is
2062 useful when writing non-GUI applications and when performing
2063 I/O operations in a non-GUI thread.
2064
2065 If called from within a slot connected to the bytesWritten() signal,
2066 bytesWritten() will not be reemitted.
2067
2068 Reimplement this function to provide a blocking API for a custom
2069 device. The default implementation does nothing, and returns \c false.
2070
2071 \warning Calling this function from the main (GUI) thread
2072 might cause your user interface to freeze.
2073
2074 \sa waitForReadyRead()
2075*/
2076bool QIODevice::waitForBytesWritten(int msecs)
2077{
2078 Q_UNUSED(msecs);
2079 return false;
2080}
2081
2082/*!
2083 Sets the human readable description of the last device error that
2084 occurred to \a str.
2085
2086 \sa errorString()
2087*/
2088void QIODevice::setErrorString(const QString &str)
2089{
2090 d_func()->errorString = str;
2091}
2092
2093/*!
2094 Returns a human-readable description of the last device error that
2095 occurred.
2096
2097 \sa setErrorString()
2098*/
2099QString QIODevice::errorString() const
2100{
2101 Q_D(const QIODevice);
2102 if (d->errorString.isEmpty()) {
2103#ifdef QT_NO_QOBJECT
2104 return QLatin1String(QT_TRANSLATE_NOOP(QIODevice, "Unknown error"));
2105#else
2106 return tr("Unknown error");
2107#endif
2108 }
2109 return d->errorString;
2110}
2111
2112/*!
2113 \fn qint64 QIODevice::readData(char *data, qint64 maxSize)
2114
2115 Reads up to \a maxSize bytes from the device into \a data, and
2116 returns the number of bytes read or -1 if an error occurred.
2117
2118 If there are no bytes to be read and there can never be more bytes
2119 available (examples include socket closed, pipe closed, sub-process
2120 finished), this function returns -1.
2121
2122 This function is called by QIODevice. Reimplement this function
2123 when creating a subclass of QIODevice.
2124
2125 When reimplementing this function it is important that this function
2126 reads all the required data before returning. This is required in order
2127 for QDataStream to be able to operate on the class. QDataStream assumes
2128 all the requested information was read and therefore does not retry reading
2129 if there was a problem.
2130
2131 This function might be called with a maxSize of 0, which can be used to
2132 perform post-reading operations.
2133
2134 \sa read(), readLine(), writeData()
2135*/
2136
2137/*!
2138 \fn qint64 QIODevice::writeData(const char *data, qint64 maxSize)
2139
2140 Writes up to \a maxSize bytes from \a data to the device. Returns
2141 the number of bytes written, or -1 if an error occurred.
2142
2143 This function is called by QIODevice. Reimplement this function
2144 when creating a subclass of QIODevice.
2145
2146 When reimplementing this function it is important that this function
2147 writes all the data available before returning. This is required in order
2148 for QDataStream to be able to operate on the class. QDataStream assumes
2149 all the information was written and therefore does not retry writing if
2150 there was a problem.
2151
2152 \sa read(), write()
2153*/
2154
2155/*!
2156 \internal
2157 \fn int qt_subtract_from_timeout(int timeout, int elapsed)
2158
2159 Reduces the \a timeout by \a elapsed, taking into account that -1 is a
2160 special value for timeouts.
2161*/
2162
2163int qt_subtract_from_timeout(int timeout, int elapsed)
2164{
2165 if (timeout == -1)
2166 return -1;
2167
2168 timeout = timeout - elapsed;
2169 return timeout < 0 ? 0 : timeout;
2170}
2171
2172
2173#if !defined(QT_NO_DEBUG_STREAM)
2174QDebug operator<<(QDebug debug, QIODevice::OpenMode modes)
2175{
2176 debug << "OpenMode(";
2177 QStringList modeList;
2178 if (modes == QIODevice::NotOpen) {
2179 modeList << QLatin1String("NotOpen");
2180 } else {
2181 if (modes & QIODevice::ReadOnly)
2182 modeList << QLatin1String("ReadOnly");
2183 if (modes & QIODevice::WriteOnly)
2184 modeList << QLatin1String("WriteOnly");
2185 if (modes & QIODevice::Append)
2186 modeList << QLatin1String("Append");
2187 if (modes & QIODevice::Truncate)
2188 modeList << QLatin1String("Truncate");
2189 if (modes & QIODevice::Text)
2190 modeList << QLatin1String("Text");
2191 if (modes & QIODevice::Unbuffered)
2192 modeList << QLatin1String("Unbuffered");
2193 }
2194 std::sort(modeList.begin(), modeList.end());
2195 debug << modeList.join(QLatin1Char('|'));
2196 debug << ')';
2197 return debug;
2198}
2199#endif
2200
2201QT_END_NAMESPACE
2202
2203#ifndef QT_NO_QOBJECT
2204#include "moc_qiodevice.cpp"
2205#endif
2206