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

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