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