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