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