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