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

source code of qtbase/src/corelib/io/qiodevice.cpp