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