From 787d178b19587731fa9e78d37a053bd75308eba6 Mon Sep 17 00:00:00 2001 From: Marc Mutz Date: Mon, 4 Apr 2022 16:49:03 +0200 Subject: [PATCH] QBuffer: optimize seek()-past-end-of-buffer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Use new QByteArray::resize(n, ch) method to resize the buffer directly, instead of first allocating a QByteArray full of NULs and then using public write() API to append it. Change-Id: Ibdb082b970de0ba24534a570ecb23304c5f1470c Reviewed-by: Qt CI Bot Reviewed-by: MÃ¥rten Nordheim Reviewed-by: Thiago Macieira Reviewed-by: Oswald Buddenhagen --- src/corelib/io/qbuffer.cpp | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/corelib/io/qbuffer.cpp b/src/corelib/io/qbuffer.cpp index 2b53f09796..8e1888d893 100644 --- a/src/corelib/io/qbuffer.cpp +++ b/src/corelib/io/qbuffer.cpp @@ -363,16 +363,15 @@ bool QBuffer::seek(qint64 pos) const auto oldBufSize = d->buf->size(); constexpr qint64 MaxSeekPos = (std::numeric_limits::max)(); if (pos <= MaxSeekPos && pos > oldBufSize && isWritable()) { - if (seek(d->buf->size())) { - const qint64 gapSize = pos - d->buf->size(); - if (write(QByteArray(gapSize, 0)) != gapSize) { - qWarning("QBuffer::seek: Unable to fill gap"); - return false; - } - } else { + QT_TRY { + d->buf->resize(qsizetype(pos), '\0'); + } QT_CATCH(const std::bad_alloc &) {} // swallow, failure case is handled below + if (d->buf->size() != pos) { + qWarning("QBuffer::seek: Unable to fill gap"); return false; } - } else if (pos > d->buf->size() || pos < 0) { + } + if (pos > d->buf->size() || pos < 0) { qWarning("QBuffer::seek: Invalid pos: %lld", pos); return false; }