Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qbuffer.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:data-parser
4
5#include "qbuffer.h"
6#include <QtCore/qmetaobject.h>
7#include "private/qiodevice_p.h"
8
9#include <limits>
10#include <utility>
11
12QT_BEGIN_NAMESPACE
13
14/** QBufferPrivate **/
15class QBufferPrivate : public QIODevicePrivate
16{
17 Q_DECLARE_PUBLIC(QBuffer)
18
19public:
20 QBufferPrivate() = default;
21
22 QByteArray *buf = nullptr;
23 QByteArray defaultBuf;
24
25 qint64 peek(char *data, qint64 maxSize) override;
26 QByteArray peek(qint64 maxSize) override;
27
28#ifndef QT_NO_QOBJECT
29 qint64 writtenSinceLastEmit = 0;
30 int signalConnectionCount = 0;
31 bool signalsEmitted = false;
32#endif
33};
34
35qint64 QBufferPrivate::peek(char *data, qint64 maxSize)
36{
37 qint64 readBytes = qMin(maxSize, static_cast<qint64>(buf->size()) - pos);
38 memcpy(data, buf->constData() + pos, readBytes);
39 return readBytes;
40}
41
42QByteArray QBufferPrivate::peek(qint64 maxSize)
43{
44 qint64 readBytes = qMin(maxSize, static_cast<qint64>(buf->size()) - pos);
45 if (pos == 0 && maxSize >= buf->size())
46 return *buf;
47 return QByteArray(buf->constData() + pos, readBytes);
48}
49
50/*!
51 \class QBuffer
52 \inmodule QtCore
53 \reentrant
54 \brief The QBuffer class provides a QIODevice interface for a QByteArray.
55
56 \ingroup io
57
58 QBuffer allows you to access a QByteArray using the QIODevice
59 interface. The QByteArray is treated just as a standard random-accessed
60 file. Example:
61
62 \snippet buffer/buffer.cpp 0
63
64 By default, an internal QByteArray buffer is created for you when
65 you create a QBuffer. You can access this buffer directly by
66 calling buffer(). You can also use QBuffer with an existing
67 QByteArray by calling setBuffer(), or by passing your array to
68 QBuffer's constructor.
69
70 Call open() to open the buffer. Then call write() or
71 putChar() to write to the buffer, and read(), readLine(),
72 readAll(), or getChar() to read from it. size() returns the
73 current size of the buffer, and you can seek to arbitrary
74 positions in the buffer by calling seek(). When you are done with
75 accessing the buffer, call close().
76
77 The following code snippet shows how to write data to a
78 QByteArray using QDataStream and QBuffer:
79
80 \snippet buffer/buffer.cpp 1
81
82 Effectively, we convert the application's QPalette into a byte
83 array. Here's how to read the data from the QByteArray:
84
85 \snippet buffer/buffer.cpp 2
86
87 QTextStream and QDataStream also provide convenience constructors
88 that take a QByteArray and that create a QBuffer behind the
89 scenes.
90
91 QBuffer emits readyRead() when new data has arrived in the
92 buffer. By connecting to this signal, you can use QBuffer to
93 store temporary data before processing it. QBuffer also emits
94 bytesWritten() every time new data has been written to the buffer.
95
96 \sa QFile, QDataStream, QTextStream, QByteArray
97*/
98
99#ifdef QT_NO_QOBJECT
100QBuffer::QBuffer()
101 : QIODevice(*new QBufferPrivate)
102{
103 Q_D(QBuffer);
104 d->buf = &d->defaultBuf;
105}
106QBuffer::QBuffer(QByteArray *buf)
107 : QIODevice(*new QBufferPrivate)
108{
109 Q_D(QBuffer);
110 d->buf = buf ? buf : &d->defaultBuf;
111 d->defaultBuf.clear();
112}
113#else
114/*!
115 Constructs an empty buffer with the given \a parent. You can call
116 setData() to fill the buffer with data, or you can open it in
117 write mode and use write().
118
119 \sa open()
120*/
121QBuffer::QBuffer(QObject *parent)
122 : QIODevice(*new QBufferPrivate, parent)
123{
124 Q_D(QBuffer);
125 d->buf = &d->defaultBuf;
126}
127
128/*!
129 Constructs a QBuffer that uses the QByteArray pointed to by \a
130 byteArray as its internal buffer, and with the given \a parent.
131 The caller is responsible for ensuring that \a byteArray remains
132 valid until the QBuffer is destroyed, or until setBuffer() is
133 called to change the buffer. QBuffer doesn't take ownership of
134 the QByteArray.
135
136 If you open the buffer in write-only mode or read-write mode and
137 write something into the QBuffer, \a byteArray will be modified.
138
139 Example:
140
141 \snippet buffer/buffer.cpp 3
142
143 \sa open(), setBuffer(), setData()
144*/
145QBuffer::QBuffer(QByteArray *byteArray, QObject *parent)
146 : QIODevice(*new QBufferPrivate, parent)
147{
148 Q_D(QBuffer);
149 d->buf = byteArray ? byteArray : &d->defaultBuf;
150 d->defaultBuf.clear();
151}
152#endif
153
154/*!
155 Destroys the buffer.
156*/
157
158QBuffer::~QBuffer()
159{
160}
161
162/*!
163 Makes QBuffer use the QByteArray pointed to by \a
164 byteArray as its internal buffer. The caller is responsible for
165 ensuring that \a byteArray remains valid until the QBuffer is
166 destroyed, or until setBuffer() is called to change the buffer.
167 QBuffer doesn't take ownership of the QByteArray.
168
169 Does nothing if isOpen() is true.
170
171 If you open the buffer in write-only mode or read-write mode and
172 write something into the QBuffer, \a byteArray will be modified.
173
174 Example:
175
176 \snippet buffer/buffer.cpp 4
177
178 If \a byteArray is \nullptr, the buffer creates its own internal
179 QByteArray to work on. This byte array is initially empty.
180
181 \sa buffer(), setData(), open()
182*/
183
184void QBuffer::setBuffer(QByteArray *byteArray)
185{
186 Q_D(QBuffer);
187 if (isOpen()) {
188 qWarning("QBuffer::setBuffer: Buffer is open");
189 return;
190 }
191 if (byteArray) {
192 d->buf = byteArray;
193 } else {
194 d->buf = &d->defaultBuf;
195 }
196 d->defaultBuf.clear();
197}
198
199/*!
200 Returns a reference to the QBuffer's internal buffer. You can use
201 it to modify the QByteArray behind the QBuffer's back.
202
203 \sa setBuffer(), data()
204*/
205
206QByteArray &QBuffer::buffer()
207{
208 Q_D(QBuffer);
209 return *d->buf;
210}
211
212/*!
213 \overload
214
215 This is the same as data().
216*/
217
218const QByteArray &QBuffer::buffer() const
219{
220 Q_D(const QBuffer);
221 return *d->buf;
222}
223
224
225/*!
226 Returns the data contained in the buffer.
227
228 This is the same as buffer().
229
230 \sa setData(), setBuffer()
231*/
232
233const QByteArray &QBuffer::data() const
234{
235 Q_D(const QBuffer);
236 return *d->buf;
237}
238
239/*!
240 Sets the contents of the internal buffer to be \a data. This is
241 the same as assigning \a data to buffer().
242
243 Does nothing if isOpen() is true.
244
245 \sa setBuffer()
246*/
247void QBuffer::setData(const QByteArray &data)
248{
249 Q_D(QBuffer);
250 if (isOpen()) {
251 qWarning("QBuffer::setData: Buffer is open");
252 return;
253 }
254 *d->buf = data;
255}
256
257/*!
258 \overload
259
260 Sets the contents of the internal buffer to be the first \a size
261 bytes of \a data.
262
263 \note In Qt versions prior to 6.5, this function took the length as
264 an \c{int} parameter, potentially truncating sizes.
265*/
266void QBuffer::setData(const char *data, qsizetype size)
267{
268 Q_D(QBuffer);
269 if (isOpen()) {
270 qWarning("QBuffer::setData: Buffer is open");
271 return;
272 }
273 d->buf->assign(data, data + size);
274}
275
276/*!
277 Opens the buffer using \a mode flags, returning \c true if successful;
278 otherwise returns \c false.
279
280 The flags for \a mode must include \l QIODeviceBase::ReadOnly,
281 \l WriteOnly, or \l ReadWrite. If not, an error is printed and
282 the method fails. In any other case, it succeeds.
283
284 Unlike \l QFile::open(), opening a QBuffer with \l WriteOnly
285 does not truncate it. However, \l pos() is set to \c{0}.
286 Use \l Append or \l Truncate to change either behavior.
287*/
288bool QBuffer::open(OpenMode mode)
289{
290 Q_D(QBuffer);
291
292 if ((mode & (Append | Truncate)) != 0)
293 mode |= WriteOnly;
294 if ((mode & (ReadOnly | WriteOnly)) == 0) {
295 qWarning("QBuffer::open: Buffer access not specified");
296 return false;
297 }
298
299 if ((mode & Truncate) == Truncate)
300 d->buf->resize(0);
301
302 return QIODevice::open(mode | QIODevice::Unbuffered);
303}
304
305/*!
306 \reimp
307*/
308void QBuffer::close()
309{
310 QIODevice::close();
311}
312
313/*!
314 \reimp
315*/
316qint64 QBuffer::pos() const
317{
318 return QIODevice::pos();
319}
320
321/*!
322 \reimp
323*/
324qint64 QBuffer::size() const
325{
326 Q_D(const QBuffer);
327 return qint64(d->buf->size());
328}
329
330/*!
331 \reimp
332*/
333bool QBuffer::seek(qint64 pos)
334{
335 Q_D(QBuffer);
336 const auto oldBufSize = d->buf->size();
337 constexpr qint64 MaxSeekPos = (std::numeric_limits<decltype(oldBufSize)>::max)();
338 if (pos <= MaxSeekPos && pos > oldBufSize && isWritable()) {
339 QT_TRY {
340 d->buf->resize(qsizetype(pos), '\0');
341 } QT_CATCH(const std::bad_alloc &) {} // swallow, failure case is handled below
342 if (d->buf->size() != pos) {
343 qWarning("QBuffer::seek: Unable to fill gap");
344 return false;
345 }
346 }
347 if (pos > d->buf->size() || pos < 0) {
348 qWarning("QBuffer::seek: Invalid pos: %lld", pos);
349 return false;
350 }
351 return QIODevice::seek(pos);
352}
353
354/*!
355 \reimp
356*/
357bool QBuffer::atEnd() const
358{
359 return QIODevice::atEnd();
360}
361
362/*!
363 \reimp
364*/
365bool QBuffer::canReadLine() const
366{
367 Q_D(const QBuffer);
368 if (!isOpen())
369 return false;
370
371 return d->buf->indexOf('\n', int(pos())) != -1 || QIODevice::canReadLine();
372}
373
374/*!
375 \reimp
376*/
377qint64 QBuffer::readData(char *data, qint64 len)
378{
379 Q_D(QBuffer);
380 if ((len = qMin(len, qint64(d->buf->size()) - pos())) <= 0)
381 return qint64(0);
382 memcpy(data, d->buf->constData() + pos(), len);
383 return len;
384}
385
386/*!
387 \reimp
388*/
389qint64 QBuffer::writeData(const char *data, qint64 len)
390{
391 Q_D(QBuffer);
392 const quint64 required = quint64(pos()) + quint64(len); // cannot overflow (pos() ≥ 0, len ≥ 0)
393
394 if (required > quint64(d->buf->size())) { // capacity exceeded
395 // The following must hold, since qsizetype covers half the virtual address space:
396 Q_ASSERT(required <= quint64((std::numeric_limits<qsizetype>::max)()));
397 d->buf->resize(qsizetype(required));
398 if (quint64(d->buf->size()) != required) { // could not resize
399 qWarning("QBuffer::writeData: Memory allocation error");
400 return -1;
401 }
402 }
403
404 memcpy(d->buf->data() + pos(), data, size_t(len));
405
406#ifndef QT_NO_QOBJECT
407 d->writtenSinceLastEmit += len;
408 if (d->signalConnectionCount && !d->signalsEmitted && !signalsBlocked()) {
409 d->signalsEmitted = true;
410 QMetaObject::invokeMethod(this, [](QBuffer *q) {
411 auto d = q->d_func();
412 const qint64 written = std::exchange(d->writtenSinceLastEmit, 0);
413 emit q->bytesWritten(written);
414 emit q->channelBytesWritten(0, written);
415 emit q->readyRead();
416 emit q->channelReadyRead(0);
417 d->signalsEmitted = false;
418 }, Qt::QueuedConnection, this);
419 }
420#endif
421 return len;
422}
423
424#ifndef QT_NO_QOBJECT
425static bool is_tracked_signal(const QMetaMethod &signal)
426{
427 // dynamic initialization: minimize the number of guard variables:
428 static const struct {
429 QMetaMethod readyReadSignal = QMetaMethod::fromSignal(&QBuffer::readyRead);
430 QMetaMethod bytesWrittenSignal = QMetaMethod::fromSignal(&QBuffer::bytesWritten);
431 QMetaMethod channelReadyReadSignal = QMetaMethod::fromSignal(&QBuffer::channelReadyRead);
432 QMetaMethod channelBytesWrittenSignal =
433 QMetaMethod::fromSignal(&QBuffer::channelBytesWritten);
434 } sigs;
435 return signal == sigs.readyReadSignal || signal == sigs.bytesWrittenSignal
436 || signal == sigs.channelReadyReadSignal || signal == sigs.channelBytesWrittenSignal;
437}
438/*!
439 \reimp
440 \internal
441*/
442void QBuffer::connectNotify(const QMetaMethod &signal)
443{
444 if (is_tracked_signal(signal))
445 d_func()->signalConnectionCount++;
446}
447
448/*!
449 \reimp
450 \internal
451*/
452void QBuffer::disconnectNotify(const QMetaMethod &signal)
453{
454 if (signal.isValid()) {
455 if (is_tracked_signal(signal))
456 d_func()->signalConnectionCount--;
457 } else {
458 d_func()->signalConnectionCount = 0;
459 }
460}
461#endif
462
463QT_END_NAMESPACE
464
465#ifndef QT_NO_QOBJECT
466# include "moc_qbuffer.cpp"
467#endif
static bool is_tracked_signal(const QMetaMethod &signal)
Definition qbuffer.cpp:425